Beispiel #1
0
        /// <inheritdoc />
        public async Task <TextResource> GetText(string org, string app, string language)
        {
            TextResource textResource = null;
            string       cacheKey     = $"{org}-{app}-{language.ToLower()}";

            if (!_memoryCache.TryGetValue(cacheKey, out textResource))
            {
                // Key not in cache, so get text from Platform Storage
                string url   = $"applications/{org}/{app}/texts/{language}";
                string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

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

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    textResource = await response.Content.ReadAsAsync <TextResource>();

                    _memoryCache.Set(cacheKey, textResource, cacheEntryOptions);
                }
                else
                {
                    _logger.LogError($"Getting text resource for {org}/{app} with language code: {language} failed with statuscode {response.StatusCode}");
                }
            }

            return(textResource);
        }
Beispiel #2
0
        public async Task <DataElement> InsertFormData <T>(Instance instance, string dataType, T dataToSerialize, Type type)
        {
            string apiUrl = $"instances/{instance.Id}/data?dataType={dataType ?? FORM_ID}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);
            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");
            Task <HttpResponseMessage> response = _client.PostAsync(apiUrl, streamContent);

            if (!response.Result.IsSuccessStatusCode)
            {
                _logger.Log(LogLevel.Error, "unable to save form data for instance{0} due to response {1}", instance.Id, response.Result.StatusCode);
                return(null);
            }

            string instanceData = await response.Result.Content.ReadAsStringAsync();

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

            return(dataElement);
        }
Beispiel #3
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);
        }
Beispiel #4
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);
        }
Beispiel #5
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);
            }
        }
Beispiel #6
0
        /// <inheritdoc />
        /// TODO - fix logic, what are you using this for? It will only get instances for a instance owners the way storage is implemented now
        public async Task <List <Instance> > GetInstances(string app, string org, int instanceOwnerId)
        {
            List <Instance>            instances  = null;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Instance));
            string appId  = ApplicationHelper.GetFormattedApplicationId(org, app);
            string apiUrl = $"instances?instanceOwnerId={instanceOwnerId}&appId={appId}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = await _client.GetAsync(apiUrl);

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

                instances = JsonConvert.DeserializeObject <List <Instance> >(instanceData);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return(instances);
            }
            else
            {
                _logger.LogError("Unable to fetch instances");
                throw new PlatformClientException(response);
            }

            return(instances);
        }
Beispiel #7
0
        /// <inheritdoc />
        public async Task <Instance> UpdateInstance(object dataToSerialize, string app, string org, int instanceOwnerId, Guid instanceId)
        {
            string   instanceIdentifier = $"{instanceOwnerId}/{instanceId}";
            Instance instance           = new Instance();
            string   apiUrl             = $"instances/{instanceIdentifier}";
            string   token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            string              jsonData    = JsonConvert.SerializeObject(dataToSerialize);
            StringContent       httpContent = new StringContent(jsonData, 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 = JsonConvert.DeserializeObject <Instance>(instanceData);
            }
            else
            {
                _logger.LogError($"Unable to update instance with instance id {instanceId}");
                throw new PlatformClientException(response);
            }

            return(instance);
        }
Beispiel #8
0
        /// <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);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = await _client.GetAsync(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 new PlatformHttpException(response);
            }
        }
Beispiel #9
0
        /// <inheritdoc />
        public async Task <Instance> GetInstance(string app, string org, int instanceOwnerId, Guid instanceId)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceId}";

            Instance instance = new Instance();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Instance));

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

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = await _client.GetAsync(apiUrl);

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

                instance = JsonConvert.DeserializeObject <Instance>(instanceData);
            }
            else
            {
                _logger.LogError($"Unable to fetch instance with instance id {instanceId}");
                throw new PlatformClientException(response);
            }

            return(instance);
        }
Beispiel #10
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);
        }
Beispiel #11
0
        /// <inheritdoc/>
        public async Task <string> SaveInstanceEvent(object dataToSerialize, string org, string appName)
        {
            InstanceEvent instanceEvent = (InstanceEvent)dataToSerialize;

            instanceEvent.CreatedDateTime = DateTime.UtcNow;
            string apiUrl = $"instances/{instanceEvent.InstanceId}/events";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

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

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

                InstanceEvent result = JsonConvert.DeserializeObject <InstanceEvent>(eventData);
                return(result.Id.ToString());
            }
            catch
            {
                _logger.LogError($"Unable to store instance event");
                return(null);
            }
        }
Beispiel #12
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);
        }
        /// <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);
        }
Beispiel #14
0
        /// <inheritdoc />
        public async Task <Instance> 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, _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}");
                }

                string instanceData = await response.Result.Content.ReadAsStringAsync();

                Instance instance = JsonConvert.DeserializeObject <Instance>(instanceData);
                return(instance);
            }
        }
Beispiel #15
0
        /// <inheritdoc/>
        public ServiceState GetCurrentState(Guid instanceId, string org, string appName, int instanceOwnerId)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceId}";
            Instance instance;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Instance));
            string apiUrl = $"instances/{instanceIdentifier}";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);
            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            Task<HttpResponseMessage> response = _client.GetAsync(apiUrl);
            if (response.Result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string instanceData = response.Result.Content.ReadAsStringAsync().Result;
                instance = JsonConvert.DeserializeObject<Instance>(instanceData);
            }
            else
            {
                throw new Exception("Unable to fetch workflow state");
            }

            Enum.TryParse<WorkflowStep>(instance.Process.CurrentTask, out WorkflowStep currentWorkflowState);

            return new ServiceState
            {
                State = currentWorkflowState
            };
        }
Beispiel #16
0
        /// <inheritdoc />
        public async Task <List <AttachmentList> > GetBinaryDataList(string org, string app, int instanceOwnerId, Guid instanceGuid)
        {
            string instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string apiUrl             = $"instances/{instanceIdentifier}/data";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            List <DataElement>    dataList       = null;
            List <AttachmentList> attachmentList = new List <AttachmentList>();

            HttpResponseMessage response = await _client.GetAsync(apiUrl);

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

                dataList = JsonConvert.DeserializeObject <List <DataElement> >(instanceData);

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

            return(attachmentList);
        }
Beispiel #17
0
        /// <inheritdoc />
        public 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, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            Task <HttpResponseMessage> response = _client.GetAsync(apiUrl);

            if (response.Result.IsSuccessStatusCode)
            {
                XmlSerializer serializer = new XmlSerializer(type);
                try
                {
                    using (Stream stream = response.Result.Content.ReadAsStreamAsync().Result)
                    {
                        return(serializer.Deserialize(stream));
                    }
                }
                catch
                {
                    return(Activator.CreateInstance(type));
                }
            }
            else
            {
                return(Activator.CreateInstance(type));
            }
        }
Beispiel #18
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);
        }
Beispiel #19
0
        /// <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);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

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

            if (response.StatusCode == System.Net.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 new PlatformHttpException(response);
            }
        }
Beispiel #20
0
        /// <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.ApiStorageEndpoint}instances/{instanceIdentifier}/data/{dataGuid}";
            string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

            StreamContent content = CreateContentStream(request);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

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

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

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

                return(dataElement);
            }

            _logger.LogError($"Updating attachment {dataGuid} for instance {instanceGuid} failed with status code {response.StatusCode}");

            throw new PlatformHttpException(response);
        }
Beispiel #21
0
        /// <inheritdoc />
        public async Task <Guid> SaveFormAttachment(string org, string appName, int instanceOwnerId, Guid instanceGuid, string attachmentType, string attachmentName, HttpRequest attachment)
        {
            string   instanceIdentifier = $"{instanceOwnerId}/{instanceGuid}";
            string   apiUrl             = $"{_platformSettings.GetApiStorageEndpoint}instances/{instanceIdentifier}/data?elementType={attachmentType}&attachmentName={attachmentName}";
            string   token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);
            Instance instance;

            FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
            string contentType;

            provider.TryGetContentType(attachmentName, out contentType);

            // 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(contentType));
                JwtTokenUtil.AddTokenToRequestHeader(client, token);

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

                    HttpResponseMessage response = client.PostAsync(apiUrl, content).Result;

                    response.EnsureSuccessStatusCode();

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

                    instance = JsonConvert.DeserializeObject <Instance>(instancedata);
                    return(Guid.Parse(instance.Data.Find(m => m.FileName.Equals(attachmentName)).Id));
                }
                else
                {
                    using (Stream input = attachment.Body)
                    {
                        HttpContent fileStreamContent = new StreamContent(input);

                        using (MultipartFormDataContent formData = new MultipartFormDataContent())
                        {
                            fileStreamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);

                            formData.Add(fileStreamContent, attachmentType, attachmentName);
                            HttpResponseMessage response = client.PostAsync(apiUrl, formData).Result;

                            response.EnsureSuccessStatusCode();

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

                            instance = JsonConvert.DeserializeObject <Instance>(instancedata);
                            return(Guid.Parse(instance.Data.Find(m => m.FileName.Equals(attachmentName)).Id));
                        }
                    }
                }
            }
        }
Beispiel #22
0
        /// <inheritdoc />
        public void DeleteFormAttachment(string org, string appName, int instanceOwnerId, Guid instanceGuid, string attachmentType, string attachmentId)
        {
            string instanceIdentifier            = $"{instanceOwnerId}/{instanceGuid}";
            List <AttachmentList> attachmentList = new List <AttachmentList>();
            string apiUrl = $"instances/{instanceIdentifier}/data/{attachmentId}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            Task <HttpResponseMessage> response = _client.DeleteAsync(apiUrl);

            response.Result.EnsureSuccessStatusCode();
        }
Beispiel #23
0
        /// <inheritdoc />
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid     instanceId;
            Instance instance        = null;
            string   org             = startServiceModel.Org;
            string   appId           = ApplicationHelper.GetFormattedApplicationId(org, startServiceModel.Service);
            string   appName         = startServiceModel.Service;
            int      instanceOwnerId = startServiceModel.PartyId;

            string apiUrl = $"instances/?appId={appId}&instanceOwnerId={instanceOwnerId}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

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

                Instance createdInstance = await response.Content.ReadAsAsync <Instance>();

                instanceId = Guid.Parse(createdInstance.Id.Split("/")[1]);
            }
            catch
            {
                return(instance);
            }

            // Save instantiated form model
            instance = await _data.InsertData(
                serviceModel,
                instanceId,
                serviceImplementation.GetServiceModelType(),
                org,
                appName,
                instanceOwnerId);

            ServiceState currentState = _workflow.GetInitialServiceState(org, appName);

            // set initial workflow state
            instance.Process = new Storage.Interface.Models.ProcessState()
            {
                CurrentTask = currentState.State.ToString(),
                IsComplete  = false,
            };

            instance = await UpdateInstance(instance, appName, org, instanceOwnerId, instanceId);

            return(instance);
        }
        /// <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);
        }
Beispiel #25
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);
        }
Beispiel #26
0
        /// <inheritdoc/>
        public async Task <Party> GetParty(int partyId)
        {
            string token = JwtTokenUtil.GetTokenFromContext(_contextaccessor.HttpContext, "AltinnStudioRuntime");
            string url   = $"parties/{partyId}";

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

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

                return(party);
            }

            throw new PlatformHttpException(response);
        }
Beispiel #27
0
        /// <inheritdoc/>
        public async Task <UserProfile> GetUser(int userId)
        {
            string token = JwtTokenUtil.GetTokenFromContext(_contextaccessor.HttpContext, "AltinnStudioRuntime");
            string url   = $"users/{userId}";

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

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                UserProfile profile = await response.Content.ReadAsAsync <UserProfile>();

                return(profile);
            }

            throw new PlatformHttpException(response);
        }
Beispiel #28
0
        /// <inheritdoc />
        public 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, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            HttpResponseMessage response = _client.GetAsync(apiUrl).Result;

            if (response.IsSuccessStatusCode)
            {
                return(response.Content.ReadAsStreamAsync());
            }

            return(null);
        }
        /// <inheritdoc />
        public async Task <string> RefreshToken()
        {
            string endpointUrl           = $"refresh";
            string token                 = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, Constants.General.RuntimeCookieName);
            HttpResponseMessage response = await _client.GetAsync(token, endpointUrl);

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

                refreshedToken = refreshedToken.Replace('"', ' ').Trim();
                return(refreshedToken);
            }

            _logger.LogError($"Refreshing JwtToken failed with status code {response.StatusCode}");
            return(string.Empty);
        }
Beispiel #30
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);
        }