From ed4245ce319d40dcb8d032740f70e3c659e79377 Mon Sep 17 00:00:00 2001 From: OpenApi-Bot Date: Wed, 17 Aug 2022 09:37:26 +0000 Subject: [PATCH] Update to newly built API from GH Run 145 --- Client/Client.csproj | 23 + Client/Com/Cumulocity/Client/Api/AlarmsApi.cs | 470 ++++++++ .../Client/Api/ApplicationBinariesApi.cs | 181 +++ .../Cumulocity/Client/Api/ApplicationsApi.cs | 490 ++++++++ .../Cumulocity/Client/Api/AttachmentsApi.cs | 242 ++++ Client/Com/Cumulocity/Client/Api/AuditsApi.cs | 181 +++ .../Com/Cumulocity/Client/Api/BinariesApi.cs | 248 ++++ .../Cumulocity/Client/Api/BootstrapUserApi.cs | 71 ++ .../Client/Api/BulkOperationsApi.cs | 262 +++++ .../Client/Api/ChildOperationsApi.cs | 1000 +++++++++++++++++ .../Client/Api/CurrentApplicationApi.cs | 186 +++ .../Cumulocity/Client/Api/CurrentUserApi.cs | 115 ++ .../Client/Api/DeviceCredentialsApi.cs | 122 ++ .../Client/Api/DeviceStatisticsApi.cs | 176 +++ Client/Com/Cumulocity/Client/Api/EventsApi.cs | 346 ++++++ .../Cumulocity/Client/Api/ExternalIDsApi.cs | 188 ++++ Client/Com/Cumulocity/Client/Api/GroupsApi.cs | 386 +++++++ .../Com/Cumulocity/Client/Api/IdentityApi.cs | 71 ++ .../Com/Cumulocity/Client/Api/InventoryApi.cs | 70 ++ .../Client/Api/InventoryRolesApi.cs | 479 ++++++++ .../Cumulocity/Client/Api/LoginOptionsApi.cs | 127 +++ .../Cumulocity/Client/Api/LoginTokensApi.cs | 35 + .../Client/Api/ManagedObjectsApi.cs | 574 ++++++++++ .../Cumulocity/Client/Api/MeasurementsApi.cs | 376 +++++++ .../Client/Api/NewDeviceRequestsApi.cs | 243 ++++ .../Cumulocity/Client/Api/OperationsApi.cs | 286 +++++ .../Com/Cumulocity/Client/Api/OptionsApi.cs | 319 ++++++ .../Client/Api/RealtimeNotificationApi.cs | 281 +++++ .../Client/Api/RetentionRulesApi.cs | 267 +++++ Client/Com/Cumulocity/Client/Api/RolesApi.cs | 364 ++++++ .../Cumulocity/Client/Api/SubscriptionsApi.cs | 275 +++++ .../Cumulocity/Client/Api/SystemOptionsApi.cs | 100 ++ .../Client/Api/TenantApplicationsApi.cs | 175 +++ .../Com/Cumulocity/Client/Api/TenantsApi.cs | 337 ++++++ Client/Com/Cumulocity/Client/Api/TokensApi.cs | 78 ++ .../Client/Api/UsageStatisticsApi.cs | 395 +++++++ Client/Com/Cumulocity/Client/Api/UsersApi.cs | 526 +++++++++ .../Cumulocity/Client/Model/AccessToken.cs | 33 + Client/Com/Cumulocity/Client/Model/Alarm.cs | 259 +++++ .../Client/Model/AlarmCollection.cs | 57 + .../Client/Model/AlarmsApiResource.cs | 102 ++ .../Cumulocity/Client/Model/Application.cs | 196 ++++ .../Client/Model/ApplicationApiResource.cs | 66 ++ .../Client/Model/ApplicationBinaries.cs | 84 ++ .../Client/Model/ApplicationCollection.cs | 57 + .../Client/Model/ApplicationManifestProbe.cs | 84 ++ .../Client/Model/ApplicationOwner.cs | 51 + .../Client/Model/ApplicationReference.cs | 33 + .../Model/ApplicationReferenceCollection.cs | 57 + .../Client/Model/ApplicationSettings.cs | 72 ++ .../Client/Model/ApplicationUserCollection.cs | 63 ++ .../Client/Model/AuditApiResource.cs | 102 ++ .../Cumulocity/Client/Model/AuditRecord.cs | 404 +++++++ .../Client/Model/AuditRecordCollection.cs | 57 + .../Com/Cumulocity/Client/Model/AuthConfig.cs | 536 +++++++++ .../Model/BasicAuthenticationRestrictions.cs | 48 + Client/Com/Cumulocity/Client/Model/Binary.cs | 90 ++ .../Client/Model/BinaryCollection.cs | 57 + .../Com/Cumulocity/Client/Model/BinaryInfo.cs | 39 + .../Cumulocity/Client/Model/BootstrapUser.cs | 42 + .../Client/Model/BulkNewDeviceRequest.cs | 149 +++ .../Cumulocity/Client/Model/BulkOperation.cs | 178 +++ .../Client/Model/BulkOperationCollection.cs | 57 + .../Model/C8yAccelerationMeasurement.cs | 33 + .../Client/Model/C8yAccelerationSensor.cs | 27 + .../Client/Model/C8yActiveAlarmsStatus.cs | 39 + .../Com/Cumulocity/Client/Model/C8yAgent.cs | 55 + .../Client/Model/C8yAvailability.cs | 39 + .../Client/Model/C8yAvailabilityStatus.cs | 30 + .../Cumulocity/Client/Model/C8yCellInfo.cs | 51 + .../Cumulocity/Client/Model/C8yCellTower.cs | 93 ++ .../Com/Cumulocity/Client/Model/C8yCommand.cs | 39 + .../Client/Model/C8yCommunicationMode.cs | 30 + .../Client/Model/C8yConfiguration.cs | 36 + .../Cumulocity/Client/Model/C8yConnection.cs | 33 + .../Client/Model/C8yCurrentMeasurement.cs | 33 + .../Client/Model/C8yCurrentSensor.cs | 27 + .../Client/Model/C8yDistanceMeasurement.cs | 33 + .../Client/Model/C8yDistanceSensor.cs | 27 + .../Cumulocity/Client/Model/C8yFirmware.cs | 45 + .../Cumulocity/Client/Model/C8yHardware.cs | 45 + .../Client/Model/C8yHumidityMeasurement.cs | 36 + .../Client/Model/C8yHumiditySensor.cs | 27 + .../Client/Model/C8yLightMeasurement.cs | 36 + .../Cumulocity/Client/Model/C8yLightSensor.cs | 27 + .../Client/Model/C8yLogfileRequest.cs | 63 ++ .../Client/Model/C8yMeasurementValue.cs | 33 + .../Com/Cumulocity/Client/Model/C8yMobile.cs | 66 ++ .../Client/Model/C8yMoistureMeasurement.cs | 36 + .../Client/Model/C8yMoistureSensor.cs | 27 + .../Client/Model/C8yMotionMeasurement.cs | 57 + .../Client/Model/C8yMotionSensor.cs | 27 + .../Com/Cumulocity/Client/Model/C8yNetwork.cs | 195 ++++ .../Cumulocity/Client/Model/C8yPosition.cs | 54 + .../Com/Cumulocity/Client/Model/C8yProfile.cs | 45 + .../Client/Model/C8yRequiredAvailability.cs | 33 + .../Model/C8ySinglePhaseElectricitySensor.cs | 27 + .../Model/C8ySinglePhaseEnergyMeasurement.cs | 33 + .../Client/Model/C8ySoftwareList.cs | 45 + .../Com/Cumulocity/Client/Model/C8ySteam.cs | 60 + .../Client/Model/C8yTemperatureMeasurement.cs | 33 + .../Client/Model/C8yTemperatureSensor.cs | 27 + .../Model/C8yThreePhaseElectricitySensor.cs | 27 + .../Model/C8yThreePhaseEnergyMeasurement.cs | 33 + .../Client/Model/C8yVoltageMeasurement.cs | 33 + .../Client/Model/CategoryKeyOption.cs | 30 + .../Client/Model/CategoryOptions.cs | 120 ++ .../Model/ChildOperationsAddMultiple.cs | 78 ++ .../Client/Model/ChildOperationsAddOne.cs | 60 + .../Client/Model/ComCumulocityModelAgent.cs | 27 + .../Cumulocity/Client/Model/CurrentTenant.cs | 81 ++ .../Cumulocity/Client/Model/CurrentUser.cs | 104 ++ .../Client/Model/CustomProperties.cs | 130 +++ .../Client/Model/DailyUsageStatistics.cs | 152 +++ .../Client/Model/DeviceControlApiResource.cs | 93 ++ .../Client/Model/DeviceCredentials.cs | 54 + .../Client/Model/DevicePermissions.cs | 27 + .../Client/Model/DeviceStatistics.cs | 54 + .../Model/DeviceStatisticsCollection.cs | 54 + Client/Com/Cumulocity/Client/Model/Error.cs | 42 + Client/Com/Cumulocity/Client/Model/Event.cs | 195 ++++ .../Cumulocity/Client/Model/EventBinary.cs | 48 + .../Client/Model/EventCollection.cs | 57 + .../Client/Model/EventsApiResource.cs | 96 ++ .../Com/Cumulocity/Client/Model/ExternalId.cs | 82 ++ .../Cumulocity/Client/Model/ExternalIds.cs | 39 + Client/Com/Cumulocity/Client/Model/Group.cs | 146 +++ .../Cumulocity/Client/Model/GroupReference.cs | 33 + .../Client/Model/GroupReferenceCollection.cs | 57 + .../Client/Model/IdentityApiResource.cs | 42 + .../Client/Model/InventoryApiResource.cs | 81 ++ .../Client/Model/InventoryAssignment.cs | 54 + .../Model/InventoryAssignmentCollection.cs | 39 + .../Model/InventoryAssignmentReference.cs | 51 + .../Cumulocity/Client/Model/InventoryRole.cs | 60 + .../Client/Model/InventoryRoleCollection.cs | 57 + .../Client/Model/InventoryRolePermission.cs | 91 ++ .../Model/JSONPredicateRepresentation.cs | 82 ++ .../Com/Cumulocity/Client/Model/LoginForm.cs | 70 ++ .../Cumulocity/Client/Model/LoginOption.cs | 133 +++ .../Client/Model/LoginOptionCollection.cs | 42 + .../Cumulocity/Client/Model/ManagedObject.cs | 231 ++++ .../Client/Model/ManagedObjectCollection.cs | 57 + .../Client/Model/ManagedObjectReference.cs | 33 + .../Model/ManagedObjectReferenceCollection.cs | 69 ++ .../Model/ManagedObjectReferenceTuple.cs | 66 ++ .../Client/Model/ManagedObjectUser.cs | 42 + .../Cumulocity/Client/Model/Measurement.cs | 203 ++++ .../Client/Model/MeasurementApiResource.cs | 108 ++ .../Client/Model/MeasurementCollection.cs | 66 ++ .../Client/Model/MeasurementFragmentSeries.cs | 42 + .../Client/Model/MeasurementSeries.cs | 57 + .../Model/MicroserviceApplicationManifest.cs | 338 ++++++ .../Client/Model/NewDeviceRequest.cs | 58 + .../Model/NewDeviceRequestCollection.cs | 57 + .../Client/Model/NotificationApiResource.cs | 78 ++ .../Client/Model/NotificationSubscription.cs | 154 +++ .../NotificationSubscriptionCollection.cs | 57 + .../Client/Model/NotificationToken.cs | 30 + .../Client/Model/NotificationTokenClaims.cs | 52 + .../Client/Model/OAuthSessionConfiguration.cs | 51 + .../Client/Model/ObjectAdditionParents.cs | 42 + .../Client/Model/ObjectAssetParents.cs | 42 + .../Client/Model/ObjectChildAdditions.cs | 48 + .../Client/Model/ObjectChildAssets.cs | 48 + .../Client/Model/ObjectChildDevices.cs | 48 + .../Client/Model/ObjectDeviceParents.cs | 42 + .../Com/Cumulocity/Client/Model/Operation.cs | 204 ++++ .../Client/Model/OperationCollection.cs | 57 + .../Client/Model/OperationReference.cs | 60 + Client/Com/Cumulocity/Client/Model/Option.cs | 51 + .../Client/Model/OptionCollection.cs | 60 + .../Cumulocity/Client/Model/PageStatistics.cs | 54 + .../Client/Model/PlatformApiResource.cs | 57 + .../Client/Model/RangeStatisticsFile.cs | 46 + .../Client/Model/RealtimeNotification.cs | 233 ++++ .../Client/Model/RequestRepresentation.cs | 129 +++ .../Cumulocity/Client/Model/RetentionRule.cs | 96 ++ .../Client/Model/RetentionRuleCollection.cs | 57 + Client/Com/Cumulocity/Client/Model/Role.cs | 45 + .../Cumulocity/Client/Model/RoleReference.cs | 36 + .../Client/Model/RoleReferenceCollection.cs | 51 + .../Cumulocity/Client/Model/StatisticsFile.cs | 83 ++ .../Model/SubscribedApplicationReference.cs | 66 ++ .../Cumulocity/Client/Model/SubscribedRole.cs | 48 + .../Cumulocity/Client/Model/SubscribedUser.cs | 48 + .../Model/SummaryAllTenantsUsageStatistics.cs | 197 ++++ .../Model/SummaryTenantUsageStatistics.cs | 146 +++ .../Client/Model/SupportedMeasurements.cs | 33 + .../Client/Model/SupportedSeries.cs | 33 + .../Cumulocity/Client/Model/SystemOption.cs | 45 + .../Client/Model/SystemOptionCollection.cs | 36 + Client/Com/Cumulocity/Client/Model/Tenant.cs | 187 +++ .../Client/Model/TenantApiResource.cs | 129 +++ .../Client/Model/TenantCollection.cs | 57 + .../Model/TenantUsageStatisticsCollection.cs | 57 + .../TenantUsageStatisticsFileCollection.cs | 60 + .../Client/Model/UsageStatisticsResources.cs | 48 + .../Model/UsageStatisticsResourcesUsedBy.cs | 48 + Client/Com/Cumulocity/Client/Model/User.cs | 231 ++++ .../Client/Model/UserApiResource.cs | 66 ++ .../Cumulocity/Client/Model/UserCollection.cs | 57 + .../Client/Model/UserGroupCollection.cs | 57 + .../Cumulocity/Client/Model/UserReference.cs | 33 + .../Client/Model/UserReferenceCollection.cs | 57 + .../Client/Model/UserRoleCollection.cs | 57 + .../Client/Model/WebApplicationManifest.cs | 55 + .../Client/Supplementary/AdaptableApi.cs | 54 + .../Supplementary/CumulocityCoreLibrary.cs | 133 +++ CumulocityCoreLibrary.sln | 30 + README.md | 60 +- .../Cumulocity/Client/Api/AlarmsApiTest.cs | 60 + .../Client/Api/ApplicationBinariesApiTest.cs | 45 + .../Client/Api/ApplicationsApiTest.cs | 52 + .../Client/Api/AttachmentsApiTest.cs | 45 + .../Cumulocity/Client/Api/AuditsApiTest.cs | 52 + .../Cumulocity/Client/Api/BinariesApiTest.cs | 52 + .../Client/Api/BootstrapUserApiTest.cs | 45 + .../Client/Api/BulkOperationsApiTest.cs | 52 + .../Client/Api/ChildOperationsApiTest.cs | 45 + .../Client/Api/CurrentApplicationApiTest.cs | 68 ++ .../Client/Api/CurrentUserApiTest.cs | 52 + .../Client/Api/DeviceCredentialsApiTest.cs | 45 + .../Client/Api/DeviceStatisticsApiTest.cs | 45 + .../Cumulocity/Client/Api/EventsApiTest.cs | 52 + .../Client/Api/ExternalIDsApiTest.cs | 45 + .../Cumulocity/Client/Api/GroupsApiTest.cs | 45 + .../Cumulocity/Client/Api/IdentityApiTest.cs | 52 + .../Cumulocity/Client/Api/InventoryApiTest.cs | 52 + .../Client/Api/InventoryRolesApiTest.cs | 52 + .../Client/Api/LoginOptionsApiTest.cs | 52 + .../Client/Api/LoginTokensApiTest.cs | 45 + .../Client/Api/ManagedObjectsApiTest.cs | 60 + .../Client/Api/MeasurementsApiTest.cs | 52 + .../Client/Api/NewDeviceRequestsApiTest.cs | 52 + .../Client/Api/OperationsApiTest.cs | 52 + .../Cumulocity/Client/Api/OptionsApiTest.cs | 52 + .../Client/Api/RealtimeNotificationApiTest.cs | 45 + .../Client/Api/RetentionRulesApiTest.cs | 52 + .../Com/Cumulocity/Client/Api/RolesApiTest.cs | 52 + .../Client/Api/SubscriptionsApiTest.cs | 52 + .../Client/Api/SystemOptionsApiTest.cs | 52 + .../Client/Api/TenantApplicationsApiTest.cs | 45 + .../Cumulocity/Client/Api/TenantsApiTest.cs | 60 + .../Cumulocity/Client/Api/TokensApiTest.cs | 45 + .../Client/Api/UsageStatisticsApiTest.cs | 76 ++ .../Com/Cumulocity/Client/Api/UsersApiTest.cs | 45 + .../Client/Supplementary/TestConfiguration.cs | 34 + Test/Test.csproj | 40 + Test/appsettings.test.json | 7 + 250 files changed, 24984 insertions(+), 2 deletions(-) create mode 100644 Client/Client.csproj create mode 100644 Client/Com/Cumulocity/Client/Api/AlarmsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/ApplicationBinariesApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/ApplicationsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/AttachmentsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/AuditsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/BinariesApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/BootstrapUserApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/BulkOperationsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/ChildOperationsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/CurrentApplicationApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/CurrentUserApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/DeviceCredentialsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/DeviceStatisticsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/EventsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/ExternalIDsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/GroupsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/IdentityApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/InventoryApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/InventoryRolesApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/LoginOptionsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/LoginTokensApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/ManagedObjectsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/MeasurementsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/NewDeviceRequestsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/OperationsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/OptionsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/RealtimeNotificationApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/RetentionRulesApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/RolesApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/SubscriptionsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/SystemOptionsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/TenantApplicationsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/TenantsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/TokensApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/UsageStatisticsApi.cs create mode 100644 Client/Com/Cumulocity/Client/Api/UsersApi.cs create mode 100644 Client/Com/Cumulocity/Client/Model/AccessToken.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Alarm.cs create mode 100644 Client/Com/Cumulocity/Client/Model/AlarmCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/AlarmsApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Application.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationBinaries.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationManifestProbe.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationOwner.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationReferenceCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationSettings.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ApplicationUserCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/AuditApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/AuditRecord.cs create mode 100644 Client/Com/Cumulocity/Client/Model/AuditRecordCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/AuthConfig.cs create mode 100644 Client/Com/Cumulocity/Client/Model/BasicAuthenticationRestrictions.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Binary.cs create mode 100644 Client/Com/Cumulocity/Client/Model/BinaryCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/BinaryInfo.cs create mode 100644 Client/Com/Cumulocity/Client/Model/BootstrapUser.cs create mode 100644 Client/Com/Cumulocity/Client/Model/BulkNewDeviceRequest.cs create mode 100644 Client/Com/Cumulocity/Client/Model/BulkOperation.cs create mode 100644 Client/Com/Cumulocity/Client/Model/BulkOperationCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yAccelerationMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yAccelerationSensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yActiveAlarmsStatus.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yAgent.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yAvailability.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yAvailabilityStatus.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yCellInfo.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yCellTower.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yCommand.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yCommunicationMode.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yConfiguration.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yConnection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yCurrentMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yCurrentSensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yDistanceMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yDistanceSensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yFirmware.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yHardware.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yHumidityMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yHumiditySensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yLightMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yLightSensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yLogfileRequest.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yMeasurementValue.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yMobile.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yMoistureMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yMoistureSensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yMotionMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yMotionSensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yNetwork.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yPosition.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yProfile.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yRequiredAvailability.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8ySinglePhaseElectricitySensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8ySinglePhaseEnergyMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8ySoftwareList.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8ySteam.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yTemperatureMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yTemperatureSensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yThreePhaseElectricitySensor.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yThreePhaseEnergyMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/C8yVoltageMeasurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/CategoryKeyOption.cs create mode 100644 Client/Com/Cumulocity/Client/Model/CategoryOptions.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ChildOperationsAddMultiple.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ChildOperationsAddOne.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ComCumulocityModelAgent.cs create mode 100644 Client/Com/Cumulocity/Client/Model/CurrentTenant.cs create mode 100644 Client/Com/Cumulocity/Client/Model/CurrentUser.cs create mode 100644 Client/Com/Cumulocity/Client/Model/CustomProperties.cs create mode 100644 Client/Com/Cumulocity/Client/Model/DailyUsageStatistics.cs create mode 100644 Client/Com/Cumulocity/Client/Model/DeviceControlApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/DeviceCredentials.cs create mode 100644 Client/Com/Cumulocity/Client/Model/DevicePermissions.cs create mode 100644 Client/Com/Cumulocity/Client/Model/DeviceStatistics.cs create mode 100644 Client/Com/Cumulocity/Client/Model/DeviceStatisticsCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Error.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Event.cs create mode 100644 Client/Com/Cumulocity/Client/Model/EventBinary.cs create mode 100644 Client/Com/Cumulocity/Client/Model/EventCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/EventsApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ExternalId.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ExternalIds.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Group.cs create mode 100644 Client/Com/Cumulocity/Client/Model/GroupReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/GroupReferenceCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/IdentityApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/InventoryApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/InventoryAssignment.cs create mode 100644 Client/Com/Cumulocity/Client/Model/InventoryAssignmentCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/InventoryAssignmentReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/InventoryRole.cs create mode 100644 Client/Com/Cumulocity/Client/Model/InventoryRoleCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/InventoryRolePermission.cs create mode 100644 Client/Com/Cumulocity/Client/Model/JSONPredicateRepresentation.cs create mode 100644 Client/Com/Cumulocity/Client/Model/LoginForm.cs create mode 100644 Client/Com/Cumulocity/Client/Model/LoginOption.cs create mode 100644 Client/Com/Cumulocity/Client/Model/LoginOptionCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ManagedObject.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ManagedObjectCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ManagedObjectReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ManagedObjectReferenceCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ManagedObjectReferenceTuple.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ManagedObjectUser.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Measurement.cs create mode 100644 Client/Com/Cumulocity/Client/Model/MeasurementApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/MeasurementCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/MeasurementFragmentSeries.cs create mode 100644 Client/Com/Cumulocity/Client/Model/MeasurementSeries.cs create mode 100644 Client/Com/Cumulocity/Client/Model/MicroserviceApplicationManifest.cs create mode 100644 Client/Com/Cumulocity/Client/Model/NewDeviceRequest.cs create mode 100644 Client/Com/Cumulocity/Client/Model/NewDeviceRequestCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/NotificationApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/NotificationSubscription.cs create mode 100644 Client/Com/Cumulocity/Client/Model/NotificationSubscriptionCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/NotificationToken.cs create mode 100644 Client/Com/Cumulocity/Client/Model/NotificationTokenClaims.cs create mode 100644 Client/Com/Cumulocity/Client/Model/OAuthSessionConfiguration.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ObjectAdditionParents.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ObjectAssetParents.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ObjectChildAdditions.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ObjectChildAssets.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ObjectChildDevices.cs create mode 100644 Client/Com/Cumulocity/Client/Model/ObjectDeviceParents.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Operation.cs create mode 100644 Client/Com/Cumulocity/Client/Model/OperationCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/OperationReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Option.cs create mode 100644 Client/Com/Cumulocity/Client/Model/OptionCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/PageStatistics.cs create mode 100644 Client/Com/Cumulocity/Client/Model/PlatformApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/RangeStatisticsFile.cs create mode 100644 Client/Com/Cumulocity/Client/Model/RealtimeNotification.cs create mode 100644 Client/Com/Cumulocity/Client/Model/RequestRepresentation.cs create mode 100644 Client/Com/Cumulocity/Client/Model/RetentionRule.cs create mode 100644 Client/Com/Cumulocity/Client/Model/RetentionRuleCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Role.cs create mode 100644 Client/Com/Cumulocity/Client/Model/RoleReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/RoleReferenceCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/StatisticsFile.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SubscribedApplicationReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SubscribedRole.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SubscribedUser.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SummaryAllTenantsUsageStatistics.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SummaryTenantUsageStatistics.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SupportedMeasurements.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SupportedSeries.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SystemOption.cs create mode 100644 Client/Com/Cumulocity/Client/Model/SystemOptionCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/Tenant.cs create mode 100644 Client/Com/Cumulocity/Client/Model/TenantApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/TenantCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/TenantUsageStatisticsCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/TenantUsageStatisticsFileCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UsageStatisticsResources.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UsageStatisticsResourcesUsedBy.cs create mode 100644 Client/Com/Cumulocity/Client/Model/User.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UserApiResource.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UserCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UserGroupCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UserReference.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UserReferenceCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/UserRoleCollection.cs create mode 100644 Client/Com/Cumulocity/Client/Model/WebApplicationManifest.cs create mode 100644 Client/Com/Cumulocity/Client/Supplementary/AdaptableApi.cs create mode 100644 Client/Com/Cumulocity/Client/Supplementary/CumulocityCoreLibrary.cs create mode 100644 CumulocityCoreLibrary.sln create mode 100644 Test/Com/Cumulocity/Client/Api/AlarmsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/ApplicationBinariesApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/ApplicationsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/AttachmentsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/AuditsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/BinariesApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/BootstrapUserApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/BulkOperationsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/ChildOperationsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/CurrentApplicationApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/CurrentUserApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/DeviceCredentialsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/DeviceStatisticsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/EventsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/ExternalIDsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/GroupsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/IdentityApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/InventoryApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/InventoryRolesApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/LoginOptionsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/LoginTokensApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/ManagedObjectsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/MeasurementsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/NewDeviceRequestsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/OperationsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/OptionsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/RealtimeNotificationApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/RetentionRulesApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/RolesApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/SubscriptionsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/SystemOptionsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/TenantApplicationsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/TenantsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/TokensApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/UsageStatisticsApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Api/UsersApiTest.cs create mode 100644 Test/Com/Cumulocity/Client/Supplementary/TestConfiguration.cs create mode 100644 Test/Test.csproj create mode 100644 Test/appsettings.test.json diff --git a/Client/Client.csproj b/Client/Client.csproj new file mode 100644 index 0000000..9f3d323 --- /dev/null +++ b/Client/Client.csproj @@ -0,0 +1,23 @@ + + + + net6.0 + true + enable + + + + latest + + + latest + + + + + + + + + + diff --git a/Client/Com/Cumulocity/Client/Api/AlarmsApi.cs b/Client/Com/Cumulocity/Client/Api/AlarmsApi.cs new file mode 100644 index 0000000..384e628 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/AlarmsApi.cs @@ -0,0 +1,470 @@ +/// +/// AlarmsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// An alarm represents an event that requires manual action, for example, when the temperature of a fridge increases above a particular threshold. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class AlarmsApi : AdaptableApi + { + public AlarmsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all alarms
+ /// Retrieve all alarms on your tenant, or a specific subset based on queries. #### Query parameters The query parameter `withTotalPages` only works when the user has the ROLE_ALARM_READ role, otherwise it is ignored.
Required roles
The role ROLE_ALARM_READ is not required, but if a user has this role, all the alarms on the tenant are returned. If a user has access to alarms through inventory roles, only those alarms are returned.
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all alarms are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Start date or date and time of the alarm creation. + /// End date or date and time of the alarm creation. + /// The current page of the paginated results. + /// Start date or date and time of the alarm occurrence. + /// End date or date and time of the alarm occurrence. + /// Start date or date and time of the last update made. + /// End date or date and time of the last update made. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true` only alarms with status CLEARED will be fetched, whereas `false` will fetch all alarms with status ACTIVE or ACKNOWLEDGED. + /// The severity of the alarm to search for. + /// The managed object ID to which the alarm is associated. + /// The status of the alarm to search for. + /// The types of alarm to search for (comma separated). + /// When set to `true` also alarms for related source assets will be included in the request. When this parameter is provided a `source` must be specified. + /// When set to `true` also alarms for related source devices will be included in the request. When this parameter is provided a `source` must be specified. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetAlarms(System.DateTime? createdFrom = null, System.DateTime? createdTo = null, int? currentPage = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, System.DateTime? lastUpdatedFrom = null, System.DateTime? lastUpdatedTo = null, int? pageSize = null, bool? resolved = null, string? severity = null, string? source = null, string? status = null, List? type = null, bool? withSourceAssets = null, bool? withSourceDevices = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/alarm/alarms")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"createdFrom", createdFrom}, + {"createdTo", createdTo}, + {"currentPage", currentPage}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"lastUpdatedFrom", lastUpdatedFrom}, + {"lastUpdatedTo", lastUpdatedTo}, + {"pageSize", pageSize}, + {"resolved", resolved}, + {"severity", severity}, + {"source", source}, + {"status", status}, + {"type", type}, + {"withSourceAssets", withSourceAssets}, + {"withSourceDevices", withSourceDevices}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.alarmcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update alarm collections
+ /// Update alarm collections specified by query parameters. At least one query parameter is required to avoid accidentally updating all existing alarms.
Currently, only the status of alarms can be modified. > **ⓘ Info:** Since this operation can take considerable time, the request returns after maximum 0.5 seconds of processing, and the update operation continues as a background process in the platform.
Required roles
ROLE_ALARM_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An alarm collection was updated. + /// + /// + /// HTTP 202 + /// An alarm collection is being updated in background. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Start date or date and time of the alarm creation. + /// End date or date and time of the alarm creation. + /// Start date or date and time of the alarm occurrence. + /// End date or date and time of the alarm occurrence. + /// When set to `true` only alarms with status CLEARED will be fetched, whereas `false` will fetch all alarms with status ACTIVE or ACKNOWLEDGED. + /// The severity of the alarm to search for. + /// The managed object ID to which the alarm is associated. + /// The status of the alarm to search for. + /// When set to `true` also alarms for related source assets will be included in the request. When this parameter is provided a `source` must be specified. + /// When set to `true` also alarms for related source devices will be included in the request. When this parameter is provided a `source` must be specified. + public async Task UpdateAlarms(Alarm body, System.DateTime? createdFrom = null, System.DateTime? createdTo = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, bool? resolved = null, string? severity = null, string? source = null, string? status = null, bool? withSourceAssets = null, bool? withSourceDevices = null) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("firstOccurrenceTime"); + jsonNode?.RemoveFromNode("severity"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("count"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("source"); + jsonNode?.RemoveFromNode("text"); + jsonNode?.RemoveFromNode("time"); + jsonNode?.RemoveFromNode("type"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/alarm/alarms")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"createdFrom", createdFrom}, + {"createdTo", createdTo}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"resolved", resolved}, + {"severity", severity}, + {"source", source}, + {"status", status}, + {"withSourceAssets", withSourceAssets}, + {"withSourceDevices", withSourceDevices} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.alarm+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.alarm+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Create an alarm
+ /// An alarm must be associated with a source (managed object) identified by ID.
In general, each alarm may consist of: * A status showing whether the alarm is ACTIVE, ACKNOWLEDGED or CLEARED. * A time stamp to indicate when the alarm was last updated. * The severity of the alarm: CRITICAL, MAJOR, MINOR or WARNING. * A history of changes to the event in form of audit logs. ### Alarm suppression If the source device is in maintenance mode, the alarm is not created and not reported to the Cumulocity IoT event processing engine. When sending a POST request to create a new alarm and if the source device is in maintenance mode, the self link of the alarm will be: ```json "self": "https:///alarm/alarms/null" ``` ### Alarm de-duplication If an ACTIVE or ACKNOWLEDGED alarm with the same source and type exists, no new alarm is created. Instead, the existing alarm is updated by incrementing the `count` property; the `time` property is also updated. Any other changes are ignored, and the alarm history is not updated. Alarms with status CLEARED are not de-duplicated. The first occurrence of the alarm is recorded in the `firstOccurrenceTime` property.
Required roles
ROLE_ALARM_ADMIN OR owner of the source OR ALARM_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An alarm was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateAlarm(Alarm body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("firstOccurrenceTime"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("count"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("source", "self"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/alarm/alarms")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.alarm+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.alarm+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.alarm+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove alarm collections
+ /// Remove alarm collections specified by query parameters. > **⚠️ Important:** Note that it is possible to call this endpoint without providing any parameter - it will result in deleting all alarms and it is not recommended. > Also note that DELETE requests are not synchronous. The response could be returned before the delete request has been completed.
Required roles
ROLE_ALARM_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A collection of alarms was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// Start date or date and time of the alarm creation. + /// End date or date and time of the alarm creation. + /// Start date or date and time of the alarm occurrence. + /// End date or date and time of the alarm occurrence. + /// When set to `true` only alarms with status CLEARED will be fetched, whereas `false` will fetch all alarms with status ACTIVE or ACKNOWLEDGED. + /// The severity of the alarm to search for. + /// The managed object ID to which the alarm is associated. + /// The status of the alarm to search for. + /// The types of alarm to search for (comma separated). + /// When set to `true` also alarms for related source assets will be included in the request. When this parameter is provided a `source` must be specified. + /// When set to `true` also alarms for related source devices will be included in the request. When this parameter is provided a `source` must be specified. + public async Task DeleteAlarms(System.DateTime? createdFrom = null, System.DateTime? createdTo = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, bool? resolved = null, string? severity = null, string? source = null, string? status = null, List? type = null, bool? withSourceAssets = null, bool? withSourceDevices = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/alarm/alarms")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"createdFrom", createdFrom}, + {"createdTo", createdTo}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"resolved", resolved}, + {"severity", severity}, + {"source", source}, + {"status", status}, + {"type", type}, + {"withSourceAssets", withSourceAssets}, + {"withSourceDevices", withSourceDevices} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a specific alarm
+ /// Retrieve a specific alarm by a given ID.
Required roles
ROLE_ALARM_READ OR owner of the source OR ALARM_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the alarm is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Alarm not found. + /// + /// + ///
+ /// Unique identifier of the alarm. + /// + public async Task GetAlarm(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/alarm/alarms/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.alarm+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific alarm
+ /// Update a specific alarm by a given ID. Only text, status, severity and custom properties can be modified. A request will be rejected when non-modifiable properties are provided in the request body. > **ⓘ Info:** Changes to alarms will generate a new audit record. The audit record will include the username and application that triggered the update, if applicable. If the update operation doesn’t change anything (that is, the request body contains data that is identical to the already present in the database), there will be no audit record added and no notifications will be sent.
Required roles
ROLE_ALARM_ADMIN OR owner of the source OR ALARM_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An alarm was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Alarm not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of the alarm. + /// + public async Task UpdateAlarm(Alarm body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("firstOccurrenceTime"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("count"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("source"); + jsonNode?.RemoveFromNode("time"); + jsonNode?.RemoveFromNode("type"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/alarm/alarms/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.alarm+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.alarm+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.alarm+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve the total number of alarms
+ /// Count the total number of active alarms on your tenant.
Required roles
The role ROLE_ALARM_READ is not required, but if a user has this role, all the alarms on the tenant are counted. Otherwise, inventory role permissions are used to count the alarms and the limit is 100.
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the number of active alarms is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Start date or date and time of the alarm occurrence. + /// End date or date and time of the alarm occurrence. + /// When set to `true` only alarms with status CLEARED will be fetched, whereas `false` will fetch all alarms with status ACTIVE or ACKNOWLEDGED. + /// The severity of the alarm to search for. + /// The managed object ID to which the alarm is associated. + /// The status of the alarm to search for. + /// The types of alarm to search for (comma separated). + /// When set to `true` also alarms for related source assets will be included in the request. When this parameter is provided a `source` must be specified. + /// When set to `true` also alarms for related source devices will be included in the request. When this parameter is provided a `source` must be specified. + /// + public async Task GetNumberOfAlarms(System.DateTime? dateFrom = null, System.DateTime? dateTo = null, bool? resolved = null, string? severity = null, string? source = null, string? status = null, List? type = null, bool? withSourceAssets = null, bool? withSourceDevices = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/alarm/alarms/count")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"resolved", resolved}, + {"severity", severity}, + {"source", source}, + {"status", status}, + {"type", type}, + {"withSourceAssets", withSourceAssets}, + {"withSourceDevices", withSourceDevices} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, text/plain, application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/ApplicationBinariesApi.cs b/Client/Com/Cumulocity/Client/Api/ApplicationBinariesApi.cs new file mode 100644 index 0000000..7b7ea2d --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/ApplicationBinariesApi.cs @@ -0,0 +1,181 @@ +/// +/// ApplicationBinariesApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// An API method to upload an application binary. It is a deployable microservice or web application. + /// + #nullable enable + public class ApplicationBinariesApi : AdaptableApi + { + public ApplicationBinariesApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all application attachments
+ /// Retrieve all application attachments. This method is not supported by microservice applications.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the application attachments are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Application not found. + /// + /// + ///
+ /// Unique identifier of the application. + /// + public async Task GetApplicationAttachments(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}/binaries")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.applicationbinaries+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Upload an application attachment
+ /// Upload an application attachment (by a given application ID). For the applications of type “microservice” and “web application” to be available for Cumulocity IoT platform users, an attachment ZIP file must be uploaded. For a microservice application, the ZIP file must consist of: * cumulocity.json - file describing the deployment * image.tar - executable Docker image For a web application, the ZIP file must include an index.html file in the root directory.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN AND tenant is the owner of the application
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// The application attachments have been uploaded. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The ZIP file to be uploaded. + /// Unique identifier of the application. + /// + public async Task UploadApplicationAttachment(byte[] file, string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}/binaries")); + var requestContent = new MultipartFormDataContent(); + var fileContentFile = new ByteArrayContent(file); + fileContentFile.Headers.ContentType = MediaTypeHeaderValue.Parse("application/zip"); + requestContent.Add(fileContentFile, "file"); + var request = new HttpRequestMessage + { + Content = requestContent, + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.application+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific application attachment
+ /// Retrieve a specific application attachment (by a given application ID and a given binary ID). This method is not supported by microservice applications.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the application attachment is sent as a ZIP file in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of the application. + /// Unique identifier of the binary. + public async Task GetApplicationAttachment(string id, string binaryId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}/binaries/{binaryId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/zip"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Delete a specific application attachment
+ /// Delete a specific application attachment (by a given application ID and a given binary ID). This method is not supported by microservice applications.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN AND tenant is the owner of the application
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// An application binary was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// Unique identifier of the application. + /// Unique identifier of the binary. + public async Task DeleteApplicationAttachment(string id, string binaryId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}/binaries/{binaryId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/ApplicationsApi.cs b/Client/Com/Cumulocity/Client/Api/ApplicationsApi.cs new file mode 100644 index 0000000..9474cc0 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/ApplicationsApi.cs @@ -0,0 +1,490 @@ +/// +/// ApplicationsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to retrieve, create, update and delete applications. + /// + /// ### Application names + /// + /// For each tenant, Cumulocity IoT manages the subscribed applications and provides a number of applications of various types. + /// In case you want to subscribe a tenant to an application using an API, you must use the application name in the argument (as name). + /// + /// Refer to the tables in [Administration > Managing applications](https://cumulocity.com/guides/10.7.0/users-guide/administration#managing-applications) in the User guide for the respective application name to be used. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class ApplicationsApi : AdaptableApi + { + public ApplicationsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all applications
+ /// Retrieve all applications on your tenant.
Required roles
ROLE_APPLICATION_MANAGEMENT_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the list of applications is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The current page of the paginated results. + /// The name of the application. + /// The ID of the tenant that owns the applications. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// The ID of a tenant that is subscribed to the applications but doesn't own them. + /// The ID of a tenant that is subscribed to the applications. + /// The ID of a tenant that either owns the application or is subscribed to the applications. + /// The type of the application. + /// The ID of a user that has access to the applications. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetApplications(int? currentPage = null, string? name = null, string? owner = null, int? pageSize = null, string? providedFor = null, string? subscriber = null, string? tenant = null, string? type = null, string? user = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"name", name}, + {"owner", owner}, + {"pageSize", pageSize}, + {"providedFor", providedFor}, + {"subscriber", subscriber}, + {"tenant", tenant}, + {"type", type}, + {"user", user}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.applicationcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create an application
+ /// Create an application on your tenant.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An application was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 409 + /// Duplicate key/name. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateApplication(Application body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("activeVersionId"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("resourcesUrl"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.application+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.application+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.application+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific application
+ /// Retrieve a specific application (by a given ID).
Required roles
ROLE_APPLICATION_MANAGEMENT_READ OR current user has explicit access to the application
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the application is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Application not found. + /// + /// + ///
+ /// Unique identifier of the application. + /// + public async Task GetApplication(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.application+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific application
+ /// Update a specific application (by a given ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An application was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Application not found. + /// + /// + ///
+ /// + /// Unique identifier of the application. + /// + public async Task UpdateApplication(Application body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("activeVersionId"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("type"); + jsonNode?.RemoveFromNode("resourcesUrl"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.application+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.application+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.application+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Delete an application
+ /// Delete an application (by a given ID). This method is not supported by microservice applications. > **ⓘ Info:** With regards to a hosted application, there is a caching mechanism in place that keeps the information about the placement of application files (html, javascript, css, fonts, etc.). Removing a hosted application, in normal circumstances, will cause the subsequent requests for application files to fail with an HTTP 404 error because the application is removed synchronously, its files are immediately removed on the node serving the request and at the same time the information is propagated to other nodes – but in rare cases there might be a delay with this propagation. In such situations, the files of the removed application can be served from those nodes up until the aforementioned cache expires. For the same reason, the cache can also cause HTTP 404 errors when the application is updated as it will keep the path to the files of the old version of the application. The cache is filled on demand, so there should not be issues if application files were not accessed prior to the delete request. The expiration delay of the cache can differ, but should not take more than one minute.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN AND tenant is the owner of the application
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// An application was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Application not found. + /// + /// + ///
+ /// Unique identifier of the application. + /// Force deletion by unsubscribing all tenants from the application first and then deleting the application itself. + public async Task DeleteApplication(string id, bool? force = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"force", force} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Copy an application
+ /// Copy an application (by a given ID). This method is not supported by microservice applications. A request to the "clone" resource creates a new application based on an already existing one. The properties are copied to the newly created application and the prefix "clone" is added to the properties `name`, `key` and `contextPath` in order to be unique. If the target application is hosted and has an active version, the new application will have the active version with the same content.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An application was copied. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – method not supported + /// + /// + ///
+ /// Unique identifier of the application. + /// + public async Task CopyApplication(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}/clone")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.application+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve applications by name
+ /// Retrieve applications by name.
Required roles
ROLE_APPLICATION_MANAGEMENT_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the applications are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The name of the application. + /// + public async Task GetApplicationsByName(string name) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applicationsByName/{name}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.applicationcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve applications by tenant
+ /// Retrieve applications subscribed or owned by a particular tenant (by a given tenant ID).
Required roles
ROLE_APPLICATION_MANAGEMENT_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the applications are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// + public async Task GetApplicationsByTenant(string tenantId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applicationsByTenant/{tenantId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.applicationcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve applications by owner
+ /// Retrieve all applications owned by a particular tenant (by a given tenant ID).
Required roles
ROLE_APPLICATION_MANAGEMENT_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the applications are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetApplicationsByOwner(string tenantId, int? currentPage = null, int? pageSize = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applicationsByOwner/{tenantId}")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.applicationcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve applications by user
+ /// Retrieve all applications for a particular user (by a given username).
Required roles
(ROLE_USER_MANAGEMENT_OWN_READ AND is the current user) OR (ROLE_USER_MANAGEMENT_READ AND ROLE_APPLICATION_MANAGEMENT_READ)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the applications are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The username of the a user. + /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetApplicationsByUser(string username, int? currentPage = null, int? pageSize = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applicationsByUser/{username}")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.applicationcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/AttachmentsApi.cs b/Client/Com/Cumulocity/Client/Api/AttachmentsApi.cs new file mode 100644 index 0000000..35a0685 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/AttachmentsApi.cs @@ -0,0 +1,242 @@ +/// +/// AttachmentsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// It is possible to store, retrieve and delete binaries for events. Each event can have one binary attached. + /// + #nullable enable + public class AttachmentsApi : AdaptableApi + { + public AttachmentsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve the attached file of a specific event
+ /// Retrieve the attached file (binary) of a specific event by a given ID.
Required roles
ROLE_EVENT_READ OR EVENT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the file is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Attachment not found. + /// + /// + ///
+ /// Unique identifier of the event. + public async Task GetEventAttachment(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}/binaries")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/octet-stream"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Replace the attached file of a specific event
+ /// Upload and replace the attached file (binary) of a specific event by a given ID.
The size of the attachment is configurable, and the default size is 50 MiB. The default chunk size is 5MiB.
Required roles
ROLE_EVENT_ADMIN OR owner of the source OR EVENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A file was uploaded. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Event not found. + /// + /// + ///
+ /// + /// Unique identifier of the event. + /// + public async Task ReplaceEventAttachment(byte[] body, string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}/binaries")); + var request = new HttpRequestMessage + { + Content = new ByteArrayContent(body), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "text/plain"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.event+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Attach a file to a specific event
+ /// Upload a file (binary) as an attachment of a specific event by a given ID.
The size of the attachment is configurable, and the default size is 50 MiB. The default chunk size is 5MiB. After the file has been uploaded, the corresponding event will contain the fragment `c8y_IsBinary` similar to: ```json "c8y_IsBinary": { "name": "hello.txt", "length": 365, "type": "text/plain" } ``` When using `multipart/form-data` each value is sent as a block of data (body part), with a user agent-defined delimiter (`boundary`) separating each part. The keys are given in the `Content-Disposition` header of each part. ```http POST /event/events/{id}/binaries Host: https:// Authorization: Accept: application/json Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="object" { "name": "hello.txt", "type": "text/plain" } --boundary Content-Disposition: form-data; name="file"; filename="hello.txt" Content-Type: text/plain --boundary-- ```
Required roles
ROLE_EVENT_ADMIN OR owner of the source OR EVENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A file was uploaded. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Event not found. + /// + /// + /// HTTP 409 + /// An attachment exists already. + /// + /// + ///
+ /// + /// Unique identifier of the event. + /// + public async Task UploadEventAttachment(byte[] body, string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}/binaries")); + var request = new HttpRequestMessage + { + Content = new ByteArrayContent(body), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "text/plain"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.event+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Attach a file to a specific event
+ /// Upload a file (binary) as an attachment of a specific event by a given ID.
The size of the attachment is configurable, and the default size is 50 MiB. The default chunk size is 5MiB. After the file has been uploaded, the corresponding event will contain the fragment `c8y_IsBinary` similar to: ```json "c8y_IsBinary": { "name": "hello.txt", "length": 365, "type": "text/plain" } ``` When using `multipart/form-data` each value is sent as a block of data (body part), with a user agent-defined delimiter (`boundary`) separating each part. The keys are given in the `Content-Disposition` header of each part. ```http POST /event/events/{id}/binaries Host: https:// Authorization: Accept: application/json Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="object" { "name": "hello.txt", "type": "text/plain" } --boundary Content-Disposition: form-data; name="file"; filename="hello.txt" Content-Type: text/plain --boundary-- ```
Required roles
ROLE_EVENT_ADMIN OR owner of the source OR EVENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A file was uploaded. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Event not found. + /// + /// + /// HTTP 409 + /// An attachment exists already. + /// + /// + ///
+ /// + /// Path of the file to be uploaded. + /// Unique identifier of the event. + /// + public async Task UploadEventAttachment(BinaryInfo pObject, byte[] file, string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}/binaries")); + var requestContent = new MultipartFormDataContent(); + var fileContentObject = new StringContent(JsonSerializer.Serialize(pObject)); + fileContentObject.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + requestContent.Add(fileContentObject, "object"); + var fileContentFile = new ByteArrayContent(file); + fileContentFile.Headers.ContentType = MediaTypeHeaderValue.Parse("text/plain"); + requestContent.Add(fileContentFile, "file"); + var request = new HttpRequestMessage + { + Content = requestContent, + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.event+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove the attached file from a specific event
+ /// Remove the attached file (binary) from a specific event by a given ID.
Required roles
ROLE_EVENT_ADMIN OR owner of the source OR EVENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A file was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Event not found. + /// + /// + ///
+ /// Unique identifier of the event. + public async Task DeleteEventAttachment(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}/binaries")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/AuditsApi.cs b/Client/Com/Cumulocity/Client/Api/AuditsApi.cs new file mode 100644 index 0000000..25dd5ce --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/AuditsApi.cs @@ -0,0 +1,181 @@ +/// +/// AuditsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// An audit log stores events that are security-relevant and should be stored for auditing. For example, an audit log should be generated when a user logs into a gateway. + /// + /// An audit log extends an event through: + /// + /// * A username of the user that carried out the activity. + /// * An application that was used to carry out the activity. + /// * The actual activity. + /// * A severity. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class AuditsApi : AdaptableApi + { + public AuditsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all audit records
+ /// Retrieve all audit records registered on your tenant, or a specific subset based on queries. + ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all audit records are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Name of the application from which the audit was carried out. + /// The current page of the paginated results. + /// Start date or date and time of the audit record. + /// End date or date and time of the audit record. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// The platform component ID to which the audit is associated. + /// The type of audit record to search for. + /// The username to search for. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetAuditRecords(string? application = null, int? currentPage = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, int? pageSize = null, string? source = null, string? type = null, string? user = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/audit/auditRecords")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"application", application}, + {"currentPage", currentPage}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"pageSize", pageSize}, + {"source", source}, + {"type", type}, + {"user", user}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.auditrecordcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create an audit record
+ /// Create an audit record.
Required roles
ROLE_AUDIT_ADMIN OR ROLE_SYSTEM OR AUDIT_ADMIN permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An audit record was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + /// + public async Task CreateAuditRecord(AuditRecord body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("severity"); + jsonNode?.RemoveFromNode("application"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("c8y_Metadata"); + jsonNode?.RemoveFromNode("changes"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("source", "self"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/audit/auditRecords")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.auditrecord+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.auditrecord+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.auditrecord+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific audit record
+ /// Retrieve a specific audit record by a given ID.
Required roles
ROLE_AUDIT_READ OR AUDIT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the audit record is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of the audit record. + /// + public async Task GetAuditRecord(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/audit/auditRecords/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.auditrecord+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/BinariesApi.cs b/Client/Com/Cumulocity/Client/Api/BinariesApi.cs new file mode 100644 index 0000000..c53180c --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/BinariesApi.cs @@ -0,0 +1,248 @@ +/// +/// BinariesApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// Managed objects can perform operations to store, retrieve and delete binaries. One binary can store only one file. Together with the binary, a managed object is created which acts as a metadata information for the binary. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class BinariesApi : AdaptableApi + { + public BinariesApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve the stored files
+ /// Retrieve the stored files as a collections of managed objects. + ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the managed objects are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Search for a specific child addition and list all the groups to which it belongs. + /// Search for a specific child asset and list all the groups to which it belongs. + /// Search for a specific child device and list all the groups to which it belongs. + /// The current page of the paginated results. + /// The managed object IDs to search for (comma separated). + /// Username of the owner of the managed objects. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// Search for managed objects where any property value is equal to the given one. Only string values are supported. + /// The type of managed object to search for. + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetBinaries(string? childAdditionId = null, string? childAssetId = null, string? childDeviceId = null, int? currentPage = null, List? ids = null, string? owner = null, int? pageSize = null, string? text = null, string? type = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/binaries")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"childAdditionId", childAdditionId}, + {"childAssetId", childAssetId}, + {"childDeviceId", childDeviceId}, + {"currentPage", currentPage}, + {"ids", ids}, + {"owner", owner}, + {"pageSize", pageSize}, + {"text", text}, + {"type", type}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Upload a file
+ /// Uploading a file (binary) requires providing the following properties: * `object` – In JSON format, it contains information about the file. * `file` – Contains the file to be uploaded. After the file has been uploaded, the corresponding managed object will contain the fragment `c8y_IsBinary`.
Required roles
ROLE_INVENTORY_ADMIN OR ROLE_INVENTORY_CREATE
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A file was uploaded. + /// + /// + /// HTTP 400 + /// Unprocessable Entity – invalid payload. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// + /// Path of the file to be uploaded. + /// + public async Task UploadBinary(BinaryInfo pObject, byte[] file) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/binaries")); + var requestContent = new MultipartFormDataContent(); + var fileContentObject = new StringContent(JsonSerializer.Serialize(pObject)); + fileContentObject.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + requestContent.Add(fileContentObject, "object"); + var fileContentFile = new ByteArrayContent(file); + fileContentFile.Headers.ContentType = MediaTypeHeaderValue.Parse("text/plain"); + requestContent.Add(fileContentFile, "file"); + var request = new HttpRequestMessage + { + Content = requestContent, + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobject+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a stored file
+ /// Retrieve a stored file (managed object) by a given ID.
Required roles
ROLE_INVENTORY_READ OR owner of the resource OR MANAGE_OBJECT_READ permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the file is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of the managed object. + public async Task GetBinary(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/binaries/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/octet-stream"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Replace a file
+ /// Upload and replace the attached file (binary) of a specific managed object by a given ID.
Required roles
ROLE_INVENTORY_ADMIN OR owner of the resource OR MANAGE_OBJECT_ADMIN permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A file was uploaded. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + /// + public async Task ReplaceBinary(byte[] body, string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/binaries/{id}")); + var request = new HttpRequestMessage + { + Content = new ByteArrayContent(body), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "text/plain"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobject+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a stored file
+ /// Remove a managed object and its stored file by a given ID.
Required roles
ROLE_INVENTORY_ADMIN OR owner of the resource OR MANAGE_OBJECT_ADMIN permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A managed object and its stored file was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of the managed object. + public async Task RemoveBinary(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/binaries/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/BootstrapUserApi.cs b/Client/Com/Cumulocity/Client/Api/BootstrapUserApi.cs new file mode 100644 index 0000000..d66af82 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/BootstrapUserApi.cs @@ -0,0 +1,71 @@ +/// +/// BootstrapUserApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to retrieve the bootstrap user of an application. + /// + #nullable enable + public class BootstrapUserApi : AdaptableApi + { + public BootstrapUserApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve the bootstrap user for a specific application
+ /// Retrieve the bootstrap user for a specific application (by a given ID). This only works for microservice applications.
Required roles
ROLE_APPLICATION_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the bootstrap user of the application is sent in the response. + /// + /// + /// HTTP 400 + /// Bad request. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of the application. + /// + public async Task GetBootstrapUser(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/applications/{id}/bootstrapUser")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.user+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/BulkOperationsApi.cs b/Client/Com/Cumulocity/Client/Api/BulkOperationsApi.cs new file mode 100644 index 0000000..3661d76 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/BulkOperationsApi.cs @@ -0,0 +1,262 @@ +/// +/// BulkOperationsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// The bulk operations API allows to schedule an operation on a group of devices to be executed at a specified time. + /// It is required to specify the delay between the creation of subsequent operations. + /// When the bulk operation is created, it has the status ACTIVE. + /// When all operations are created, the bulk operation has the status COMPLETED. + /// It is also possible to cancel an already created bulk operation by deleting it. + /// + /// When you create a bulk operation, you can run it in two modes: + /// + /// * If `groupId` is passed, it works the standard way, that means, it takes devices from a group and schedules operations on them. + /// * If `failedParentId` is passed, it takes the already processed bulk operation by that ID, and schedules operations on devices for which the previous operations failed. + /// + /// Note that passing both `groupId` and `failedParentId` will not work, and a bulk operation works with groups of type `static` and `dynamic`. + /// + /// > **ⓘ Info:** The bulk operations API requires different roles than the rest of the device control API: `BULK_OPERATION_READ` and `BULK_OPERATION_ADMIN`. + /// > + /// > The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class BulkOperationsApi : AdaptableApi + { + public BulkOperationsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve a list of bulk operations
+ /// Retrieve a list of bulk operations.
Required roles
ROLE_BULK_OPERATION_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the list of bulk operations sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetBulkOperations(int? currentPage = null, int? pageSize = null, bool? withTotalElements = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/bulkoperations")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalElements", withTotalElements} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.bulkoperationcollection+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a bulk operation
+ /// Create a bulk operation.
Required roles
ROLE_BULK_OPERATION_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A bulk operation was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + /// + public async Task CreateBulkOperation(BulkOperation body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("generalStatus"); + jsonNode?.RemoveFromNode("failedParentId"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("progress"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("status"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/bulkoperations")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.bulkoperation+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.bulkoperation+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.bulkoperation+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific bulk operation
+ /// Retrieve a specific bulk operation (by a given ID).
Required roles
ROLE_BULK_OPERATION_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the bulk operation is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Bulk operation not found. + /// + /// + ///
+ /// Unique identifier of the bulk operation. + /// + public async Task GetBulkOperation(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/bulkoperations/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.bulkoperation+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific bulk operation
+ /// Update a specific bulk operation (by a given ID).
Required roles
ROLE_BULK_OPERATION_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A bulk operation was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Bulk operation not found. + /// + /// + ///
+ /// + /// Unique identifier of the bulk operation. + /// + public async Task UpdateBulkOperation(BulkOperation body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("generalStatus"); + jsonNode?.RemoveFromNode("failedParentId"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("progress"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("status"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/bulkoperations/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.bulkoperation+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.bulkoperation+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.bulkoperation+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Delete a specific bulk operation
+ /// Delete a specific bulk operation (by a given ID).
Required roles
ROLE_BULK_OPERATION_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A bulk operation was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Bulk operation not found. + /// + /// + ///
+ /// Unique identifier of the bulk operation. + public async Task DeleteBulkOperation(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/bulkoperations/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/ChildOperationsApi.cs b/Client/Com/Cumulocity/Client/Api/ChildOperationsApi.cs new file mode 100644 index 0000000..ad53a4d --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/ChildOperationsApi.cs @@ -0,0 +1,1000 @@ +/// +/// ChildOperationsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// Managed objects can contain collections of references to child devices, additions and assets. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class ChildOperationsApi : AdaptableApi + { + public ChildOperationsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all child additions of a specific managed object
+ /// Retrieve all child additions of a specific managed object by a given ID, or a subset based on queries.
Required roles
ROLE_INVENTORY_READ OR owner of the source OR MANAGE_OBJECT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all child additions are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// Use query language to perform operations and/or filter the results. Details about the properties and supported operations can be found in [Query language](#tag/Query-language). + /// Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. + /// When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetChildAdditions(string id, int? currentPage = null, int? pageSize = null, string? query = null, bool? withChildren = null, bool? withChildrenCount = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAdditions")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"query", query}, + {"withChildren", withChildren}, + {"withChildrenCount", withChildrenCount}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Assign a managed object as child addition
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child addition of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child additions of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child addition to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child addition. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildAddition(ChildOperationsAddOne body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAdditions")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreference+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreference+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Assign a managed object as child addition
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child addition of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child additions of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child addition to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child addition. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildAddition(ChildOperationsAddMultiple body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAdditions")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Assign a managed object as child addition
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child addition of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child additions of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child addition to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child addition. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildAddition(ManagedObject body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("additionParents"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("childDevices"); + jsonNode?.RemoveFromNode("childAssets"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("childAdditions"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("assetParents"); + jsonNode?.RemoveFromNode("deviceParents"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAdditions")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobject+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobject+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Remove specific child additions from its parent
+ /// Remove specific child additions (by given child IDs) from its parent (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source (parent) OR owner of the child OR MANAGE_OBJECT_ADMIN permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// Child additions were removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task UnassignChildAdditions(ChildOperationsAddMultiple body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAdditions")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"), + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a specific child addition of a specific managed object
+ /// Retrieve a specific child addition (by a given child ID) of a specific managed object (by a given ID).
Required roles
ROLE_INVENTORY_READ OR MANAGE_OBJECT_READ permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the child addition is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// Unique identifier of the child object. + /// + public async Task GetChildAddition(string id, string childId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAdditions/{childId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.managedobjectreference+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific child addition from its parent
+ /// Remove a specific child addition (by a given child ID) from its parent (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source (parent) OR owner of the child OR MANAGE_OBJECT_ADMIN permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A child addition was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// Unique identifier of the child object. + public async Task UnassignChildAddition(string id, string childId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAdditions/{childId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve all child assets of a specific managed object
+ /// Retrieve all child assets of a specific managed object by a given ID, or a subset based on queries.
Required roles
ROLE_INVENTORY_READ OR owner of the source OR MANAGE_OBJECT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all child assets are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// Use query language to perform operations and/or filter the results. Details about the properties and supported operations can be found in [Query language](#tag/Query-language). + /// Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. + /// When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetChildAssets(string id, int? currentPage = null, int? pageSize = null, string? query = null, bool? withChildren = null, bool? withChildrenCount = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAssets")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"query", query}, + {"withChildren", withChildren}, + {"withChildrenCount", withChildrenCount}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Assign a managed object as child asset
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child asset of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child assets of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child asset to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child asset. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildAsset(ChildOperationsAddOne body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAssets")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreference+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreference+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Assign a managed object as child asset
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child asset of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child assets of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child asset to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child asset. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildAsset(ChildOperationsAddMultiple body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAssets")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Assign a managed object as child asset
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child asset of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child assets of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child asset to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child asset. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildAsset(ManagedObject body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("additionParents"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("childDevices"); + jsonNode?.RemoveFromNode("childAssets"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("childAdditions"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("assetParents"); + jsonNode?.RemoveFromNode("deviceParents"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAssets")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobject+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobject+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Remove specific child assets from its parent
+ /// Remove specific child assets (by given child IDs) from its parent (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source (parent) OR owner of the child OR MANAGE_OBJECT_ADMIN permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// Child assets were removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task UnassignChildAssets(ChildOperationsAddMultiple body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAssets")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"), + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a specific child asset of a specific managed object
+ /// Retrieve a specific child asset (by a given child ID) of a specific managed object (by a given ID).
Required roles
ROLE_INVENTORY_READ OR MANAGE_OBJECT_READ permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the child asset is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// Unique identifier of the child object. + /// + public async Task GetChildAsset(string id, string childId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAssets/{childId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.managedobjectreference+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific child asset from its parent
+ /// Remove a specific child asset (by a given child ID) from its parent (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source (parent) OR owner of the child OR MANAGE_OBJECT_ADMIN permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A child asset was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// Unique identifier of the child object. + public async Task UnassignChildAsset(string id, string childId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childAssets/{childId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve all child devices of a specific managed object
+ /// Retrieve all child devices of a specific managed object by a given ID, or a subset based on queries.
Required roles
ROLE_INVENTORY_READ OR owner of the source OR MANAGE_OBJECT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all child devices are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// Use query language to perform operations and/or filter the results. Details about the properties and supported operations can be found in [Query language](#tag/Query-language). + /// Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. + /// When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetChildDevices(string id, int? currentPage = null, int? pageSize = null, string? query = null, bool? withChildren = null, bool? withChildrenCount = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childDevices")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"query", query}, + {"withChildren", withChildren}, + {"withChildrenCount", withChildrenCount}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Assign a managed object as child device
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child device of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child devices of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child device to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child device. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildDevice(ChildOperationsAddOne body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childDevices")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreference+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreference+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Assign a managed object as child device
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child device of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child devices of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child device to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child device. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildDevice(ChildOperationsAddMultiple body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childDevices")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Assign a managed object as child device
+ /// The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child device of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child devices of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child device to another managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR ((owner of the source OR MANAGE_OBJECT_ADMIN permission on the source) AND (owner of the child OR MANAGE_OBJECT_ADMIN permission on the child))
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was assigned as child device. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task AssignAsChildDevice(ManagedObject body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("additionParents"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("childDevices"); + jsonNode?.RemoveFromNode("childAssets"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("childAdditions"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("assetParents"); + jsonNode?.RemoveFromNode("deviceParents"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childDevices")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobject+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobject+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Remove specific child devices from its parent
+ /// Remove specific child devices (by given child IDs) from its parent (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source (parent) OR owner of the child OR MANAGE_OBJECT_ADMIN permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// Child devices were removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + public async Task UnassignChildDevices(ChildOperationsAddMultiple body, string id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childDevices")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"), + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a specific child device of a specific managed object
+ /// Retrieve a specific child device (by a given child ID) of a specific managed object (by a given ID).
Required roles
ROLE_INVENTORY_READ OR MANAGE_OBJECT_READ permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the child device is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// Unique identifier of the child object. + /// + public async Task GetChildDevice(string id, string childId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childDevices/{childId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.managedobjectreference+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific child device from its parent
+ /// Remove a specific child device (by a given child ID) from its parent (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source (parent) OR owner of the child OR MANAGE_OBJECT_ADMIN permission on the source (parent)
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A child device was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// Unique identifier of the child object. + public async Task UnassignChildDevice(string id, string childId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/childDevices/{childId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/CurrentApplicationApi.cs b/Client/Com/Cumulocity/Client/Api/CurrentApplicationApi.cs new file mode 100644 index 0000000..e1450c6 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/CurrentApplicationApi.cs @@ -0,0 +1,186 @@ +/// +/// CurrentApplicationApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to retrieve and update the current application and to retrieve its subscribers. + /// It is the authenticated microservice user's application. + /// + /// + #nullable enable + public class CurrentApplicationApi : AdaptableApi + { + public CurrentApplicationApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve the current application
+ /// Retrieve the current application. This only works inside an application, for example, a microservice.
Required roles
Microservice bootstrap user required.
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the current application sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + ///
+ /// + public async Task GetCurrentApplication() + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/currentApplication")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.application+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update the current application
+ /// Update the current application. This only works inside an application, for example, a microservice. This method is deprecated as it is only used by legacy microservices that are not running on Kubernetes.
Required roles
Microservice bootstrap user required.
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The current application was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + ///
+ /// + /// + [Obsolete] + public async Task UpdateCurrentApplication(Application body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("activeVersionId"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("resourcesUrl"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/currentApplication")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.application+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.application+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.application+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve the current application settings
+ /// Retrieve the current application settings. This only works inside an application, for example, a microservice.
Required roles
Microservice bootstrap user OR microservice service user required.
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the current application settings are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + ///
+ /// + public async Task?> GetCurrentApplicationSettings() + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/currentApplication/settings")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.applicationsettings+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync?>(responseStream); + } + + /// + /// Retrieve the subscribed users of the current application
+ /// Retrieve the subscribed users of the current application.
Required roles
Microservice bootstrap user required.
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the list of subscribed users for the current application is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + public async Task GetSubscribedUsers() + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/application/currentApplication/subscriptions")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.applicationusercollection+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/CurrentUserApi.cs b/Client/Com/Cumulocity/Client/Api/CurrentUserApi.cs new file mode 100644 index 0000000..f0f4c74 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/CurrentUserApi.cs @@ -0,0 +1,115 @@ +/// +/// CurrentUserApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// The current user is the user that is currently authenticated with Cumulocity IoT for the API calls. + /// + /// > **ⓘ Info:** The Accept header should be provided in all PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class CurrentUserApi : AdaptableApi + { + public CurrentUserApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve the current user
+ /// Retrieve the user reference of the current user.
Required roles
ROLE_USER_MANAGEMENT_OWN_READ OR ROLE_SYSTEM
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the current user is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + public async Task GetCurrentUser() + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/currentUser")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.currentuser+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update the current user
+ /// Update the current user.
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The current user was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task UpdateCurrentUser(CurrentUser body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("effectiveRoles"); + jsonNode?.RemoveFromNode("shouldResetPassword"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("lastPasswordChange"); + jsonNode?.RemoveFromNode("devicePermissions"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/currentUser")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.currentuser+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.currentuser+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.currentuser+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/DeviceCredentialsApi.cs b/Client/Com/Cumulocity/Client/Api/DeviceCredentialsApi.cs new file mode 100644 index 0000000..62c96d4 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/DeviceCredentialsApi.cs @@ -0,0 +1,122 @@ +/// +/// DeviceCredentialsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to create device credentials in Cumulocity IoT. + /// + /// Device credentials can be enquired by devices that do not have credentials for accessing a tenant yet. + /// Since the device does not have credentials yet, a set of fixed credentials is used for this API. + /// The credentials can be obtained by [contacting support](https://cumulocity.com/guides/about-doc/contacting-support/). + /// + /// > **⚠️ Important:** Do not use your tenant credentials with this API. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class DeviceCredentialsApi : AdaptableApi + { + public DeviceCredentialsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Create device credentials
+ /// Create device credentials.
Required roles
ROLE_DEVICE_BOOTSTRAP
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// Device credentials were created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + /// + public async Task CreateDeviceCredentials(DeviceCredentials body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("password"); + jsonNode?.RemoveFromNode("tenantId"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("username"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/deviceCredentials")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.devicecredentials+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.devicecredentials+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.devicecredentials+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a bulk device credentials request
+ /// Create a bulk device credentials request. Device credentials and basic device representation can be provided within a CSV file which must be UTF-8 or ANSI encoded. The CSV file must have two sections. The first section is the first line of the CSV file. This line contains column names (headers): |Name|Mandatory|Description| |--- |--- |--- | |ID|Yes|The external ID of a device.| |CREDENTIALS|Yes|Password for the device's user.| |AUTH_TYPE|No|Required authentication type for the device's user. If the device uses credentials, this can be skipped or filled with "BASIC". Devices that use certificates must set "CERTIFICATES".| |TENANT|No|The ID of the tenant for which the registration is executed (only allowed for the management tenant).| |TYPE|No|The type of the device representation.| |NAME|No|The name of the device representation.| |ICCID|No|The ICCID of the device (SIM card number). If the ICCID appears in file, the import adds a fragment `c8y_Mobile.iccid`. The ICCID value is not mandatory for each row, see the example for an HTTP request below.| |IDTYPE|No|The type of the external ID. If IDTYPE doesn't appear in the file, the default value is used. The default value is `c8y_Serial`. The IDTYPE value is not mandatory for each row, see the example for an HTTP request below.| |PATH|No|The path in the groups hierarchy where the device is added. PATH contains the name of each group separated by `/`, that is: `main_group/sub_group/.../last_sub_group`. If a group does not exist, the import creates the group.| |SHELL|No|If this column contains a value of 1, the import adds the SHELL feature to the device (specifically the `c8y_SupportedOperations` fragment). The SHELL value is not mandatory for each row, see the example for an HTTP request below.| Section two is the rest of the CSV file. Section two contains the device information. The order and quantity of the values must be the same as of the headers. A separator is automatically obtained from the CSV file. Valid separator values are: `\t` (tabulation mark), `;` (semicolon) and `,` (comma). > **ⓘ Info:** A bulk registration creates an elementary representation of the device. Then, the device needs to update it to a full representation with its own status. The device is ready to use only after it is updated to the full representation. Also see [credentials upload](https://cumulocity.com/guides/users-guide/device-management/#creds-upload) and [device integration](https://cumulocity.com/guides/device-sdk/rest/#device-integration). A CSV file can appear in many forms (with regard to the optional tenant column and the occurrence of device information): * If a user is logged in as the management tenant, then the columns ID, CREDENTIALS and TENANT are mandatory, and the device credentials will be created for the tenant mentioned in the TENANT column. * If a user is logged in as a different tenant, for example, as `sample_tenant`, then the columns ID and CREDENTIALS are mandatory (if the file contains the TENANT column, it is ignored and the device credentials will be created for the tenant that is logged in). * If a user wants to add information about the device, the columns TYPE and NAME must appear in the CSV file. * If a user wants to add information about a SIM card number, the columns TYPE, NAME and ICCID must appear in the CSV file. * If a user wants to change the type of external ID, the columns TYPE, NAME and IDTYPE must appear in the CSV file. * If a user wants to add a device to a group, the columns TYPE, NAME and PATH must appear in the CSV file. * If a user wants to add the SHELL feature, the columns TYPE, NAME and SHELL must appear in the CSV file and the column SHELL must contain a value of 1. It is possible to define a custom [external ID](#tag/External-IDs) mapping and some custom device properties which are added to newly created devices during registration: * To add a custom external ID mapping, enter the external ID type as the header of the last column with the prefix "external-", for example, to add an external ID mapping of type `c8y_Imei`, enter `external-c8y_Imei` in the last column header. The value of this external ID type should be set in the corresponding column of the data rows. * To add a custom property to a registered device, enter the custom property name as a header, for example, "myCustomProperty", and the value would be in the rows below. The custom device properties mapping has the following limitations: * Braces '{}' used in data rows will be interpreted as strings of "{}". The system will interpret the value as an object when some custom property is added, for example, put `com_cumulocity_model_Agent.active` into the headers row and `true` into the data row to create an object `"com_cumulocity_model_Agent": {"active": "true"}"`. * It is not possible to add array values via bulk registration. Example file: ```csv ID;CREDENTIALS;TYPE;NAME;ICCID;IDTYPE;PATH;SHELL id_101;abcd1234;type_of_device;Device 101;111111111;;csv device/subgroup0;1 id_102;abcd1234;type_of_device;Device 102;222222222;;csv device/subgroup0;0 id_111;abcd1234;type_of_device;Device 111;333333333;c8y_Imei;csv device1/subgroup1;0 id_112;abcd1234;type_of_device;Device 112;444444444;;csv device1/subgroup1;1 id_121;abcd1234;type_of_device;Device 121;555555555;;csv device1/subgroup2;1 id_122;abcd1234;type_of_device;Device 122;;;csv device1/subgroup2; id_131;abcd1234;type_of_device;Device 131;;;csv device1/subgroup3; ``` There is also a simple registration method that creates all registration requests at once, then each one needs to go through regular acceptance. This simple registration only makes use of the ID and PATH fields from the list above.
Required roles
ROLE_DEVICE_CONTROL_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A bulk of new device requests was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The CSV file to be uploaded. + /// + public async Task CreateBulkDeviceCredentials(byte[] file) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/bulkNewDeviceRequests")); + var requestContent = new MultipartFormDataContent(); + var fileContentFile = new ByteArrayContent(file); + fileContentFile.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv"); + requestContent.Add(fileContentFile, "file"); + var request = new HttpRequestMessage + { + Content = requestContent, + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.bulknewdevicerequest+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/DeviceStatisticsApi.cs b/Client/Com/Cumulocity/Client/Api/DeviceStatisticsApi.cs new file mode 100644 index 0000000..0cd0543 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/DeviceStatisticsApi.cs @@ -0,0 +1,176 @@ +/// +/// DeviceStatisticsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// Device statistics are collected for each inventory object with at least one measurement, event or alarm. There are no additional checks if the inventory object is marked as device using the `c8y_IsDevice` fragment. When the first measurement, event or alarm is created for a specific inventory object, Cumulocity IoT is always considering this as a device and starts counting. + /// + /// Device statistics are counted with daily and monthy rate. All requests are considered when counting device statistics, no matter which processing mode is used. + /// + /// The following requests are counted: + /// + /// * Alarm creation and update + /// * Event creation and update + /// * Measurement creation + /// * Bulk measurement creation is counted as multiple requests + /// * Bulk alarm status update is counted as multiple requests + /// * MQTT and SmartREST requests with multiple rows are counted as multiple requests + /// + /// ### Frequently asked questions + /// + /// #### Are operations on device firmware counted? + /// + /// **No**, device configuration and firmware update operate on inventory objects, hence they are not counted. + /// + /// #### Are requests done by the UI applications, for example, when browsing device details, counted? + /// + /// **No**, viewing device details performs only GET requests which are not counted. + /// + /// #### Is the clear alarm operation done from the UI counted? + /// + /// **Yes**, a clear alarm operation in fact performs an alarm update operation and it will be counted as device request. + /// + /// #### Is there any operation performed on the device which is counted? + /// + /// **Yes**, retrieving device logs requires from the device to create an event and attach a binary with logs to it. Those are two separate requests and both are counted. + /// + /// #### When I have a device with children are the requests counted always to the root device or separately for each child? + /// + /// Separately for each child. + /// + /// + #nullable enable + public class DeviceStatisticsApi : AdaptableApi + { + public DeviceStatisticsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve monthly device statistics
+ /// Retrieve monthly device statistics from a specific tenant (by a given ID).
Required roles
ROLE_TENANT_STATISTICS_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the devices statistics are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Date (format YYYY-MM-dd) of the queried month (the day value is ignored). + /// The current page of the paginated results. + /// The ID of the device to search for. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetMonthlyDeviceStatistics(string tenantId, System.DateTime date, int? currentPage = null, string? deviceId = null, int? pageSize = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/tenant/statistics/device/{tenantId}/monthly/{date}")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"deviceId", deviceId}, + {"pageSize", pageSize}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve daily device statistics
+ /// Retrieve daily device statistics from a specific tenant (by a given ID).
Required roles
ROLE_TENANT_STATISTICS_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the devices statistics are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Date (format YYYY-MM-dd) of the queried day. + /// The current page of the paginated results. + /// The ID of the device to search for. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetDailyDeviceStatistics(string tenantId, System.DateTime date, int? currentPage = null, string? deviceId = null, int? pageSize = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/tenant/statistics/device/{tenantId}/daily/{date}")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"deviceId", deviceId}, + {"pageSize", pageSize}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/EventsApi.cs b/Client/Com/Cumulocity/Client/Api/EventsApi.cs new file mode 100644 index 0000000..2b3e31b --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/EventsApi.cs @@ -0,0 +1,346 @@ +/// +/// EventsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// Events are used to pass real-time information through Cumulocity IoT and they come in three types: base events when something in the sensor network happens, alarms requiring manual actions, and audit logs to store events that are security-relevant. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class EventsApi : AdaptableApi + { + public EventsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all events
+ /// Retrieve all events on your tenant. In case of executing [range queries](https://en.wikipedia.org/wiki/Range_query_(database)) between an upper and lower boundary, for example, querying using `dateFrom`–`dateTo` or `createdFrom`–`createdTo`, the oldest registered events are returned first. It is possible to change the order using the query parameter `revert=true`.
Required roles
ROLE_EVENT_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all events are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Start date or date and time of the event's creation (set by the platform during creation). + /// End date or date and time of the event's creation (set by the platform during creation). + /// The current page of the paginated results. + /// Start date or date and time of the event occurrence (provided by the device). + /// End date or date and time of the event occurrence (provided by the device). + /// A characteristic which identifies a managed object or event, for example, geolocation, electricity sensor, relay state. + /// Allows filtering events by the fragment's value, but only when provided together with `fragmentType`. > **⚠️ Important:** Only fragments with a string value are supported. + /// Start date or date and time of the last update made. + /// End date or date and time of the last update made. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// If you are using a range query (that is, at least one of the `dateFrom` or `dateTo` parameters is included in the request), then setting `revert=true` will sort the results by the oldest events first. By default, the results are sorted by the latest events first. + /// The managed object ID to which the event is associated. + /// The type of event to search for. + /// When set to `true` also events for related source assets will be included in the request. When this parameter is provided a `source` must be specified. + /// When set to `true` also events for related source devices will be included in the request. When this parameter is provided a `source` must be specified. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetEvents(System.DateTime? createdFrom = null, System.DateTime? createdTo = null, int? currentPage = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, string? fragmentType = null, string? fragmentValue = null, System.DateTime? lastUpdatedFrom = null, System.DateTime? lastUpdatedTo = null, int? pageSize = null, bool? revert = null, string? source = null, string? type = null, bool? withSourceAssets = null, bool? withSourceDevices = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"createdFrom", createdFrom}, + {"createdTo", createdTo}, + {"currentPage", currentPage}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"fragmentType", fragmentType}, + {"fragmentValue", fragmentValue}, + {"lastUpdatedFrom", lastUpdatedFrom}, + {"lastUpdatedTo", lastUpdatedTo}, + {"pageSize", pageSize}, + {"revert", revert}, + {"source", source}, + {"type", type}, + {"withSourceAssets", withSourceAssets}, + {"withSourceDevices", withSourceDevices}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.eventcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create an event
+ /// An event must be associated with a source (managed object) identified by an ID.
In general, each event consists of: * A type to identify the nature of the event. * A time stamp to indicate when the event was last updated. * A description of the event. * The managed object which originated the event.
Required roles
ROLE_EVENT_ADMIN OR owner of the source OR EVENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An event was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateEvent(Event body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("source", "self"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.event+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.event+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.event+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove event collections
+ /// Remove event collections specified by query parameters. DELETE requests are not synchronous. The response could be returned before the delete request has been completed. This may happen especially when the deleted event has a lot of associated data. After sending the request, the platform starts deleting the associated data in an asynchronous way. Finally, the requested event is deleted after all associated data has been deleted. > **⚠️ Important:** Note that it is possible to call this endpoint without providing any parameter - it will result in deleting all events and it is not recommended.
Required roles
ROLE_EVENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A collection of events was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// Start date or date and time of the event's creation (set by the platform during creation). + /// End date or date and time of the event's creation (set by the platform during creation). + /// Start date or date and time of the event occurrence (provided by the device). + /// End date or date and time of the event occurrence (provided by the device). + /// A characteristic which identifies a managed object or event, for example, geolocation, electricity sensor, relay state. + /// The managed object ID to which the event is associated. + /// The type of event to search for. + public async Task DeleteEvents(System.DateTime? createdFrom = null, System.DateTime? createdTo = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, string? fragmentType = null, string? source = null, string? type = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"createdFrom", createdFrom}, + {"createdTo", createdTo}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"fragmentType", fragmentType}, + {"source", source}, + {"type", type} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a specific event
+ /// Retrieve a specific event by a given ID.
Required roles
ROLE_EVENT_READ OR owner of the source OR EVENT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the event is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Event not found. + /// + /// + ///
+ /// Unique identifier of the event. + /// + public async Task GetEvent(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.event+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific event
+ /// Update a specific event by a given ID. Only its text description and custom fragments can be updated.
Required roles
ROLE_EVENT_ADMIN OR owner of the source OR EVENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An event was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Event not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of the event. + /// + public async Task UpdateEvent(Event body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("source"); + jsonNode?.RemoveFromNode("time"); + jsonNode?.RemoveFromNode("type"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.event+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.event+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.event+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific event
+ /// Remove a specific event by a given ID.
Required roles
ROLE_EVENT_ADMIN OR owner of the source OR EVENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// An event was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Event not found. + /// + /// + ///
+ /// Unique identifier of the event. + public async Task DeleteEvent(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/event/events/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/ExternalIDsApi.cs b/Client/Com/Cumulocity/Client/Api/ExternalIDsApi.cs new file mode 100644 index 0000000..3339e76 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/ExternalIDsApi.cs @@ -0,0 +1,188 @@ +/// +/// ExternalIDsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// The external ID resource represents an individual external ID that can be queried and deleted. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class ExternalIDsApi : AdaptableApi + { + public ExternalIDsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all external IDs of a specific managed object
+ /// Retrieve all external IDs of a existing managed object (identified by ID).
Required roles
ROLE_IDENTITY_READ OR owner of the resource OR MANAGED_OBJECT_READ permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all the external IDs are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// + public async Task GetExternalIds(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/identity/globalIds/{id}/externalIds")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.externalidcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create an external ID
+ /// Create an external ID for an existing managed object (identified by ID).
Required roles
ROLE_IDENTITY_ADMIN OR owner of the resource OR MANAGED_OBJECT_ADMIN permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An external ID was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 409 + /// Duplicate – Identity already bound to a different Global ID. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + /// + public async Task CreateExternalId(ExternalId body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("managedObject"); + jsonNode?.RemoveFromNode("self"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/identity/globalIds/{id}/externalIds")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.externalid+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.externalid+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.externalid+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific external ID
+ /// Retrieve a specific external ID of a particular type.
Required roles
ROLE_IDENTITY_READ OR owner of the resource OR MANAGED_OBJECT_READ permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the external ID is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// External ID not found. + /// + /// + ///
+ /// The identifier used in the external system that Cumulocity IoT interfaces with. + /// The type of the external identifier. + /// + public async Task GetExternalId(string type, string externalId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/identity/externalIds/{type}/{externalId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.externalid+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific external ID
+ /// Remove a specific external ID of a particular type.
Required roles
ROLE_IDENTITY_ADMIN OR owner of the resource OR MANAGED_OBJECT_ADMIN permission on the resource
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// An external ID was deleted. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// External ID not found. + /// + /// + ///
+ /// The identifier used in the external system that Cumulocity IoT interfaces with. + /// The type of the external identifier. + public async Task DeleteExternalId(string type, string externalId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/identity/externalIds/{type}/{externalId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/GroupsApi.cs b/Client/Com/Cumulocity/Client/Api/GroupsApi.cs new file mode 100644 index 0000000..09eae8d --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/GroupsApi.cs @@ -0,0 +1,386 @@ +/// +/// GroupsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to create, retrieve, update and delete user groups. + /// + /// > **⚠️ Important:** In the Cumulocity IoT user interface, user groups are referred to as "global roles". Global roles are not to be confused with user roles. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class GroupsApi : AdaptableApi + { + public GroupsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all user groups of a specific tenant
+ /// Retrieve all user groups of a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_READ OR ROLE_USER_MANAGEMENT_CREATE
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all user groups are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetUserGroups(string tenantId, int? currentPage = null, int? pageSize = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/groups")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.groupcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a user group for a specific tenant
+ /// Create a user group for a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A user group was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 409 + /// Duplicate – Group name already exists. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of a Cumulocity IoT tenant. + /// + public async Task CreateUserGroup(Group body, string tenantId) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("roles"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("devicePermissions"); + jsonNode?.RemoveFromNode("users"); + jsonNode?.RemoveFromNode("applications"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/groups")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.group+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.group+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.group+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific user group for a specific tenant
+ /// Retrieve a specific user group (by a given user group ID) for a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN OR ROLE_USER_MANAGEMENT_CREATE AND is parent of the user AND is not the current user
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request succeeded and the user group is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// Group not found. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the user group. + /// + public async Task GetUserGroup(string tenantId, int groupId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/groups/{groupId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.group+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific user group for a specific tenant
+ /// Update a specific user group (by a given user group ID) for a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A user group was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// Group not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the user group. + /// + public async Task UpdateUserGroup(Group body, string tenantId, int groupId) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("roles"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("devicePermissions"); + jsonNode?.RemoveFromNode("users"); + jsonNode?.RemoveFromNode("applications"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/groups/{groupId}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.group+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.group+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.group+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Delete a specific user group for a specific tenant
+ /// Delete a specific user group (by a given user group ID) for a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A user group was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Group not found. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the user group. + public async Task DeleteUserGroup(string tenantId, int groupId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/groups/{groupId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a user group by group name for a specific tenant
+ /// Retrieve a user group by group name for a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_READ OR ROLE_USER_MANAGEMENT_CREATE AND has access to groups
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request succeeded and the user group is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// Group not found. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// The name of the user group. + /// + public async Task GetUserGroupByName(string tenantId, string groupName) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/groupByName/{groupName}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.group+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Get all user groups for specific user in a specific tenant
+ /// Get all user groups for a specific user (by a given user ID) in a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_READ OR ROLE_USER_MANAGEMENT_CREATE AND is parent of the user
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request succeeded and all groups for the user are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// User not found. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the a user. + /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetUserGroups(string tenantId, string userId, int? currentPage = null, int? pageSize = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/users/{userId}/groups")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.groupreferencecollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/IdentityApi.cs b/Client/Com/Cumulocity/Client/Api/IdentityApi.cs new file mode 100644 index 0000000..b00a112 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/IdentityApi.cs @@ -0,0 +1,71 @@ +/// +/// IdentityApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// Cumulocity IoT can associate devices and assets with multiple external identities. + /// For instance, devices can often be identified by the IMEI of their modem, by a micro-controller serial number or by an asset tag. + /// This is useful, for example, when you have non-functional hardware and must replace the hardware without losing the data that was recorded. + /// + /// The identity API resource returns URIs and URI templates for associating external identifiers with unique identifiers. + /// + /// + #nullable enable + public class IdentityApi : AdaptableApi + { + public IdentityApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve URIs to collections of external IDs
+ /// Retrieve URIs and URI templates for associating external identifiers with unique identifiers.
Required roles
ROLE_IDENTITY_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the URIs are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + public async Task GetIdentityApiResource() + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/identity")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.identityapi+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/InventoryApi.cs b/Client/Com/Cumulocity/Client/Api/InventoryApi.cs new file mode 100644 index 0000000..5fade87 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/InventoryApi.cs @@ -0,0 +1,70 @@ +/// +/// InventoryApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// The inventory stores all master data related to devices, their configuration and their connections. It also contains all related assets (for example, vehicles, machines, buildings) and their structure. The inventory API resource returns URIs and URI templates to collections of managed objects. + /// + #nullable enable + public class InventoryApi : AdaptableApi + { + public InventoryApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve URIs to collections of managed objects
+ /// Retrieve URIs and URI templates to collections of managed objects.
Required roles
ROLE_INVENTORY_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the URIs are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// + public async Task GetInventoryApiResource() + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.inventoryapi+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/InventoryRolesApi.cs b/Client/Com/Cumulocity/Client/Api/InventoryRolesApi.cs new file mode 100644 index 0000000..0f23687 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/InventoryRolesApi.cs @@ -0,0 +1,479 @@ +/// +/// InventoryRolesApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to create, retrieve, update and delete inventory roles. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class InventoryRolesApi : AdaptableApi + { + public InventoryRolesApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all inventory roles
+ /// Retrieve all inventory roles.
Required roles
ROLE_USER_MANAGEMENT_READ OR ROLE_USER_MANAGEMENT_CREATE
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request succeeded and all inventory roles are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetInventoryRoles(int? currentPage = null, int? pageSize = null, bool? withTotalElements = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/inventoryroles")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalElements", withTotalElements} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.inventoryrolecollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create an inventory role
+ /// Create an inventory role.
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An inventory role was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateInventoryRole(InventoryRole body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/inventoryroles")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.inventoryrole+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.inventoryrole+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.inventoryrole+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific inventory role
+ /// Retrieve a specific inventory role (by a given ID).
Required roles
ROLE_USER_MANAGEMENT_READ OR ROLE_USER_MANAGEMENT_CREATE AND has access to the inventory role
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request succeeded and the inventory role is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Role not found. + /// + /// + ///
+ /// Unique identifier of the inventory role. + /// + public async Task GetInventoryRole(int id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/inventoryroles/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.inventoryrole+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific inventory role
+ /// Update a specific inventory role (by a given ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An inventory role was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Role not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of the inventory role. + /// + public async Task UpdateInventoryRole(InventoryRole body, int id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/inventoryroles/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.inventoryrole+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.inventoryrole+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.inventoryrole+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific inventory role
+ /// Remove a specific inventory role (by a given ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// An inventory role was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Role not found. + /// + /// + ///
+ /// Unique identifier of the inventory role. + public async Task DeleteInventoryRole(int id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/inventoryroles/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve all inventory roles assigned to a user
+ /// Retrieve all inventory roles assigned to a specific user (by a given user ID) in a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_READ OR ROLE_USER_MANAGEMENT_CREATE AND is the parent of the user
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the inventory roles are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// User not found. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the a user. + /// + public async Task GetUserInventoryRoles(string tenantId, string userId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/users/{userId}/roles/inventory")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.inventoryassignmentcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Assign an inventory role to a user
+ /// Assign an existing inventory role to a specific user (by a given user ID) in a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN AND (is not in user hierarchy OR is root in the user hierarchy) OR ROLE_USER_MANAGEMENT_ADMIN AND is in user hiararchy AND has parent access to inventory assignments OR ROLE_USER_MANAGEMENT_CREATE AND is parent of the user AND is not the current user AND has current user access to inventory assignments AND has parent access to inventory assignments
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An inventory role was assigned to a user. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// User not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the a user. + /// + public async Task AssignUserInventoryRole(InventoryAssignment body, string tenantId, string userId) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/users/{userId}/roles/inventory")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.inventoryassignment+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.inventoryassignment+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.inventoryassignment+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific inventory role assigned to a user
+ /// Retrieve a specific inventory role (by a given ID) assigned to a specific user (by a given user ID) in a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_READ OR ROLE_USER_MANAGEMENT_CREATE AND is the parent of the user
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the inventory role is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// Role not found. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the a user. + /// Unique identifier of the inventory assignment. + /// + public async Task GetUserInventoryRole(string tenantId, string userId, int id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/users/{userId}/roles/inventory/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.inventoryassignment+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific inventory role assigned to a user
+ /// Update a specific inventory role (by a given ID) assigned to a specific user (by a given user ID) in a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An inventory assignment was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not enough permissions/roles to perform this operation. + /// + /// + /// HTTP 404 + /// Role not found. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the a user. + /// Unique identifier of the inventory assignment. + /// + public async Task UpdateUserInventoryRole(InventoryAssignmentReference body, string tenantId, string userId, int id) + { + var jsonNode = ToJsonNode(body); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/users/{userId}/roles/inventory/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.inventoryassignment+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.inventoryassignment+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.inventoryassignment+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific inventory role assigned to a user
+ /// Remove a specific inventory role (by a given ID) assigned to a specific user (by a given user ID) in a specific tenant (by a given tenant ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN AND (is not in user hierarchy OR is root in the user hierarchy) OR ROLE_USER_MANAGEMENT_ADMIN AND is in user hiararchy AND has parent access to inventory assignments OR ROLE_USER_MANAGEMENT_CREATE AND is parent of the user AND is not the current user AND has current user access to inventory assignments AND has parent access to inventory assignments
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// An inventory assignment was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Role not found. + /// + /// + ///
+ /// Unique identifier of a Cumulocity IoT tenant. + /// Unique identifier of the a user. + /// Unique identifier of the inventory assignment. + public async Task UnassignUserInventoryRole(string tenantId, string userId, int id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/user/{tenantId}/users/{userId}/roles/inventory/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/LoginOptionsApi.cs b/Client/Com/Cumulocity/Client/Api/LoginOptionsApi.cs new file mode 100644 index 0000000..ee1a63c --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/LoginOptionsApi.cs @@ -0,0 +1,127 @@ +/// +/// LoginOptionsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to retrieve the login options configured in the tenant. + /// + /// More detailed information about the parameters and their meaning can be found in [Administration > Changing settings](https://cumulocity.com/guides/users-guide/administration/#changing-settings) in the *Users guide*. + /// > **ⓘ Info:** If OAuth external is the only login option shown in the response, the user will be automatically redirected to the SSO login screen. + /// + /// + #nullable enable + public class LoginOptionsApi : AdaptableApi + { + public LoginOptionsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve the login options
+ /// Retrieve the login options available in the tenant. + ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the login options are sent in the response. + /// + /// + /// HTTP 400 + /// Bad request – invalid parameters. + /// + /// + ///
+ /// If this is set to `true`, the management tenant login options will be returned. > **ⓘ Info:** The `tenantId` parameter must not be present in the request when using the `management` parameter, otherwise it will cause an error. + /// Unique identifier of a Cumulocity IoT tenant. + /// + public async Task GetLoginOptions(bool? management = null, string? tenantId = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/tenant/loginOptions")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"management", management}, + {"tenantId", tenantId} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.loginoptioncollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a login option
+ /// Create an authentication configuration on your tenant.
Required roles
ROLE_TENANT_ADMIN OR ROLE_TENANT_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A login option was created. + /// + /// + /// HTTP 400 + /// Duplicated – The login option already exists. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateLoginOption(AuthConfig body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/tenant/loginOptions")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.authconfig+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.authconfig+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.authconfig+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/LoginTokensApi.cs b/Client/Com/Cumulocity/Client/Api/LoginTokensApi.cs new file mode 100644 index 0000000..69d5f63 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/LoginTokensApi.cs @@ -0,0 +1,35 @@ +/// +/// LoginTokensApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to obtain access tokens to the Cumulocity IoT platform in case of OAI-Secure or SSO authentication. + /// + #nullable enable + public class LoginTokensApi : AdaptableApi + { + public LoginTokensApi(HttpClient httpClient) : base(httpClient) + { + } + + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/ManagedObjectsApi.cs b/Client/Com/Cumulocity/Client/Api/ManagedObjectsApi.cs new file mode 100644 index 0000000..9d51208 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/ManagedObjectsApi.cs @@ -0,0 +1,574 @@ +/// +/// ManagedObjectsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// The inventory stores devices and other assets relevant to your IoT solution. We refer to them as managed objects and such can be “smart objects”, for example, smart electricity meters, home automation gateways or GPS devices. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class ManagedObjectsApi : AdaptableApi + { + public ManagedObjectsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all managed objects
+ /// Retrieve all managed objects (for example, devices, assets, etc.) registered in your tenant, or a subset based on queries. + ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the collection of objects is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 422 + /// Invalid data was sent. + /// + /// + ///
+ /// Search for a specific child addition and list all the groups to which it belongs. + /// Search for a specific child asset and list all the groups to which it belongs. + /// Search for a specific child device and list all the groups to which it belongs. + /// The current page of the paginated results. + /// A characteristic which identifies a managed object or event, for example, geolocation, electricity sensor, relay state. + /// The managed object IDs to search for (comma separated). + /// When set to `true` it returns managed objects which don't have any parent. If the current user doesn't have access to the parent, this is also root for the user. + /// Username of the owner of the managed objects. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// Similar to the parameter `query`, but it assumes that this is a device query request and it adds automatically the search criteria `fragmentType=c8y_IsDevice`. + /// Use query language to perform operations and/or filter the results. Details about the properties and supported operations can be found in [Query language](#tag/Query-language). + /// When set to `true`, the returned references of child devices won't contain their names. + /// Search for managed objects where any property value is equal to the given one. Only string values are supported. + /// The type of managed object to search for. + /// Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. + /// When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). + /// When set to `true` it returns additional information about the groups to which the searched managed object belongs. This results in setting the `assetParents` property with additional information about the groups. + /// When set to `true`, the returned references of child parents will return the device's parents (if any). Otherwise, it will be an empty array. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetManagedObjects(string? childAdditionId = null, string? childAssetId = null, string? childDeviceId = null, int? currentPage = null, string? fragmentType = null, List? ids = null, bool? onlyRoots = null, string? owner = null, int? pageSize = null, string? q = null, string? query = null, bool? skipChildrenNames = null, string? text = null, string? type = null, bool? withChildren = null, bool? withChildrenCount = null, bool? withGroups = null, bool? withParents = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"childAdditionId", childAdditionId}, + {"childAssetId", childAssetId}, + {"childDeviceId", childDeviceId}, + {"currentPage", currentPage}, + {"fragmentType", fragmentType}, + {"ids", ids}, + {"onlyRoots", onlyRoots}, + {"owner", owner}, + {"pageSize", pageSize}, + {"q", q}, + {"query", query}, + {"skipChildrenNames", skipChildrenNames}, + {"text", text}, + {"type", type}, + {"withChildren", withChildren}, + {"withChildrenCount", withChildrenCount}, + {"withGroups", withGroups}, + {"withParents", withParents}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a managed object
+ /// Create a managed object, for example, a device with temperature measurements support or a binary switch.
In general, each managed object may consist of: * A unique identifier that references the object. * The name of the object. * The most specific type of the managed object. * A time stamp showing the last update. * Fragments with specific meanings, for example, `c8y_IsDevice`, `c8y_SupportedOperations`. * Any additional custom fragments. Imagine, for example, that you want to describe electric meters from different vendors. Depending on the make of the meter, one may have a relay and one may be capable to measure a single phase or three phases (for example, a three-phase electricity sensor). A fragment `c8y_ThreePhaseElectricitySensor` would identify such an electric meter. Devices' characteristics are identified by storing fragments for each of them. > **ⓘ Info:** For more details about fragments with specific meanings, review the sections [Device management library](#section/Device-management-library) and [Sensor library](#section/Sensor-library).
Required roles
ROLE_INVENTORY_ADMIN OR ROLE_INVENTORY_CREATE
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A managed object was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateManagedObject(ManagedObject body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("additionParents"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("childDevices"); + jsonNode?.RemoveFromNode("childAssets"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("childAdditions"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("assetParents"); + jsonNode?.RemoveFromNode("deviceParents"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobject+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobject+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobject+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve the total number of managed objects
+ /// Retrieve the total number of managed objects (for example, devices, assets, etc.) registered in your tenant, or a subset based on queries.
Required roles
ROLE_INVENTORY_READ is not required, but if the current user doesn't have this role, the response will contain the number of inventory objects accessible for the user.
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the number of managed objects is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Search for a specific child addition and list all the groups to which it belongs. + /// Search for a specific child asset and list all the groups to which it belongs. + /// Search for a specific child device and list all the groups to which it belongs. + /// A characteristic which identifies a managed object or event, for example, geolocation, electricity sensor, relay state. + /// The managed object IDs to search for (comma separated). + /// Username of the owner of the managed objects. + /// Search for managed objects where any property value is equal to the given one. Only string values are supported. + /// The type of managed object to search for. + /// + public async Task GetNumberOfManagedObjects(string? childAdditionId = null, string? childAssetId = null, string? childDeviceId = null, string? fragmentType = null, List? ids = null, string? owner = null, string? text = null, string? type = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/count")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"childAdditionId", childAdditionId}, + {"childAssetId", childAssetId}, + {"childDeviceId", childDeviceId}, + {"fragmentType", fragmentType}, + {"ids", ids}, + {"owner", owner}, + {"text", text}, + {"type", type} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, text/plain,application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific managed object
+ /// Retrieve a specific managed object (for example, device, group, template) by a given ID.
Required roles
ROLE_INVENTORY_READ OR owner of the source OR MANAGE_OBJECT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the object is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// When set to `true`, the returned references of child devices won't contain their names. + /// Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. + /// When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). + /// When set to `true`, the returned references of child parents will return the device's parents (if any). Otherwise, it will be an empty array. + /// + public async Task GetManagedObject(string id, bool? skipChildrenNames = null, bool? withChildren = null, bool? withChildrenCount = null, bool? withParents = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"skipChildrenNames", skipChildrenNames}, + {"withChildren", withChildren}, + {"withChildrenCount", withChildrenCount}, + {"withParents", withParents} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobject+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific managed object
+ /// Update a specific managed object (for example, device) by a given ID. For example, if you want to specify that your managed object is a device, you must add the fragment `c8y_IsDevice`.
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source OR MANAGE_OBJECT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A managed object was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + /// + public async Task UpdateManagedObject(ManagedObject body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("owner"); + jsonNode?.RemoveFromNode("additionParents"); + jsonNode?.RemoveFromNode("lastUpdated"); + jsonNode?.RemoveFromNode("childDevices"); + jsonNode?.RemoveFromNode("childAssets"); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("childAdditions"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("assetParents"); + jsonNode?.RemoveFromNode("deviceParents"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobject+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobject+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobject+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific managed object
+ /// Remove a specific managed object (for example, device) by a given ID. > **ⓘ Info:** Inventory DELETE requests are not synchronous. The response could be returned before the delete request has been completed. This may happen especially when the deleted managed object has a lot of associated data. After sending the request, the platform starts deleting the associated data in an asynchronous way. Finally, the requested managed object is deleted after all associated data has been deleted.
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source OR MANAGE_OBJECT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A managed object was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// When set to `true` and the managed object is a device or group, all the hierarchy will be deleted. + /// When set to `true` all the hierarchy will be deleted without checking the type of managed object. It takes precedence over the parameter `cascade`. + /// When set to `true` and the managed object is a device, it deletes the associated device user (credentials). + public async Task DeleteManagedObject(string id, bool? cascade = null, bool? forceCascade = null, bool? withDeviceUser = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"cascade", cascade}, + {"forceCascade", forceCascade}, + {"withDeviceUser", withDeviceUser} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve the latest availability date of a specific managed object
+ /// Retrieve the date when a specific managed object (by a given ID) sent the last message to Cumulocity IoT.
Required roles
ROLE_INVENTORY_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the date is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// + public async Task GetLatestAvailability(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/availability")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, text/plain, application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve all supported measurement fragments of a specific managed object
+ /// Retrieve all measurement types of a specific managed object by a given ID.
Required roles
ROLE_INVENTORY_READ OR owner of the source OR MANAGE_OBJECT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all measurement types are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// + public async Task GetSupportedMeasurements(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/supportedMeasurements")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve all supported measurement fragments and series of a specific managed object
+ /// Retrieve all supported measurement fragments and series of a specific managed object by a given ID.
Required roles
ROLE_INVENTORY_READ OR owner of the source OR MANAGE_OBJECT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all supported measurement series are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// + public async Task GetSupportedSeries(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/supportedSeries")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve the username and state of a specific managed object
+ /// Retrieve the device owner's username and state (enabled or disabled) of a specific managed object (by a given ID).
Required roles
ROLE_INVENTORY_READ OR owner of the source OR MANAGE_OBJECT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the username and state are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// Unique identifier of the managed object. + /// + public async Task GetManagedObjectUser(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/user")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.managedobjectuser+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update the user's details of a specific managed object
+ /// Update the device owner's state (enabled or disabled) of a specific managed object (by a given ID).
Required roles
ROLE_INVENTORY_ADMIN OR owner of the source OR MANAGE_OBJECT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The user's details of a specific managed object were updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Managed object not found. + /// + /// + ///
+ /// + /// Unique identifier of the managed object. + /// + public async Task UpdateManagedObjectUser(ManagedObjectUser body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("userName"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/inventory/managedObjects/{id}/user")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.managedobjectuser+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.managedobjectuser+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.managedobjectuser+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/MeasurementsApi.cs b/Client/Com/Cumulocity/Client/Api/MeasurementsApi.cs new file mode 100644 index 0000000..5d5f261 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/MeasurementsApi.cs @@ -0,0 +1,376 @@ +/// +/// MeasurementsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// Measurements are produced by reading sensor values. In some cases, this data is read in static intervals and sent to the platform (for example, temperature sensors or electrical meters). In other cases, the data is read on demand or at irregular intervals (for example, health devices such as weight scales). Regardless what kind of protocol the device supports, the agent is responsible for converting it into a "push" protocol by uploading data to Cumulocity IoT. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class MeasurementsApi : AdaptableApi + { + public MeasurementsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all measurements
+ /// Retrieve all measurements on your tenant, or a specific subset based on queries. In case of executing [range queries](https://en.wikipedia.org/wiki/Range_query_(database)) between an upper and lower boundary, for example, querying using `dateFrom`–`dateTo`, the oldest registered measurements are returned first. It is possible to change the order using the query parameter `revert=true`. For large measurement collections, querying older records without filters can be slow as the server needs to scan from the beginning of the input results set before beginning to return the results. For cases when older measurements should be retrieved, it is recommended to narrow the scope by using range queries based on the time stamp reported by a device. The scope of query can also be reduced significantly when a source device is provided. Review [Measurements Specifics](#tag/Measurements-Specifics) for details about data streaming and response formats.
Required roles
ROLE_MEASUREMENT_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and all measurements are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The current page of the paginated results. + /// Start date or date and time of the measurement. + /// End date or date and time of the measurement. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// If you are using a range query (that is, at least one of the `dateFrom` or `dateTo` parameters is included in the request), then setting `revert=true` will sort the results by the latest measurements first. By default, the results are sorted by the oldest measurements first. + /// The managed object ID to which the measurement is associated. + /// The type of measurement to search for. + /// The specific series to search for. + /// A characteristic which identifies the measurement. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetMeasurements(int? currentPage = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, int? pageSize = null, bool? revert = null, string? source = null, string? type = null, string? valueFragmentSeries = null, string? valueFragmentType = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/measurement/measurements")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"pageSize", pageSize}, + {"revert", revert}, + {"source", source}, + {"type", type}, + {"valueFragmentSeries", valueFragmentSeries}, + {"valueFragmentType", valueFragmentType}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.measurementcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a measurement
+ /// A measurement must be associated with a source (managed object) identified by ID, and must specify the type of measurement and the time when it was measured by the device (for example, a thermometer). Each measurement fragment is an object (for example, `c8y_Steam`) containing the actual measurements as properties. The property name represents the name of the measurement (for example, `Temperature`) and it contains two properties: * `value` - The value of the individual measurement. The maximum precision for floating point numbers is 64-bit IEEE 754. For integers it's a 64-bit two's complement integer. * `unit` - The unit of the measurements. Review the [System of units](#section/System-of-units) section for details about the conversions of units. Also review the [Naming conventions of fragments](https://cumulocity.com/guides/concepts/domain-model/#naming-conventions-of-fragments) in the Concepts guide. The example below uses `c8y_Steam` in the request body to illustrate a fragment for recording temperature measurements. > **⚠️ Important:** Property names used for fragment and series must not contain whitespaces nor the special characters `. , * [ ] ( ) @ $`. This is required to ensure a correct processing and visualization of measurement series on UI graphs. ### Create multiple measurements It is also possible to create multiple measurements at once by sending a `measurements` array containing all the measurements to be created. The content type must be `application/vnd.com.nsn.cumulocity.measurementcollection+json`. > **ⓘ Info:** For more details about fragments with specific meanings, review the sections [Device management library](#section/Device-management-library) and [Sensor library](#section/Sensor-library).
Required roles
ROLE_MEASUREMENT_ADMIN OR owner of the source OR MEASUREMENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A measurement was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateMeasurement(Measurement body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("source", "self"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/measurement/measurements")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.measurement+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.measurement+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.measurement+json, application/vnd.com.nsn.cumulocity.measurementcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a measurement
+ /// A measurement must be associated with a source (managed object) identified by ID, and must specify the type of measurement and the time when it was measured by the device (for example, a thermometer). Each measurement fragment is an object (for example, `c8y_Steam`) containing the actual measurements as properties. The property name represents the name of the measurement (for example, `Temperature`) and it contains two properties: * `value` - The value of the individual measurement. The maximum precision for floating point numbers is 64-bit IEEE 754. For integers it's a 64-bit two's complement integer. * `unit` - The unit of the measurements. Review the [System of units](#section/System-of-units) section for details about the conversions of units. Also review the [Naming conventions of fragments](https://cumulocity.com/guides/concepts/domain-model/#naming-conventions-of-fragments) in the Concepts guide. The example below uses `c8y_Steam` in the request body to illustrate a fragment for recording temperature measurements. > **⚠️ Important:** Property names used for fragment and series must not contain whitespaces nor the special characters `. , * [ ] ( ) @ $`. This is required to ensure a correct processing and visualization of measurement series on UI graphs. ### Create multiple measurements It is also possible to create multiple measurements at once by sending a `measurements` array containing all the measurements to be created. The content type must be `application/vnd.com.nsn.cumulocity.measurementcollection+json`. > **ⓘ Info:** For more details about fragments with specific meanings, review the sections [Device management library](#section/Device-management-library) and [Sensor library](#section/Sensor-library).
Required roles
ROLE_MEASUREMENT_ADMIN OR owner of the source OR MEASUREMENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// A measurement was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateMeasurement(MeasurementCollection body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("next"); + jsonNode?.RemoveFromNode("prev"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("statistics"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/measurement/measurements")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.measurementcollection+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.measurementcollection+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.measurement+json, application/vnd.com.nsn.cumulocity.measurementcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove measurement collections
+ /// Remove measurement collections specified by query parameters. DELETE requests are not synchronous. The response could be returned before the delete request has been completed. This may happen especially when there are a lot of measurements to be deleted. > **⚠️ Important:** Note that it is possible to call this endpoint without providing any parameter - it may result in deleting all measurements and it is not recommended.
Required roles
ROLE_MEASUREMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A collection of measurements was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// Start date or date and time of the measurement. + /// End date or date and time of the measurement. + /// A characteristic which identifies a managed object or event, for example, geolocation, electricity sensor, relay state. + /// The managed object ID to which the measurement is associated. + /// The type of measurement to search for. + public async Task DeleteMeasurements(System.DateTime? dateFrom = null, System.DateTime? dateTo = null, string? fragmentType = null, string? source = null, string? type = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/measurement/measurements")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"fragmentType", fragmentType}, + {"source", source}, + {"type", type} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a specific measurement
+ /// Retrieve a specific measurement by a given ID.
Required roles
ROLE_MEASUREMENT_READ OR owner of the source OR MEASUREMENT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the measurement is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Measurement not found. + /// + /// + ///
+ /// Unique identifier of the measurement. + /// + public async Task GetMeasurement(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/measurement/measurements/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.measurement+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Remove a specific measurement
+ /// Remove a specific measurement by a given ID.
Required roles
ROLE_MEASUREMENT_ADMIN OR owner of the source OR MEASUREMENT_ADMIN permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A measurement was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// Measurement not found. + /// + /// + ///
+ /// Unique identifier of the measurement. + public async Task DeleteMeasurement(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/measurement/measurements/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a list of series and their values
+ /// Retrieve a list of series (all or only those matching the specified names) and their values within a given period of a specific managed object (source).
A series is any fragment in measurement that contains a `value` property. It is possible to fetch aggregated results using the `aggregationType` parameter. If the aggregation is not specified, the result will contain no more than 5000 values. > **⚠️ Important:** For the aggregation to be done correctly, a device shall always use the same time zone when it sends dates.
Required roles
ROLE_MEASUREMENT_READ OR owner of the source OR MEASUREMENT_READ permission on the source
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the series are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// Fetch aggregated results as specified. + /// Start date or date and time of the measurement. + /// End date or date and time of the measurement. + /// If you are using a range query (that is, at least one of the `dateFrom` or `dateTo` parameters is included in the request), then setting `revert=true` will sort the results by the latest measurements first. By default, the results are sorted by the oldest measurements first. + /// The specific series to search for. + /// The managed object ID to which the measurement is associated. + /// + public async Task GetMeasurementSeries(string? aggregationType = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, bool? revert = null, List? series = null, string? source = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/measurement/measurements/series")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"aggregationType", aggregationType}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"revert", revert}, + {"series", series}, + {"source", source} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/NewDeviceRequestsApi.cs b/Client/Com/Cumulocity/Client/Api/NewDeviceRequestsApi.cs new file mode 100644 index 0000000..e54238d --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/NewDeviceRequestsApi.cs @@ -0,0 +1,243 @@ +/// +/// NewDeviceRequestsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to create, retrieve, update and delete new device requests in Cumulocity IoT. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class NewDeviceRequestsApi : AdaptableApi + { + public NewDeviceRequestsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve a list of new device requests
+ /// Retrieve a list of new device requests.
Required roles
ROLE_DEVICE_CONTROL_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the list of new device requests sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetNewDeviceRequests(int? currentPage = null, int? pageSize = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/newDeviceRequests")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.newdevicerequestcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create a new device request
+ /// Create a new device request.
Required roles
ROLE_DEVICE_CONTROL_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A new device request was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + /// + public async Task CreateNewDeviceRequest(NewDeviceRequest body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("status"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/newDeviceRequests")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.newdevicerequest+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.newdevicerequest+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.newdevicerequest+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Retrieve a specific new device request
+ /// Retrieve a specific new device request (by a given ID).
Required roles
ROLE_DEVICE_CONTROL_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the new device request is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// New device request not found. + /// + /// + ///
+ /// Unique identifier of the new device request. + /// + public async Task GetNewDeviceRequest(string requestId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/newDeviceRequests/{requestId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.newdevicerequest+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific new device request status
+ /// Update a specific new device request (by a given ID). You can only update its status.
Required roles
ROLE_DEVICE_CONTROL_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// A new device request was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// New device request not found. + /// + /// + ///
+ /// + /// Unique identifier of the new device request. + /// + public async Task UpdateNewDeviceRequest(NewDeviceRequest body, string requestId) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/newDeviceRequests/{requestId}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.newdevicerequest+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.newdevicerequest+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.newdevicerequest+json, application/vnd.com.nsn.cumulocity.error+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Delete a specific new device request
+ /// Delete a specific new device request (by a given ID).
Required roles
ROLE_USER_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A new device request was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + /// HTTP 404 + /// New device request not found. + /// + /// + ///
+ /// Unique identifier of the new device request. + public async Task DeleteNewDeviceRequest(string requestId) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/newDeviceRequests/{requestId}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/OperationsApi.cs b/Client/Com/Cumulocity/Client/Api/OperationsApi.cs new file mode 100644 index 0000000..c725986 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/OperationsApi.cs @@ -0,0 +1,286 @@ +/// +/// OperationsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to create, retrieve, update and delete operations in Cumulocity IoT. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class OperationsApi : AdaptableApi + { + public OperationsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve a list of operations
+ /// Retrieve a list of operations. Notes about operation collections: * The embedded operation object contains `deviceExternalIDs` only when queried with an `agentId` parameter. * The embedded operation object is filled with `deviceName`, but only when requesting resource: Get a collection of operations. * Operations are returned in the order of their ascending IDs.
Required roles
ROLE_DEVICE_CONTROL_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the list of operations is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// An agent ID that may be part of the operation. If this parameter is set, the operation response objects contain the `deviceExternalIDs` object. + /// The bulk operation ID that this operation belongs to. + /// The current page of the paginated results. + /// Start date or date and time of the operation. + /// End date or date and time of the operation. + /// The ID of the device the operation is performed for. + /// The type of fragment that must be part of the operation. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// If you are using a range query (that is, at least one of the `dateFrom` or `dateTo` parameters is included in the request), then setting `revert=true` will sort the results by the newest operations first. By default, the results are sorted by the oldest operations first. + /// Status of the operation. + /// When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetOperations(string? agentId = null, string? bulkOperationId = null, int? currentPage = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, string? deviceId = null, string? fragmentType = null, int? pageSize = null, bool? revert = null, string? status = null, bool? withTotalElements = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/operations")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"agentId", agentId}, + {"bulkOperationId", bulkOperationId}, + {"currentPage", currentPage}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"deviceId", deviceId}, + {"fragmentType", fragmentType}, + {"pageSize", pageSize}, + {"revert", revert}, + {"status", status}, + {"withTotalElements", withTotalElements}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.operationcollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create an operation
+ /// Create an operation.
Required roles
ROLE_DEVICE_CONTROL_ADMIN OR owner of the device OR ADMIN permissions on the device
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 201 + /// An operation was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// + /// + public async Task CreateOperation(Operation body) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("deviceExternalIDs", "self"); + jsonNode?.RemoveFromNode("bulkOperationId"); + jsonNode?.RemoveFromNode("failureReason"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/operations")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.operation+json"), + Method = HttpMethod.Post, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.operation+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.operation+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Delete a list of operations
+ /// Delete a list of operations. The DELETE method allows for deletion of operation collections.
Required roles
ROLE_DEVICE_CONTROL_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 204 + /// A list of operations was removed. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 403 + /// Not authorized to perform this operation. + /// + /// + ///
+ /// An agent ID that may be part of the operation. + /// Start date or date and time of the operation. + /// End date or date and time of the operation. + /// The ID of the device the operation is performed for. + /// Status of the operation. + public async Task DeleteOperations(string? agentId = null, System.DateTime? dateFrom = null, System.DateTime? dateTo = null, string? deviceId = null, string? status = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/operations")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"agentId", agentId}, + {"dateFrom", dateFrom}, + {"dateTo", dateTo}, + {"deviceId", deviceId}, + {"status", status} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Delete, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return responseStream; + } + + /// + /// Retrieve a specific operation
+ /// Retrieve a specific operation (by a given ID).
Required roles
ROLE_DEVICE_CONTROL_READ OR owner of the resource OR ADMIN permission on the device
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the operation is sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Operation not found. + /// + /// + ///
+ /// Unique identifier of the operation. + /// + public async Task GetOperation(string id) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/operations/{id}")); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.operation+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Update a specific operation status
+ /// Update a specific operation (by a given ID). You can only update its status.
Required roles
ROLE_DEVICE_CONTROL_ADMIN OR owner of the resource OR ADMIN permission on the device
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An operation was updated. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 404 + /// Operation not found. + /// + /// + /// HTTP 422 + /// Validation error. + /// + /// + ///
+ /// + /// Unique identifier of the operation. + /// + public async Task UpdateOperation(Operation body, string id) + { + var jsonNode = ToJsonNode(body); + jsonNode?.RemoveFromNode("creationTime"); + jsonNode?.RemoveFromNode("deviceExternalIDs", "self"); + jsonNode?.RemoveFromNode("com_cumulocity_model_WebCamDevice"); + jsonNode?.RemoveFromNode("bulkOperationId"); + jsonNode?.RemoveFromNode("failureReason"); + jsonNode?.RemoveFromNode("self"); + jsonNode?.RemoveFromNode("id"); + jsonNode?.RemoveFromNode("deviceId"); + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/devicecontrol/operations/{id}")); + var request = new HttpRequestMessage + { + Content = new StringContent(jsonNode.ToString(), Encoding.UTF8, "application/vnd.com.nsn.cumulocity.operation+json"), + Method = HttpMethod.Put, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.com.nsn.cumulocity.operation+json"); + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.operation+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + } + #nullable disable +} diff --git a/Client/Com/Cumulocity/Client/Api/OptionsApi.cs b/Client/Com/Cumulocity/Client/Api/OptionsApi.cs new file mode 100644 index 0000000..7e54897 --- /dev/null +++ b/Client/Com/Cumulocity/Client/Api/OptionsApi.cs @@ -0,0 +1,319 @@ +/// +/// OptionsApi.cs +/// CumulocityCoreLibrary +/// +/// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. +/// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. +/// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Com.Cumulocity.Client.Model; +using Com.Cumulocity.Client.Supplementary; + +namespace Com.Cumulocity.Client.Api +{ + /// + /// API methods to retrieve the options configured in the tenant. + /// + /// > **ⓘ Info:** The Accept header should be provided in all POST/PUT requests, otherwise an empty response body will be returned. + /// + /// + #nullable enable + public class OptionsApi : AdaptableApi + { + public OptionsApi(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// Retrieve all options
+ /// Retrieve all the options available on the tenant.
Required roles
ROLE_OPTION_MANAGEMENT_READ
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// The request has succeeded and the options are sent in the response. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + ///
+ /// The current page of the paginated results. + /// Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. + /// When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). + /// + public async Task GetOptions(int? currentPage = null, int? pageSize = null, bool? withTotalPages = null) + { + var client = HttpClient; + var uriBuilder = new UriBuilder(new Uri($"{client?.BaseAddress?.AbsoluteUri}/tenant/options")); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + var allQueryParameter = new Dictionary() + { + #pragma warning disable CS8604 // Possible null reference argument. + {"currentPage", currentPage}, + {"pageSize", pageSize}, + {"withTotalPages", withTotalPages} + #pragma warning restore CS8604 // Possible null reference argument. + }; + allQueryParameter.Where(p => p.Value != null).AsParallel().ForAll(e => queryString.Add(e.Key, $"{e.Value}")); + uriBuilder.Query = queryString.ToString(); + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri(uriBuilder.ToString()) + }; + request.Headers.TryAddWithoutValidation("Accept", "application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.optioncollection+json"); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + using var responseStream = await response.Content.ReadAsStreamAsync(); + return await JsonSerializer.DeserializeAsync(responseStream); + } + + /// + /// Create an option
+ /// Create an option on your tenant. Options are category-key-value tuples which store tenant configurations. Some categories of options allow the creation of new ones, while others are limited to predefined set of keys. Any option of any tenant can be defined as "non-editable" by the "management" tenant; once done, any PUT or DELETE requests made on that option by the tenant owner will result in a 403 error (Unauthorized). ### Default option categories **access.control** | Key | Default value | Predefined | Description | |--|--|--|--| | allow.origin | * | Yes | Comma separated list of domains allowed for execution of CORS. Wildcards are allowed (for example, `*.cumuclocity.com`) | **alarm.type.mapping** | Key | Predefined | Description | |--|--|--| | <ALARM_TYPE> | No | Overrides the severity and alarm text for the alarm with type <ALARM_TYPE>. The severity and text are specified as `\|`. If either part is empty, the value will not be overridden. If the severity is NONE, the alarm will be suppressed. Example: `"CRITICAL\|temperature too high"`| ### Encrypted credentials Adding a "credentials." prefix to the `key` will make the `value` of the option encrypted. When the option is sent to a microservice, the "credentials." prefix is removed and the `value` is decrypted. For example: ```json { "category": "secrets", "key": "credentials.mykey", "value": "myvalue" } ``` In that particular example, the request will contain an additional header `"Mykey": "myvalue"`.
Required roles
ROLE_OPTION_MANAGEMENT_ADMIN
+ ///
The following table gives an overview of the possible response codes and their meanings:
+ /// + /// + /// HTTP 200 + /// An option was created. + /// + /// + /// HTTP 401 + /// Authentication information is missing or invalid. + /// + /// + /// HTTP 422 + /// Unprocessable Entity – invalid payload. + /// + /// + ///
+ /// + /// + public async Task CreateOption(Option body) + { + var jsonNode = ToJsonNode