/// <inheritdoc/>
        public async Task <List <InstanceEvent> > GetInstanceEvents(string instanceId, string instanceOwnerId, string org, string app, string[] eventTypes, string from, string to)
        {
            string apiUrl = $"{instanceOwnerId}/{instanceId}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            if (eventTypes != null)
            {
                StringBuilder bld = new StringBuilder();
                foreach (string type in eventTypes)
                {
                    bld.Append($"&eventTypes={type}");
                }

                apiUrl += bld.ToString();
            }

            if (!(string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to)))
            {
                apiUrl += $"&from={from}&to={to}";
            }

            HttpResponseMessage response = await _client.GetAsync(token, apiUrl);

            if (response.IsSuccessStatusCode)
            {
                string eventData = await response.Content.ReadAsStringAsync();

                List <InstanceEvent> instanceEvents = JsonConvert.DeserializeObject <List <InstanceEvent> >(eventData);

                return(instanceEvents);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #2
0
        public async Task <DataElement> InsertFormData <T>(Instance instance, string dataType, T dataToSerialize, Type type)
        {
            string      apiUrl = $"instances/{instance.Id}/data?dataType={dataType}";
            string      token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);
            DataElement dataElement;

            XmlSerializer serializer = new XmlSerializer(type);

            using MemoryStream stream = new MemoryStream();

            serializer.Serialize(stream, dataToSerialize);
            stream.Position = 0;
            StreamContent streamContent = new StreamContent(stream);

            streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
            HttpResponseMessage response = await _client.PostAsync(token, apiUrl, streamContent);

            if (response.IsSuccessStatusCode)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                dataElement = JsonConvert.DeserializeObject <DataElement>(instanceData);

                return(dataElement);
            }

            _logger.Log(LogLevel.Error, "unable to save form data for instance{0} due to response {1}", instance.Id, response.StatusCode);
            throw await PlatformHttpException.CreateAsync(response);
        }
        public async Task AddCompleteConfirmation_StorageReturnsNonSuccess_ThrowsPlatformHttpException()
        {
            // Arrange
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.Forbidden,
                Content    = new StringContent("Error message", Encoding.UTF8, "application/json"),
            };

            InitializeMocks(httpResponseMessage, "complete");

            HttpClient httpClient = new HttpClient(handlerMock.Object);

            InstanceAppSI target = new InstanceAppSI(platformSettingsOptions.Object, logger.Object, contextAccessor.Object, httpClient, appSettingsOptions.Object);

            PlatformHttpException actualException = null;

            // Act
            try
            {
                await target.AddCompleteConfirmation(1337, Guid.NewGuid());
            }
            catch (PlatformHttpException e)
            {
                actualException = e;
            }

            // Assert
            handlerMock.VerifyAll();

            Assert.NotNull(actualException);
        }
        /// <inheritdoc />
        /// Get instances of an instance owner.
        public async Task <List <Instance> > GetInstances(int instanceOwnerPartyId)
        {
            string apiUrl = $"instances/{instanceOwnerPartyId}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            HttpResponseMessage response = await _client.GetAsync(token, apiUrl);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                List <Instance> instances = JsonConvert.DeserializeObject <List <Instance> >(instanceData);

                return(instances);
            }
            else if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }
            else
            {
                _logger.LogError("Unable to fetch instances");
                throw await PlatformHttpException.CreateAsync(response);
            }
        }
Exemple #5
0
        public async Task <int> PartyLookup(string orgNo, string person)
        {
            string eventsPath = Path.Combine(GetPartiesPath(), $@"{_partiesCollection}.json");
            int    partyId    = 0;

            if (File.Exists(eventsPath))
            {
                string       content = File.ReadAllText(eventsPath);
                List <Party> parties = JsonConvert.DeserializeObject <List <Party> >(content);

                if (!string.IsNullOrEmpty(orgNo))
                {
                    partyId = parties.Where(p => p.OrgNumber != null && p.OrgNumber.Equals(orgNo)).Select(p => p.PartyId).FirstOrDefault();
                }
                else
                {
                    partyId = parties.Where(p => p.SSN != null && p.SSN.Equals(person)).Select(p => p.PartyId).FirstOrDefault();
                }
            }

            return(partyId > 0
                ? partyId
                : throw await PlatformHttpException.CreateAsync(new HttpResponseMessage
                                                                { Content = new StringContent(string.Empty), StatusCode = System.Net.HttpStatusCode.NotFound }));
        }
Exemple #6
0
        /// <inheritdoc />
        public async Task <object> GetFormData(Guid instanceGuid, Type type, string org, string app, int instanceOwnerId, Guid dataId)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string apiUrl             = $"instances/{instanceIdentifier}/data/{dataId}";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            HttpResponseMessage response = await _client.GetAsync(token, apiUrl);

            if (response.IsSuccessStatusCode)
            {
                XmlSerializer serializer = new XmlSerializer(type);
                try
                {
                    using Stream stream = await response.Content.ReadAsStreamAsync();

                    return(serializer.Deserialize(stream));
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Cannot deserialize XML form data read from storage: {ex}");
                    throw new ServiceException(HttpStatusCode.Conflict, $"Cannot deserialize XML form data from storage", ex);
                }
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #7
0
        /// <inheritdoc />
        public async Task <DataElement> UpdateData <T>(T dataToSerialize, Guid instanceGuid, Type type, string org, string app, int instanceOwnerId, Guid dataId)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string apiUrl             = $"instances/{instanceIdentifier}/data/{dataId}";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            XmlSerializer serializer = new XmlSerializer(type);

            using MemoryStream stream = new MemoryStream();
            serializer.Serialize(stream, dataToSerialize);
            stream.Position = 0;
            StreamContent streamContent = new StreamContent(stream);

            streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");

            HttpResponseMessage response = await _client.PutAsync(token, apiUrl, streamContent);

            if (response.IsSuccessStatusCode)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                DataElement dataElement = JsonConvert.DeserializeObject <DataElement>(instanceData);
                return(dataElement);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #8
0
        /// <inheritdoc />
        public async Task <List <AttachmentList> > GetBinaryDataList(string org, string app, int instanceOwnerId, Guid instanceGuid)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string apiUrl             = $"instances/{instanceIdentifier}/dataelements";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            DataElementList       dataList;
            List <AttachmentList> attachmentList = new List <AttachmentList>();

            HttpResponseMessage response = await _client.GetAsync(token, apiUrl);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                dataList = JsonConvert.DeserializeObject <DataElementList>(instanceData);

                ExtractAttachments(dataList.DataElements, attachmentList);

                return(attachmentList);
            }

            _logger.Log(LogLevel.Error, "Unable to fetch attachment list {0}", response.StatusCode);

            throw await PlatformHttpException.CreateAsync(response);
        }
        /// <inheritdoc />
        public async Task <Instance> UpdateProcess(Instance instance)
        {
            ProcessState processState = instance.Process;

            string apiUrl = $"instances/{instance.Id}/process";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            string processStateString = JsonConvert.SerializeObject(processState);

            _logger.LogInformation($"update process state: {processStateString}");

            StringContent       httpContent = new StringContent(processStateString, Encoding.UTF8, "application/json");
            HttpResponseMessage response    = await _client.PutAsync(token, apiUrl, httpContent);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                Instance updatedInstance = JsonConvert.DeserializeObject <Instance>(instanceData);

                return(updatedInstance);
            }
            else
            {
                _logger.LogError($"Unable to update instance process with instance id {instance.Id}");
                throw await PlatformHttpException.CreateAsync(response);
            }
        }
Exemple #10
0
        public async Task <DataElement> InsertBinaryData(string instanceId, string dataType, string contentType, string fileName, Stream stream)
        {
            string      apiUrl = $"{_platformSettings.ApiStorageEndpoint}instances/{instanceId}/data?dataType={dataType}";
            string      token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);
            DataElement dataElement;

            StreamContent content = new StreamContent(stream);

            content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
            if (!string.IsNullOrEmpty(fileName))
            {
                string contentHeaderString = $"attachment; filename={fileName}";
                content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(contentHeaderString);
            }

            HttpResponseMessage response = await _client.PostAsync(token, apiUrl, content);

            if (response.IsSuccessStatusCode)
            {
                string instancedata = await response.Content.ReadAsStringAsync();

                dataElement = JsonConvert.DeserializeObject <DataElement>(instancedata);

                return(dataElement);
            }

            _logger.LogError($"Storing attachment for instance {instanceId} failed with status code {response.StatusCode} - content {await response.Content.ReadAsStringAsync()}");
            throw await PlatformHttpException.CreateAsync(response);
        }
        public async Task <Instance> UpdateSubstatus(int instanceOwnerPartyId, Guid instanceGuid, Substatus substatus)
        {
            DateTime creationTime = DateTime.UtcNow;

            if (substatus == null || string.IsNullOrEmpty(substatus.Label))
            {
                throw await PlatformHttpException.CreateAsync(
                          new System.Net.Http.HttpResponseMessage {
                    StatusCode = System.Net.HttpStatusCode.BadRequest
                });
            }

            string instancePath = GetInstancePath(instanceOwnerPartyId, instanceGuid);

            if (File.Exists(instancePath))
            {
                string   content        = File.ReadAllText(instancePath);
                Instance storedInstance = (Instance)JsonConvert.DeserializeObject(content, typeof(Instance));

                storedInstance.Status ??= new InstanceStatus();

                storedInstance.Status.Substatus = substatus;
                storedInstance.LastChanged      = creationTime;

                // mock does not set last changed by, but this is set by the platform.
                storedInstance.LastChangedBy = string.Empty;

                File.WriteAllText(instancePath, JsonConvert.SerializeObject(storedInstance));
                return(await GetInstance(storedInstance));
            }

            return(null);
        }
Exemple #12
0
        /// <inheritdoc/>
        public async Task <int> PartyLookup(string orgNo, string person)
        {
            string endpointUrl = "parties/lookup";

            PartyLookup partyLookup = new PartyLookup()
            {
                Ssn = person, OrgNo = orgNo
            };

            string bearerToken = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _generalSettings.JwtCookieName);
            string accessToken = _accessTokenGenerator.GenerateAccessToken("platform", "events");

            StringContent content = new StringContent(JsonSerializer.Serialize(partyLookup));

            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            HttpResponseMessage response = await _client.PostAsync(bearerToken, endpointUrl, content, accessToken);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Party party = await response.Content.ReadAsAsync <Party>();

                return(party.PartyId);
            }
            else
            {
                string reason = await response.Content.ReadAsStringAsync();

                _logger.LogError($"// RegisterService // PartyLookup // Failed to lookup party in platform register. Response {response}. \n Reason {reason}.");

                throw await PlatformHttpException.CreateAsync(response);
            }
        }
Exemple #13
0
        public Task <Instance> CreateInstance(string org, string app, Instance instanceTemplate)
        {
            HttpResponseMessage response = new HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.BadRequest,
                Content    = new StringContent("ERROR"),
            };

            throw PlatformHttpException.CreateAsync(response).Result;
        }
Exemple #14
0
        /// <inheritdoc />
        public async Task <Instance> GetInstance(Instance instance)
        {
            HttpResponseMessage response = new HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.BadRequest,
                Content    = new StringContent("ERROR"),
            };

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #15
0
        public async Task <Instance> GetInstance(string app, string org, int instanceOwnerPartyId, Guid instanceId)
        {
            HttpResponseMessage response = new HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.BadRequest,
                Content    = new StringContent("ERROR"),
            };

            throw await PlatformHttpException.CreateAsync(response);
        }
        public async Task AddEvent_TheServiceResponseIndicateFailure_ThrowsPlatformHttpException()
        {
            // Arrange
            Instance instance = new Instance
            {
                Org           = "ttd",
                InstanceOwner = new InstanceOwner {
                    OrganisationNumber = "org"
                }
            };

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadRequest,
                Content    = new StringContent(Guid.NewGuid().ToString()),
            };

            HttpRequestMessage actualRequest = null;

            void SetRequest(HttpRequestMessage request) => actualRequest = request;

            InitializeMocks(httpResponseMessage, SetRequest);

            HttpClient httpClient = new HttpClient(handlerMock.Object);

            EventsAppSI target = new EventsAppSI(
                platformSettingsOptions.Object,
                contextAccessor.Object,
                httpClient,
                accessTokenGeneratorMock.Object,
                appResourcesMock.Object,
                appSettingsOptions.Object,
                generalSettingsOptions.Object);

            PlatformHttpException actual = null;

            // Act
            try
            {
                await target.AddEvent("created", instance);
            }
            catch (PlatformHttpException platformHttpException)
            {
                actual = platformHttpException;
            }

            // Assert
            Assert.NotNull(actual);
            Assert.Equal(HttpStatusCode.BadRequest, actual.Response.StatusCode);

            Assert.NotNull(actualRequest);

            handlerMock.VerifyAll();
        }
Exemple #17
0
 private ActionResult HandlePlatformHttpException(PlatformHttpException e)
 {
     if (e.Response.StatusCode == HttpStatusCode.NotFound)
     {
         return(NotFound());
     }
     else
     {
         _logger.LogError($"// EventsController // HandlePlatformHttpException // Unexpected response from Altinn Platform. {e}");
         return(StatusCode(500, e));
     }
 }
        /// <inheritdoc/>
        public async Task <bool> DeleteAllInstanceEvents(string instanceId, string instanceOwnerId, string org, string app)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceId}";
            string apiUrl             = $"instances/{instanceIdentifier}/events";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            HttpResponseMessage response = await _client.DeleteAsync(token, apiUrl);

            if (response.IsSuccessStatusCode)
            {
                return(true);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #19
0
        /// <inheritdoc />
        public async Task <bool> DeleteBinaryData(string org, string app, int instanceOwnerId, Guid instanceGuid, Guid dataGuid)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string apiUrl             = $"instances/{instanceIdentifier}/data/{dataGuid}";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            HttpResponseMessage response = await _client.DeleteAsync(token, apiUrl);

            if (response.IsSuccessStatusCode)
            {
                return(true);
            }

            _logger.LogError($"Deleting form attachment {dataGuid} for instance {instanceGuid} failed with status code {response.StatusCode}");
            throw await PlatformHttpException.CreateAsync(response);
        }
        /// <inheritdoc/>
        public async Task <string> AddEvent(string eventType, Instance instance)
        {
            string alternativeSubject = null;

            if (!string.IsNullOrWhiteSpace(instance.InstanceOwner.OrganisationNumber))
            {
                alternativeSubject = $"/org/{instance.InstanceOwner.OrganisationNumber}";
            }

            if (!string.IsNullOrWhiteSpace(instance.InstanceOwner.PersonNumber))
            {
                alternativeSubject = $"/person/{instance.InstanceOwner.PersonNumber}";
            }

            CloudEvent cloudEvent = new CloudEvent
            {
                Subject            = $"/party/{instance.InstanceOwner.PartyId}",
                Type               = eventType,
                AlternativeSubject = alternativeSubject,
                Time               = DateTime.UtcNow,
                SpecVersion        = "1.0",
                Source             = new Uri($"https://{instance.Org}.apps.{_generalSettings.HostName}/{instance.AppId}/instances/{instance.Id}")
            };

            string accessToken = _accessTokenGenerator.GenerateAccessToken(_appResources.GetApplication().Org, _appResources.GetApplication().Id.Split("/")[1]);

            string token =
                JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            string serializedCloudEvent = JsonSerializer.Serialize(cloudEvent);

            HttpResponseMessage response = await _client.PostAsync(
                token,
                "app",
                new StringContent(serializedCloudEvent, Encoding.UTF8, "application/json"),
                accessToken);

            if (response.IsSuccessStatusCode)
            {
                string eventId = await response.Content.ReadAsStringAsync();

                return(eventId);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #21
0
        /// <inheritdoc />
        public async Task <DataElement> Update(Instance instance, DataElement dataElement)
        {
            string apiUrl = $"{_platformSettings.ApiStorageEndpoint}instances/{instance.Id}/dataelements/{dataElement.Id}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            StringContent       jsonString = new StringContent(JsonConvert.SerializeObject(dataElement), Encoding.UTF8, "application/json");
            HttpResponseMessage response   = await _client.PutAsync(token, apiUrl, jsonString);

            if (response.IsSuccessStatusCode)
            {
                DataElement result = JsonConvert.DeserializeObject <DataElement>(await response.Content.ReadAsStringAsync());

                return(result);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
        /// <inheritdoc/>
        public async Task <Instance> UpdateSubstatus(int instanceOwnerPartyId, Guid instanceGuid, Substatus substatus)
        {
            string apiUrl = $"instances/{instanceOwnerPartyId}/{instanceGuid}/substatus";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            HttpResponseMessage response = await _client.PutAsync(token, apiUrl, new StringContent(JsonConvert.SerializeObject(substatus), Encoding.UTF8, "application/json"));

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                Instance instance = JsonConvert.DeserializeObject <Instance>(instanceData);
                return(instance);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
        /// <inheritdoc />
        public async Task <Instance> DeleteInstance(int instanceOwnerPartyId, Guid instanceGuid, bool hard)
        {
            string apiUrl = $"instances/{instanceOwnerPartyId}/{instanceGuid}?hard={hard}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            HttpResponseMessage response = await _client.DeleteAsync(token, apiUrl);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                Instance instance = JsonConvert.DeserializeObject <Instance>(instanceData);
                return(instance);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #24
0
        private ActionResult ExceptionResponse(Exception exception, string message)
        {
            _logger.LogError($"{message}: {exception}");

            if (exception is PlatformHttpException)
            {
                PlatformHttpException phe = exception as PlatformHttpException;
                return(StatusCode((int)phe.Response.StatusCode, phe.Message));
            }
            else if (exception is ServiceException)
            {
                ServiceException se = exception as ServiceException;
                return(StatusCode((int)se.StatusCode, se.Message));
            }

            return(StatusCode(500, $"{message}"));
        }
Exemple #25
0
        public async Task <ProcessHistoryList> GetProcessHistory(string instanceGuid, string instanceOwnerPartyId)
        {
            string apiUrl = $"instances/{instanceOwnerPartyId}/{instanceGuid}/process/history";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _appSettings.RuntimeCookieName);

            HttpResponseMessage response = await _client.GetAsync(token, apiUrl);

            if (response.IsSuccessStatusCode)
            {
                string eventData = await response.Content.ReadAsStringAsync();

                ProcessHistoryList processHistoryList = JsonConvert.DeserializeObject <ProcessHistoryList>(eventData);

                return(processHistoryList);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
        /// <inheritdoc/>
        public async Task <Instance> CreateInstance(string org, string app, Instance instanceTemplate)
        {
            string apiUrl = $"instances?appId={org}/{app}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            StringContent       content  = new StringContent(JsonConvert.SerializeObject(instanceTemplate), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await _client.PostAsync(token, apiUrl, content);

            if (response.IsSuccessStatusCode)
            {
                Instance createdInstance = JsonConvert.DeserializeObject <Instance>(await response.Content.ReadAsStringAsync());

                return(createdInstance);
            }

            _logger.LogError($"Unable to create instance {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #27
0
        /// <inheritdoc />
        public async Task <Stream> GetBinaryData(string org, string app, int instanceOwnerId, Guid instanceGuid, Guid dataId)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string apiUrl             = $"instances/{instanceIdentifier}/data/{dataId}";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            HttpResponseMessage response = await _client.GetAsync(token, apiUrl);

            if (response.IsSuccessStatusCode)
            {
                return(await response.Content.ReadAsStreamAsync());
            }
            else if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }

            throw await PlatformHttpException.CreateAsync(response);
        }
Exemple #28
0
 private ActionResult HandlePlatformHttpException(PlatformHttpException e, string defaultMessage)
 {
     if (e.Response.StatusCode == HttpStatusCode.Forbidden)
     {
         return(Forbid());
     }
     else if (e.Response.StatusCode == HttpStatusCode.NotFound)
     {
         return(NotFound());
     }
     else if (e.Response.StatusCode == HttpStatusCode.Conflict)
     {
         return(Conflict());
     }
     else
     {
         return(ExceptionResponse(e, defaultMessage));
     }
 }
Exemple #29
0
 private ActionResult HandlePlatformHttpException(PlatformHttpException e)
 {
     if (e.Response.StatusCode == HttpStatusCode.Unauthorized)
     {
         return(StatusCode(401, e.Message));
     }
     else if (e.Response.StatusCode == HttpStatusCode.Forbidden)
     {
         return(StatusCode(403, e.Message));
     }
     else if (e.Response.StatusCode == HttpStatusCode.NotFound)
     {
         return(StatusCode(404, e.Message));
     }
     else
     {
         return(StatusCode(500, e.Message));
     }
 }
        /// <inheritdoc />
        public async Task <Instance> UpdateInstance(Instance instance)
        {
            string apiUrl = $"instances/{instance.Id}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            StringContent       httpContent = new StringContent(instance.ToString(), Encoding.UTF8, "application/json");
            HttpResponseMessage response    = await _client.PutAsync(token, apiUrl, httpContent);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string instanceData = await response.Content.ReadAsStringAsync();

                Instance updatedInstance = JsonConvert.DeserializeObject <Instance>(instanceData);

                return(updatedInstance);
            }

            _logger.LogError($"Unable to update instance with instance id {instance.Id}");
            throw await PlatformHttpException.CreateAsync(response);
        }