public void SetContext(RequestContext requestContext, ServiceContext serviceContext, StartServiceModel startServiceModel, ModelStateDictionary modelState)
 {
     this._requestContext    = requestContext;
     this._modelState        = modelState;
     this._startServiceModel = startServiceModel;
     this._serviceContext    = serviceContext;
 }
Example #2
0
        /// <inheritdoc/>
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid   instanceGuid    = Guid.NewGuid();
            string appName         = startServiceModel.Service;
            string org             = startServiceModel.Org;
            int    instanceOwnerId = startServiceModel.PartyId;
            int    userId          = startServiceModel.UserId;

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

            Instance instance = new Instance
            {
                Id = $"{instanceOwnerId}/{instanceGuid}",
                InstanceOwnerId = instanceOwnerId.ToString(),
                AppId           = $"{org}/{appName}",
                Org             = org,
                CreatedBy       = userId.ToString(),
                CreatedDateTime = DateTime.UtcNow,
                Process         = new Storage.Interface.Models.ProcessState()
                {
                    CurrentTask = currentTask.State.ToString(),
                    IsComplete  = false,
                },
                InstanceState = new Storage.Interface.Models.InstanceState()
                {
                    IsArchived            = false,
                    IsDeleted             = false,
                    IsMarkedForHardDelete = false,
                },
                LastChangedDateTime = DateTime.UtcNow,
                LastChangedBy       = userId.ToString(),
            };

            string developer         = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext);
            string testDataForParty  = $"{_settings.GetTestdataForPartyPath(org, appName, developer)}{instanceOwnerId}";
            string folderForInstance = Path.Combine(testDataForParty, instanceGuid.ToString());

            Directory.CreateDirectory(folderForInstance);
            string instanceFilePath = $"{testDataForParty}/{instanceGuid}/{instanceGuid}.json";

            File.WriteAllText(instanceFilePath, JsonConvert.SerializeObject(instance).ToString(), Encoding.UTF8);

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

            return(instance);
        }
Example #3
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);
        }
        public async Task <IActionResult> Index(string org, string service, int reporteeId)
        {
            if (reporteeId == 0)
            {
                return(LocalRedirect($"/designer/{org}/{service}/ManualTesting/Users/"));
            }

            CheckAndUpdateWorkflowFile(org, service);
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty);

            requestContext.UserContext = await _userHelper.CreateUserContextBasedOnReportee(HttpContext, reporteeId);

            requestContext.Reportee = requestContext.UserContext.Reportee;

            StartServiceModel startServiceModel = new StartServiceModel
            {
                ServiceID    = org + "_" + service,
                ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId)
                               .Select(x => new SelectListItem {
                    Text = x.ReporteeNumber + " " + x.ReporteeName, Value = x.PartyID.ToString()
                })
                               .ToList(),
                PrefillList = _testdata.GetServicePrefill(requestContext.Reportee.PartyId, org, service)
                              .Select(x => new SelectListItem {
                    Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey
                })
                              .ToList(),
                ReporteeID = requestContext.Reportee.PartyId,
                Org        = org,
                Service    = service,
            };

            if (reporteeId != 0 && reporteeId != startServiceModel.ReporteeID && startServiceModel.ReporteeList.Any(r => r.Value.Equals(reporteeId.ToString())))
            {
                startServiceModel.ReporteeID = reporteeId;
                requestContext.Reportee      = await _register.GetParty(startServiceModel.ReporteeID);

                requestContext.UserContext.ReporteeId = reporteeId;
                requestContext.UserContext.Reportee   = requestContext.Reportee;
                HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString());
            }

            List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Reportee.PartyId, org, service);

            ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList();

            return(View(startServiceModel));
        }
Example #5
0
        /// <inheritdoc />
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid     instanceId;
            Instance instance           = null;
            string   applicationOwnerId = startServiceModel.Org;
            string   applicationId      = ApplicationHelper.GetFormattedApplicationId(applicationOwnerId, startServiceModel.Service);
            int      instanceOwnerId    = startServiceModel.ReporteeID;

            using (HttpClient client = new HttpClient())
            {
                string apiUrl = $"{_platformSettings.GetApiStorageEndpoint}instances/?applicationId={applicationId}&instanceOwnerId={instanceOwnerId}";
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    HttpResponseMessage response = await client.PostAsync(apiUrl, null);

                    string id = await response.Content.ReadAsAsync <string>();

                    instanceId = Guid.Parse(id);
                }
                catch
                {
                    return(instance);
                }
            }

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

            ServiceState currentState = _workflow.GetInitialServiceState(applicationOwnerId, applicationId);

            // set initial workflow state
            instance.CurrentWorkflowStep = currentState.State.ToString();

            instance = await UpdateInstance(instance, applicationId, applicationOwnerId, instanceOwnerId, instanceId);

            return(instance);
        }
Example #6
0
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid     instanceId;
            Instance instance        = null;
            string   org             = startServiceModel.Org;
            string   app             = startServiceModel.Service;
            int      instanceOwnerId = startServiceModel.PartyId;

            Instance instanceTemplate = new Instance()
            {
                InstanceOwnerId = instanceOwnerId.ToString(),
                Process         = new ProcessState()
                {
                    Started     = DateTime.UtcNow,
                    CurrentTask = new ProcessElementInfo
                    {
                        Started = DateTime.UtcNow,

                        ElementId = _workflow.GetInitialServiceState(org, app).State.ToString(),
                    }
                },
            };

            Instance createdInstance = await CreateInstance(org, app, instanceTemplate);

            if (createdInstance == null)
            {
                return(null);
            }

            instanceId = Guid.Parse(createdInstance.Id.Split("/")[1]);

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

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

            return(instance);
        }
        public IActionResult StartService(string org, string service)
        {
            UserContext userContext       = _userHelper.GetUserContext(HttpContext);
            var         startServiceModel = new StartServiceModel
            {
                ReporteeList = _authorization
                               .GetReporteeList(userContext.UserId)
                               .Select(x => new SelectListItem
                {
                    Text  = x.ReporteeNumber + " " + x.ReporteeName,
                    Value = x.PartyID.ToString(),
                })
                               .ToList(),
                ServiceID = org + "_" + service,
            };

            return(View(startServiceModel));
        }
        public async Task <IActionResult> StartService(string org, string service)
        {
            UserContext userContext = await _userHelper.GetUserContext(HttpContext);

            var startServiceModel = new StartServiceModel
            {
                PartyList = _authorization
                            .GetPartyList(userContext.UserId)
                            .Select(x => new SelectListItem
                {
                    Text  = (x.PartyTypeName == PartyType.Person) ? x.SSN + " " + x.Name : x.OrgNumber + " " + x.Name,
                    Value = x.PartyId.ToString(),
                })
                            .ToList(),
                ServiceID = org + "_" + service,
            };

            return(View(startServiceModel));
        }
        public IActionResult Index(string org, string service, int reporteeId)
        {
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, 0);

            requestContext.UserContext = _userHelper.GetUserContext(HttpContext);
            requestContext.Reportee    = requestContext.UserContext.Reportee;

            var startServiceModel = new StartServiceModel
            {
                ServiceID    = org + "_" + service,
                ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId)
                               .Select(x => new SelectListItem {
                    Text = x.ReporteeNumber + " " + x.ReporteeName, Value = x.PartyID.ToString()
                })
                               .ToList(),
                PrefillList = _testdata.GetServicePrefill(requestContext.Reportee.PartyId, org, service)
                              .Select(x => new SelectListItem {
                    Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey
                })
                              .ToList(),
                ReporteeID = requestContext.Reportee.PartyId
            };

            if (reporteeId != 0 && reporteeId != startServiceModel.ReporteeID && startServiceModel.ReporteeList.Any(r => r.Value.Equals(reporteeId.ToString())))
            {
                startServiceModel.ReporteeID          = reporteeId;
                requestContext.Reportee               = _register.GetParty(startServiceModel.ReporteeID);
                requestContext.UserContext.ReporteeId = reporteeId;
                requestContext.UserContext.Reportee   = requestContext.Reportee;
                HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString());
            }

            List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Reportee.PartyId, org, service);

            ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList();

            return(View(startServiceModel));
        }
Example #10
0
        /// <summary>
        /// This method creates new instance in database
        /// </summary>
        public async Task <Guid> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid   instanceId;
            string applicationId      = startServiceModel.Service;
            string applicationOwnerId = startServiceModel.Org;
            int    instanceOwnerId    = startServiceModel.ReporteeID;

            using (HttpClient client = new HttpClient())
            {
                string apiUrl = $"{_platformStorageSettings.ApiUrl}/instances/?applicationId={applicationId}&instanceOwnerId={instanceOwnerId}";
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    HttpResponseMessage response = await client.PostAsync(apiUrl, null);

                    string id = await response.Content.ReadAsAsync <string>();

                    instanceId = Guid.Parse(id);
                }
                catch
                {
                    return(Guid.Parse(string.Empty));
                }
            }

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

            return(instanceId);
        }
        public async Task <IActionResult> Index(string org, string service, int reporteeId)
        {
            var    developer = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext);
            string apiUrl    = _settings.GetRuntimeAPIPath("ZipAndSendRepo", org, service, developer);

            using (HttpClient client = AuthenticationHelper.GetDesignerHttpClient(_httpContextAccessor.HttpContext, _testdataRepositorySettings.GetDesignerHost()))
            {
                client.BaseAddress = new Uri(apiUrl);
                HttpResponseMessage response = await client.GetAsync(apiUrl);

                string zipPath     = $"{_settings.GetServicePath(org, service, developer)}{service}.zip";
                string extractPath = _settings.GetServicePath(org, service, developer);
                if (!Directory.Exists(extractPath))
                {
                    Directory.CreateDirectory(extractPath);
                }
                else
                {
                    Directory.Delete(extractPath, true);
                    Directory.CreateDirectory(extractPath);
                }

                using (Stream s = response.Content.ReadAsStreamAsync().Result)
                {
                    using (var w = System.IO.File.OpenWrite(zipPath))
                    {
                        s.CopyTo(w);
                    }
                }

                ZipFile.ExtractToDirectory(zipPath, extractPath);
            }

            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, 0);

            requestContext.UserContext = _userHelper.GetUserContext(HttpContext);
            requestContext.Reportee    = requestContext.UserContext.Reportee;

            var startServiceModel = new StartServiceModel
            {
                ServiceID    = org + "_" + service,
                ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId)
                               .Select(x => new SelectListItem {
                    Text = x.ReporteeNumber + " " + x.ReporteeName, Value = x.PartyID.ToString()
                })
                               .ToList(),
                PrefillList = _testdata.GetServicePrefill(requestContext.Reportee.PartyId, org, service)
                              .Select(x => new SelectListItem {
                    Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey
                })
                              .ToList(),
                ReporteeID = requestContext.Reportee.PartyId,
                Org        = org,
                Service    = service,
            };

            if (reporteeId != 0 && reporteeId != startServiceModel.ReporteeID && startServiceModel.ReporteeList.Any(r => r.Value.Equals(reporteeId.ToString())))
            {
                startServiceModel.ReporteeID          = reporteeId;
                requestContext.Reportee               = _register.GetParty(startServiceModel.ReporteeID);
                requestContext.UserContext.ReporteeId = reporteeId;
                requestContext.UserContext.Reportee   = requestContext.Reportee;
                HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString());
            }

            List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Reportee.PartyId, org, service, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext));

            ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList();

            return(View(startServiceModel));
        }
        public async Task <IActionResult> StartService(StartServiceModel startServiceModel)
        {
            // Dependency Injection: Getting the Service Specific Implementation based on the service parameter data store
            // Will compile code and load DLL in to memory for AltinnCore
            bool startService = true;
            IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(startServiceModel.Org, startServiceModel.Service, startService);

            // Get the service context containing metadata about the service
            ServiceContext serviceContext = _execution.GetServiceContext(startServiceModel.Org, startServiceModel.Service, startService);

            // Create and populate the RequestContext object and make it available for the service implementation so
            // service developer can implement logic based on information about the request and the user performing
            // the request
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty);

            requestContext.UserContext = await _userHelper.GetUserContext(HttpContext);

            // Populate the reportee information
            requestContext.UserContext.Party = await _register.GetParty(startServiceModel.PartyId);

            requestContext.Party = requestContext.UserContext.Party;

            // Create platform service and assign to service implementation making it possible for the service implementation
            // to use plattform services. Also make it available in ViewBag so it can be used from Views
            serviceImplementation.SetPlatformServices(_platformSI);

            // Assign the different context information to the service implementation making it possible for
            // the service developer to take use of this information
            serviceImplementation.SetContext(requestContext, serviceContext, null, ModelState);

            object serviceModel = null;

            if (!string.IsNullOrEmpty(startServiceModel.PrefillKey))
            {
                _form.GetPrefill(
                    startServiceModel.Org,
                    startServiceModel.Service,
                    serviceImplementation.GetServiceModelType(),
                    startServiceModel.PartyId,
                    startServiceModel.PrefillKey);
            }

            if (serviceModel == null)
            {
                // If the service model was not loaded from prefill.
                serviceModel = serviceImplementation.CreateNewServiceModel();
            }

            // Assign service model to the implementation
            serviceImplementation.SetServiceModel(serviceModel);

            // Run Instansiation event
            await serviceImplementation.RunServiceEvent(ServiceEventType.Instantiation);

            // Run validate Instansiation event where
            await serviceImplementation.RunServiceEvent(ServiceEventType.ValidateInstantiation);

            // If ValidateInstansiation event has not added any errors the new form is saved and user is redirercted to the correct
            if (ModelState.IsValid)
            {
                if (serviceContext.WorkFlow.Any() && serviceContext.WorkFlow[0].StepType.Equals(StepType.Lookup))
                {
                    return(RedirectToAction("Lookup", new { org = startServiceModel.Org, service = startServiceModel.Service }));
                }

                int instanceOwnerId = requestContext.UserContext.PartyId;

                // Create a new instance document
                Instance instance = await _instance.InstantiateInstance(startServiceModel, serviceModel, serviceImplementation);

                // Create and store the instance created event
                InstanceEvent instanceEvent = new InstanceEvent
                {
                    AuthenticationLevel = requestContext.UserContext.AuthenticationLevel,
                    EventType           = InstanceEventType.Created.ToString(),
                    InstanceId          = instance.Id,
                    InstanceOwnerId     = instanceOwnerId.ToString(),
                    UserId       = requestContext.UserContext.UserId,
                    WorkflowStep = instance.Process.CurrentTask
                };

                await _event.SaveInstanceEvent(instanceEvent, startServiceModel.Org, startServiceModel.Service);

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

                string redirectUrl = _workflowSI.GetUrlForCurrentState(Guid.Parse(instance.Id), startServiceModel.Org, startServiceModel.Service, currentStep);
                return(Redirect(redirectUrl));
            }

            startServiceModel.PartyList = _authorization.GetPartyList(requestContext.UserContext.UserId)
                                          .Select(x => new SelectListItem
            {
                Text  = (x.PartyTypeName == PartyType.Person) ? x.SSN + " " + x.Name : x.OrgNumber + " " + x.Name,
                Value = x.PartyId.ToString(),
            }).ToList();

            HttpContext.Response.Cookies.Append(_generalSettings.GetAltinnPartyCookieName, startServiceModel.PartyId.ToString());
            return(View(startServiceModel));
        }
        public async Task <IActionResult> StartService(StartServiceModel startServiceModel)
        {
            // Dependency Injection: Getting the Service Specific Implementation based on the service parameter data store
            // Will compile code and load DLL in to memory for AltinnCore
            bool startService = true;
            IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(startServiceModel.Org, startServiceModel.Service, startService);

            // Get the service context containing metadata about the service
            ServiceContext serviceContext = _execution.GetServiceContext(startServiceModel.Org, startServiceModel.Service, startService);

            // Create and populate the RequestContext object and make it available for the service implementation so
            // service developer can implement logic based on information about the request and the user performing
            // the request
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, 0);

            requestContext.UserContext = _userHelper.GetUserContext(HttpContext);

            // Populate the reportee information
            requestContext.UserContext.Reportee = _register.GetParty(startServiceModel.ReporteeID);
            requestContext.Reportee             = requestContext.UserContext.Reportee;

            // Create platform service and assign to service implementation making it possible for the service implementation
            // to use plattform services. Also make it available in ViewBag so it can be used from Views
            PlatformServices platformServices = new PlatformServices(_authorization, _repository, _execution, startServiceModel.Org, startServiceModel.Service);

            serviceImplementation.SetPlatformServices(platformServices);
            ViewBag.PlatformServices = platformServices;

            // Assign the different context information to the service implementation making it possible for
            // the service developer to take use of this information
            serviceImplementation.SetContext(requestContext, ViewBag, serviceContext, null, ModelState);

            object serviceModel = null;

            if (!string.IsNullOrEmpty(startServiceModel.PrefillKey))
            {
                _form.GetPrefill(
                    startServiceModel.Org,
                    startServiceModel.Service,
                    serviceImplementation.GetServiceModelType(),
                    startServiceModel.ReporteeID,
                    startServiceModel.PrefillKey);
            }

            if (serviceModel == null)
            {
                // If the service model was not loaded from prefill.
                serviceModel = serviceImplementation.CreateNewServiceModel();
            }

            // Assign service model to the implementation
            serviceImplementation.SetServiceModel(serviceModel);

            // Run Instansiation event
            await serviceImplementation.RunServiceEvent(ServiceEventType.Instantiation);

            // Run validate Instansiation event where
            await serviceImplementation.RunServiceEvent(ServiceEventType.ValidateInstantiation);

            // If ValidateInstansiation event has not added any errors the new form is saved and user is redirercted to the correct
            if (ModelState.IsValid)
            {
                if (serviceContext.WorkFlow.Any() && serviceContext.WorkFlow[0].StepType.Equals(StepType.Lookup))
                {
                    return(RedirectToAction("Lookup", new { org = startServiceModel.Org, service = startServiceModel.Service }));
                }

                // Create a new instance Id
                int formID = _execution.GetNewServiceInstanceID(startServiceModel.Org, startServiceModel.Service);

                _form.SaveFormModel(
                    serviceModel,
                    formID,
                    serviceImplementation.GetServiceModelType(),
                    startServiceModel.Org,
                    startServiceModel.Service,
                    requestContext.UserContext.ReporteeId);

                ServiceState currentState = _workflowSI.InitializeService(formID, startServiceModel.Org, startServiceModel.Service, requestContext.UserContext.ReporteeId);
                string       redirectUrl  = _workflowSI.GetUrlForCurrentState(formID, startServiceModel.Org, startServiceModel.Service, currentState.State);
                return(Redirect(redirectUrl));
            }

            startServiceModel.ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId)
                                             .Select(x => new SelectListItem
            {
                Text  = x.ReporteeNumber + " " + x.ReporteeName,
                Value = x.PartyID.ToString(),
            }).ToList();

            HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString());
            return(View(startServiceModel));
        }
 public void HandleValidateInstansiationEvent(StartServiceModel startServiceModel, ModelStateDictionary modelState)
 {
 }
        public async Task <IActionResult> Index(string org, string app, int partyId, int userId)
        {
            if (userId == 0 || partyId == 0)
            {
                return(LocalRedirect($"/designer/{org}/{app}/ManualTesting/Users/"));
            }

            bool?isValidSelection = await _authorization.ValidateSelectedParty(userId, partyId);

            if (isValidSelection != true)
            {
                return(LocalRedirect($"/designer/{org}/{app}/ManualTesting/Users/"));
            }

            Response.Cookies.Append(
                _generalSettings.GetAltinnPartyCookieName,
                partyId.ToString(),
                new CookieOptions
            {
                Domain = _generalSettings.HostName
            });

            CheckAndUpdateWorkflowFile(org, app);
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty);

            requestContext.UserContext = await _userHelper.CreateUserContextBasedOnUserAndParty(HttpContext, userId, partyId);

            requestContext.Party = requestContext.UserContext.Party;

            StartServiceModel startServiceModel = new StartServiceModel
            {
                ServiceID = org + "_" + app,
                PartyList = _authorization.GetPartyList(requestContext.UserContext.UserId)
                            .Select(x => new SelectListItem
                {
                    Text  = (x.PartyTypeName == PartyType.Person) ? x.SSN + " " + x.Name : x.OrgNumber + " " + x.Name,
                    Value = x.PartyId.ToString()
                })
                            .ToList(),
                PrefillList = _testdata.GetServicePrefill(requestContext.Party.PartyId, org, app)
                              .Select(x => new SelectListItem {
                    Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey
                })
                              .ToList(),
                PartyId = requestContext.Party.PartyId,
                Org     = org,
                Service = app,
            };

            if (partyId != 0 && partyId != startServiceModel.PartyId && startServiceModel.PartyList.Any(r => r.Value.Equals(partyId.ToString())))
            {
                startServiceModel.PartyId = partyId;
                requestContext.Party      = await _register.GetParty(startServiceModel.PartyId);

                requestContext.UserContext.PartyId = partyId;
                requestContext.UserContext.Party   = requestContext.Party;
            }

            List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Party.PartyId, org, app);

            ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList();

            return(View(startServiceModel));
        }
        /// <summary>
        /// Generates a new service instanceID for a service.
        /// </summary>
        /// <returns>A new instanceId.</returns>
        public async Task <Guid> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid   instanceId         = Guid.NewGuid();
            string applicationId      = startServiceModel.Service;
            string applicationOwnerId = startServiceModel.Org;
            int    instanceOwnerId    = startServiceModel.ReporteeID;

            Instance instance = new Instance
            {
                Id = instanceId.ToString(),
                InstanceOwnerId = instanceOwnerId.ToString(),
                ApplicationId   = applicationId,
                CreatedBy       = instanceOwnerId,
                CreatedDateTime = DateTime.UtcNow,
            };

            string developer = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext);
            string apiUrl    = $"{_settings.GetRuntimeAPIPath(SaveInstanceMethod, applicationOwnerId, applicationId, developer, instanceOwnerId)}&instanceId={instanceId}";

            using (HttpClient client = AuthenticationHelper.GetDesignerHttpClient(_httpContextAccessor.HttpContext, _testdataRepositorySettings.GetDesignerHost()))
            {
                client.BaseAddress = new Uri(apiUrl);

                using (MemoryStream stream = new MemoryStream())
                {
                    var          jsonData = JsonConvert.SerializeObject(instance);
                    StreamWriter writer   = new StreamWriter(stream);
                    writer.Write(jsonData);
                    writer.Flush();
                    stream.Position = 0;

                    Task <HttpResponseMessage> response = client.PostAsync(apiUrl, new StreamContent(stream));
                    if (!response.Result.IsSuccessStatusCode)
                    {
                        throw new Exception("Unable to save instance");
                    }
                }
            }

            // Save instantiated form model
            Guid dataId = await _form.SaveFormModel(
                serviceModel,
                instanceId,
                serviceImplementation.GetServiceModelType(),
                applicationOwnerId,
                applicationId,
                instanceOwnerId,
                Guid.Empty);

            // Update instance with dataId
            instance = await GetInstance(applicationId, applicationOwnerId, instanceOwnerId, instanceId);

            Data data = new Data
            {
                Id          = dataId.ToString(),
                ContentType = "application/Xml",
                StorageUrl  = "data/boatdata/",
                CreatedBy   = instanceOwnerId.ToString(),
            };
            Dictionary <string, Data> formData = new Dictionary <string, Data>();

            formData.Add(dataId.ToString(), data);
            instance.Data = new Dictionary <string, Dictionary <string, Data> >();
            instance.Data.Add("boatData", formData);
            await UpdateInstance(instance, applicationId, applicationOwnerId, instanceOwnerId, instanceId);

            return(instanceId);
        }