コード例 #1
0
        /// <inheritdoc />
        public async Task <Instance> UpdateInstance(Instance instance)
        {
            string apiUrl = $"instances/{instance.Id}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            StringContent       httpContent = new StringContent(instance.ToString(), Encoding.UTF8, "application/json");
            HttpResponseMessage response    = await _client.PutAsync(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 new PlatformHttpException(response);
        }
コード例 #2
0
        /// <inheritdoc />
        public async Task <UserProfile> GetUserProfile(int userId)
        {
            UserProfile userProfile = null;

            string endpointUrl = $"users/{userId}";
            string token       = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = await _client.GetAsync(endpointUrl);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                userProfile = await response.Content.ReadAsAsync <UserProfile>();
            }
            else
            {
                _logger.LogError($"Getting user profile with userId {userId} failed with statuscode {response.StatusCode}");
            }

            return(userProfile);
        }
コード例 #3
0
        /// <inheritdoc />
        public async Task <Organization> GetOrganization(string OrgNr)
        {
            Organization organization = null;

            string endpointUrl = $"organizations/{OrgNr}";
            string token       = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = await _client.GetAsync(endpointUrl);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                organization = await response.Content.ReadAsAsync <Organization>();
            }
            else
            {
                _logger.LogError($"Getting organisation with orgnr {OrgNr} failed with statuscode {response.StatusCode}");
            }

            return(organization);
        }
コード例 #4
0
        /// <inheritdoc/>
        public async Task <Party> GetParty(int partyId)
        {
            Party party = null;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Party));

            string endpointUrl = $"parties/{partyId}";
            string token       = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);
            HttpResponseMessage response = await _client.GetAsync(endpointUrl);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                party = await response.Content.ReadAsAsync <Party>();
            }
            else
            {
                _logger.LogError($"// Getting party with partyID {partyId} failed with statuscode {response.StatusCode}");
            }

            return(party);
        }
コード例 #5
0
        /// <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, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            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}";
            }

            try
            {
                HttpResponseMessage response = await _client.GetAsync(apiUrl);

                string eventData = await response.Content.ReadAsStringAsync();

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

                return(instanceEvents);
            }
            catch (Exception)
            {
                _logger.LogError($"Unable to retrieve instance event");
                return(null);
            }
        }
コード例 #6
0
        /// <inheritdoc />
        public async Task <bool?> ValidateSelectedParty(int userId, int partyId)
        {
            bool?  result;
            string apiUrl = $"parties/{partyId}/validate?userid={userId}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_authClient, token);

            HttpResponseMessage response = await _authClient.GetAsync(apiUrl);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string responseData = response.Content.ReadAsStringAsync().Result;
                result = JsonConvert.DeserializeObject <bool>(responseData);
            }
            else
            {
                _logger.LogError($"Validating selected party {partyId} for user {userId} failed with statuscode {response.StatusCode}");
                result = null;
            }

            return(result);
        }
コード例 #7
0
        /// <inheritdoc/>
        public async Task <string> SaveInstanceEvent(object dataToSerialize, string org, string app)
        {
            InstanceEvent instanceEvent = (InstanceEvent)dataToSerialize;

            instanceEvent.Created = DateTime.UtcNow;
            string apiUrl = $"instances/{instanceEvent.InstanceId}/events";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);


            HttpResponseMessage response = await _client.PostAsync(apiUrl, new StringContent(instanceEvent.ToString(), Encoding.UTF8, "application/json"));

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

                InstanceEvent result = JsonConvert.DeserializeObject <InstanceEvent>(eventData);
                return(result.Id.ToString());
            }

            throw new PlatformHttpException(response);
        }
コード例 #8
0
        /// <inheritdoc/>
        public async Task <Person> GetPerson(string SSN)
        {
            Person person = null;

            string endpointUrl = $"persons/{SSN}";

            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = await _client.GetAsync(endpointUrl);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                person = await response.Content.ReadAsAsync <Person>();
            }
            else
            {
                _logger.LogError($"Getting person with ssn {SSN} failed with statuscode {response.StatusCode}");
            }

            return(person);
        }
コード例 #9
0
        /// <inheritdoc />
        public async Task <Instance> GetInstance(string app, string org, int instanceOwnerId, Guid instanceGuid)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";

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

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = await _client.GetAsync(apiUrl);

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

                Instance instance = JsonConvert.DeserializeObject <Instance>(instanceData);
                return(instance);
            }
            else
            {
                _logger.LogError($"Unable to fetch instance with instance id {instanceGuid}");
                throw new PlatformHttpException(response);
            }
        }
コード例 #10
0
        /// <inheritdoc />
        public List <Party> GetPartyList(int userId)
        {
            List <Party> partyList = null;
            string       apiUrl    = $"parties?userid={userId}";
            string       token     = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_authClient, token);
            try
            {
                HttpResponseMessage response = _authClient.GetAsync(apiUrl).Result;

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string partyListData = response.Content.ReadAsStringAsync().Result;
                    partyList = JsonConvert.DeserializeObject <List <Party> >(partyListData);
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"Unable to retrieve party list. An error occured {e.Message}");
            }

            return(partyList);
        }
コード例 #11
0
        /// <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);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            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(apiUrl);

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

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

                return(instanceEvents);
            }

            throw new PlatformHttpException(response);
        }
コード例 #12
0
ファイル: DataAppSI.cs プロジェクト: afrog33k/altinn-studio
        /// <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, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            // Waiting for the instance and subsequently locking it.
            SemaphoreSlim instanceLock = _instanceLocks.GetOrAdd(instanceGuid, k => new SemaphoreSlim(1, 1));
            await instanceLock.WaitAsync();

            try
            {
                HttpResponseMessage response = await _client.DeleteAsync(apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    return(true);
                }
                else
                {
                    _logger.LogError($"Deleting form attachment {dataGuid} for instance {instanceGuid} failed with status code {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Deleting form attachment {dataGuid} for instance {instanceGuid} failed. Exception message: {ex.Message}");
            }
            finally
            {
                instanceLock.Release();
            }

            return(false);
        }
コード例 #13
0
ファイル: DataAppSI.cs プロジェクト: maritg/altinn-studio
        /// <inheritdoc />
        public void UpdateData <T>(T dataToSerialize, Guid instanceGuid, Type type, string org, string appName, int instanceOwnerId, Guid dataId)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string apiUrl             = $"instances/{instanceIdentifier}/data/{dataId}";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            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");

                Task <HttpResponseMessage> response = _client.PutAsync(apiUrl, streamContent);
                if (!response.Result.IsSuccessStatusCode)
                {
                    _logger.LogError($"Unable to save form model for instance {instanceGuid}");
                }
            }
        }
コード例 #14
0
        /// <inheritdoc/>
        public async Task <Party> LookupParty(string personOrOrganisationNumber)
        {
            Party party;

            string endpointUrl = "parties/lookupObject";
            string token       = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            StringContent content = new StringContent(JsonConvert.SerializeObject(personOrOrganisationNumber));

            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new System.Uri(endpointUrl, System.UriKind.Relative),
                Method     = HttpMethod.Get,
                Content    = content,
            };

            HttpResponseMessage response = await _client.SendAsync(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                party = await response.Content.ReadAsAsync <Party>();
            }
            else
            {
                string reason = await response.Content.ReadAsStringAsync();

                _logger.LogError($"// Getting party with personOrOrganisationNumber {personOrOrganisationNumber} failed with statuscode {response.StatusCode} - {reason}");

                throw new PlatformClientException($"Failed to lookup party in platform register. {response.StatusCode} - {reason}.");
            }

            return(party);
        }
コード例 #15
0
ファイル: DataAppSI.cs プロジェクト: afrog33k/altinn-studio
        /// <inheritdoc />
        public async Task <DataElement> UpdateBinaryData(string org, string app, int instanceOwnerId, Guid instanceGuid, Guid dataGuid, HttpRequest request)
        {
            string   instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string   apiUrl             = $"{_platformSettings.GetApiStorageEndpoint}instances/{instanceIdentifier}/data/{dataGuid}";
            string   token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);
            Instance instance;

            // Waiting for the instance and subsequently locking it.
            SemaphoreSlim instanceLock = _instanceLocks.GetOrAdd(instanceGuid, k => new SemaphoreSlim(1, 1));
            await instanceLock.WaitAsync();

            try
            {
                // using a non-generic client in order to support unknown content type
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeHeaderValue.Parse(request.ContentType).ToString()));
                    JwtTokenUtil.AddTokenToRequestHeader(client, token);

                    HttpResponseMessage response;

                    if (request.ContentType.StartsWith("multipart"))
                    {
                        StreamContent content = new StreamContent(request.Body);
                        content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.ContentType);

                        response = await client.PutAsync(apiUrl, content);

                        content.Dispose();
                    }
                    else
                    {
                        using (Stream input = request.Body)
                            using (MultipartFormDataContent attachmentData = new MultipartFormDataContent())
                            {
                                HttpContent fileStreamContent = new StreamContent(input);

                                fileStreamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(request.ContentType);
                                attachmentData.Add(fileStreamContent);

                                response = await client.PutAsync(apiUrl, attachmentData);
                            }
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        string instancedata = response.Content.ReadAsStringAsync().Result;
                        instance = JsonConvert.DeserializeObject <Instance>(instancedata);

                        return(instance.Data.Find(d => d.Id.Equals(dataGuid.ToString())));
                    }
                    else
                    {
                        _logger.LogError($"Updating attachment {dataGuid} for instance {instanceGuid} failed with status code {response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Updating attachment {dataGuid} for instance {instanceGuid} failed. Exception message: {ex.Message}");
            }
            finally
            {
                instanceLock.Release();
            }

            return(null);
        }