public void AdministratorDefaultToWriteAccess()
            {
                Application application = new Application
                {
                    FormId = "form-1",
                    OrganisationId = "org-1",
                    WorkflowState = "New"
                };

                User user = new User
                {
                    Id = "administrator-1",
                    Roles = new Dictionary<string, string> { { "role-1", "role-1" }, { "Administrators", "Administrators" } }
                };
                user.Organisations.Add("org-1", "Organisation One");

                var controlsList = new ControlList
                                       {
                                           new TextControl { Id = 1 }
                                       };

                AccessLevel applicationAccess = this.provider.GetApplicationAccess(new SecureSession(user), application, this.roleList, 1);
                List<ControlAccess> controlsAccess = this.provider.GetControlsAccess(new SecureSession(user), application, controlsList, this.roleList, 1);

                Assert.AreEqual(AccessLevel.Write, applicationAccess);
                Assert.AreEqual(AccessLevel.Write, controlsAccess[0].AccessLevel);
            }
        /// <summary>
        /// Populates <paramref name="target"/> with static and <paramref name="source"/> values
        /// as defined by <paramref name="fieldMap"/>.
        /// </summary>
        /// <param name="source">The application from which to get field values.</param>
        /// <param name="fieldMap">A definition of field mappings.</param>
        /// <param name="target">The target object to populate with mapped key/values.</param>
        internal void Map(Application source, MappedFieldList fieldMap, JObject target)
        {
            foreach (MappedField map in fieldMap)
            {
                switch (map.MapType)
                {
                    case MapType.Value:
                    case MapType.PrivateValue:
                        target.Add(map.Target, map.Source);
                        break;

                    case MapType.Field:
                        object tokenValue = source.GetTokenValue(map.Source);
                        if (tokenValue == null)
                        {
                            target.Add(map.Target, string.Empty);
                        }
                        else if (tokenValue is IEnumerable<object>)
                        {
                            target.Add(map.Target, JArray.FromObject(tokenValue));
                        }
                        else
                        {
                            target.Add(map.Target, tokenValue.ToString());
                        }

                        break;

                    default:
                        throw new InvalidOperationException(string.Format(ExceptionMessages.InvalidMapType, map.MapType));
                }
            }
        }
            public void GetDataPropertyValueUnknownToken()
            {
                Application application = new Application();

                object value = application.GetTokenValue("Foo");
                Assert.IsNull(value);
            }
            public void AccessNewApplication()
            {
                ApplicationEntitlementProvider wrappedProvider = new ApplicationEntitlementProvider(new MockSecurityService());
                FormPreviewApplicationEntitlementProvider provider = new FormPreviewApplicationEntitlementProvider(wrappedProvider)
                {
                    ImpersonatedSession = new ImpersonatedSession(new Dictionary<string, string>
                                                                                                                       {
                                                                                                                           { "role-2", "role-2" }
                                                                                                                       })
                };

                Application application = new Application
                {
                    FormId = "form-1",
                    OrganisationId = "org-1",
                    WorkflowState = "New"
                };

                User user = new User
                {
                    Id = "user-1",
                    Roles = new Dictionary<string, string>
                            { { "role-1", "role-1" } }
                };
                user.Organisations.Add("org-1", "Organisation One");

                AccessLevel applicationAccess = provider.GetApplicationAccess(new SecureSession(user), application, this.roleList, 1);

                Assert.AreEqual(AccessLevel.Write, applicationAccess);
            }
        /// <summary>
        /// Gets the base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.
        /// </summary>
        /// <param name="session">Contains session and user information used to determine access rights.</param>
        /// <param name="application">The application.</param>
        /// <param name="roleList">The list of roles.</param>
        /// <param name="versionNumber">The version number of the form being accessed.</param>
        /// <returns>The base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.</returns>
        public virtual AccessLevel GetApplicationAccess(SecureSession session, Application application, RoleList roleList, int versionNumber)
        {
            if (this.IsAdministrator(session))
            {
                return AccessLevel.Write;
            }

            if (!this.IsOrganisationEntitled(session, application))
            {
                return AccessLevel.NoAccess;
            }

            string userId = this.GetSessionUserId(session);
            bool viewAllDrafts = session.AuthenticatedUser != null && this.GetSystemEntitlements(userId)[SystemEntitlementAccess.VIEW_DRAFT_APPLICATIONS] > AccessLevel.NoAccess;
            if (application.Draft && application.AssignedTo != userId && !viewAllDrafts)
            {
                return AccessLevel.NoAccess;
            }

            var systemEntitlements = this.GetSystemEntitlements(session.AuthenticatedUser != null ? session.AuthenticatedUser.Id : null);

            if (application.Draft && application.AssignedTo != userId && systemEntitlements[SystemEntitlementAccess.VIEW_DRAFT_APPLICATIONS] == AccessLevel.NoAccess)
            {
                return AccessLevel.NoAccess;
            }

            Dictionary<string, string> userRoles = this.DetermineRolesForUser(session, roleList, application);
            ApplicationEntitlementList applicationEntitlements = this.securityService.GetApplicationEntitlements(application.FormId, versionNumber, application.WorkflowState, userRoles.Keys);
            return applicationEntitlements.Any() ? applicationEntitlements.Max(e => e.AccessLevel) : AccessLevel.NoAccess;
        }
            public void GetClassPropertyValueNull()
            {
                Application application = new Application();

                object value = application.GetTokenValue("ApplicationId");
                Assert.IsNull(value);
            }
 public void ApplicationUrl()
 {
     Application application = new Application { ApplicationId = "4kdlsjfdlsfjldsads" };
     this.formatter.BaseUrl = @"http://core.iapply.web";
     string replaced = this.formatter.Format(@"{%ApplicationUrl%}", application, new ControlList());
     string testUrl = string.Format("{0}/#/form/{1}/app/{2}", this.formatter.BaseUrl, application.FormId, application.ApplicationId);
     Assert.AreEqual(string.Format("<a href=\"{0}\">{0}</a>", testUrl), replaced);
 }
            public void GetDataPropertyValue()
            {
                Application application = new Application();
                application.ApplicationData.Add("Foo", "Bar");

                string value = application.GetTokenValue("Foo").ToString();
                Assert.AreEqual("Bar", value);
            }
            public void GetDataPropertyValueNull()
            {
                Application application = new Application();
                application.ApplicationData.Add("Foo", null);

                object value = application.GetTokenValue("Foo");
                Assert.IsNull(value);
            }
            public void DateTimeStamp()
            {
                Application application = new Application { OrganisationId = "MyOrg!", ApplicationId = "4kdlsjfdlsfjldsads" };

                string replaced = this.formatter.Format(@"Example\Path\Docs\{%OrganisationId%}_{%ApplicationId%}_{%Timestamp[yyyyMMdd-HHmmss]%}.pdf", application, new ControlList());
                string date = DateTime.Now.ToString("yyyyMMdd-HHmmss");
                Assert.AreEqual(@"Example\Path\Docs\MyOrg!_4kdlsjfdlsfjldsads_" + date + ".pdf", replaced);
            }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationWorkflowItem"/> class.
 /// </summary>
 /// <param name="postedApplication">The updated <see cref="Application"/> containing
 /// the posted <see cref="ApplicationData"/>.</param>
 /// <param name="existingData">The existing <see cref="ApplicationData"/>. Defaults to <see langword="null"/>.</param>
 /// <param name="controlList">The controls. Defaults to <see langword="null"/>.</param>
 public ApplicationWorkflowItem(Application postedApplication, ApplicationData existingData = null, ControlList controlList = null)
     : this(postedApplication.FormId, postedApplication.LastEditBy)
 {
     this.ApplicationId = postedApplication.ApplicationId;
     this.VersionNumber = postedApplication.VersionNumber;
     this.PostedData = postedApplication.ApplicationData;
     this.ExistingData = existingData;
     this.ControlList = controlList;
 }
        /// <summary>
        /// Gets the base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.
        /// </summary>
        /// <param name="session">Contains session and user information used to determine access rights.</param>
        /// <param name="application">The application.</param>
        /// <param name="roleList">The list of roles.</param>
        /// <param name="versionNumber">The version number of the form being accessed.</param>
        /// <returns>The base <see cref="AccessLevel" /> applicable for a combination of user &amp; application.</returns>
        public AccessLevel GetApplicationAccess(SecureSession session, Application application, RoleList roleList, int versionNumber)
        {
            if (this.ImpersonatedSession != null && string.IsNullOrWhiteSpace(application.Id))
            {
                this.ImpersonateEntitlements(session);
            }

            return this.wrappedProvider.GetApplicationAccess(session, application, roleList, versionNumber);
        }
            public void GetClassPropertyValue()
            {
                Application application = new Application
                {
                    ApplicationId = "GetMe"
                };

                string value = application.GetTokenValue("ApplicationId").ToString();
                Assert.AreEqual("GetMe", value);
            }
            public void ApplicationDataValueNotFound()
            {
                Application application = new Application { OrganisationId = "MyOrg!", ApplicationId = "4kdlsjfdlsfjldsads" };
                application.ApplicationData.Add("key1", "someval");
                application.ApplicationData.Add("key2", 456);
                application.ApplicationData.Add("key3", false);

                string replaced = this.formatter.Format(@"Example\Path\Docs\{%OrganisationId%}_{%ApplicationId%}_{%Timestamp[yyyyMMdd]%}_{%keyunknown%}.pdf", application, new ControlList());
                string date = DateTime.Now.ToString("yyyyMMdd");
                Assert.AreEqual(@"Example\Path\Docs\MyOrg!_4kdlsjfdlsfjldsads_" + date + "_.pdf", replaced);
            }
        /// <summary>
        /// Creates and returns a GET request.
        /// </summary>
        /// <param name="baseUrl">The base URL, to which QueryString parameters will be appended.</param>
        /// <param name="application">The application.</param>
        /// <param name="requestFieldMap">The list of request fields to map.</param>
        /// <param name="obfuscatedRequestBody">The request body.</param>
        /// <returns>A new <see cref="HttpWebRequest" /> that uses the GET method.</returns>
        private HttpWebRequest CreateGetRequest(string baseUrl, Application application, MappedFieldList requestFieldMap, out string obfuscatedRequestBody)
        {
            Dictionary<string, string> parameterData = this.GetHttpVariableRequestContent(application, requestFieldMap);

            string url = new UrlBuilder().Create(baseUrl, parameterData);
            Uri myUri = new Uri(url);
            obfuscatedRequestBody = this.ObfuscateRequest(myUri.Query, HttpResources.HttpRequestFieldValueLocator, requestFieldMap);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Get;
            return request;
        }
        public string SendRequest(ServiceEndpoint endpoint, ServiceEndpointUtilisation utilisation, Application application, ApplicationData updateTarget)
        {
            if (this.type == "VALIDATE")
            {
                string validateStr = AssemblyResourceReader.ReadAsString(string.Format("Test_Data.EndpointValidation.VALIDATE-{0}.json", endpoint.Id.PadLeft(2, '0')));

                return validateStr;
            }

            return null;
        }
        /// <summary>
        /// Creates a new <see cref="HttpWebRequest" />.
        /// </summary>
        /// <param name="endpoint">Contains information on what sort of request to create.</param>
        /// <param name="application">The application containing values to map.</param>
        /// <param name="requestFieldMap">The list of request fields to map.</param>
        /// <param name="obfuscatedRequestBody">The request body.</param>
        /// <returns>A new <see cref="HttpWebRequest" />.</returns>
        internal HttpWebRequest Create(ServiceEndpoint endpoint, Application application, MappedFieldList requestFieldMap, out string obfuscatedRequestBody)
        {
            obfuscatedRequestBody = string.Empty;
            if (endpoint.Method == HttpRequestMethod.GET && endpoint.RequestFormat != ServiceDataFormat.HttpVariables)
            {
                throw new InvalidOperationException(string.Format(ExceptionMessages.IncompatibleRequestFormat, endpoint.RequestFormat, endpoint.Method));
            }

            return (endpoint.Method == HttpRequestMethod.GET) ?
                this.CreateGetRequest(endpoint.Url, application, requestFieldMap, out obfuscatedRequestBody) :
                this.CreatePostRequest(endpoint, application, requestFieldMap, out obfuscatedRequestBody);
        }
            public void NestedCalcDependency()
            {
                Application app = new Application();

                app.ApplicationData[this.rootControl.Name] = "9"; // * 3

                List<Dictionary<string, object>> outerValue = new List<Dictionary<string, object>>
                                                              {
                                                                  new Dictionary<string, object>()
                                                              };
                outerValue[0][this.outerChild.Name] = "7"; // *2
                outerValue.Add(new Dictionary<string, object>());
                outerValue[1][this.outerChild.Name] = "6"; // *2

                List<Dictionary<string, object>> innerValue0 = new List<Dictionary<string, object>>
                                                               {
                                                                   new Dictionary<string, object>()
                                                               };
                innerValue0[0][this.innerChild.Name] = "10"; // * 5
                innerValue0.Add(new Dictionary<string, object>());
                innerValue0[1][this.innerChild.Name] = "8"; // * 5
                outerValue[0][this.innerRepeat.Name] = innerValue0.ToArray();

                List<Dictionary<string, object>> innerValue1 = new List<Dictionary<string, object>>
                                                               {
                                                                   new Dictionary<string, object>()
                                                               };
                innerValue1[0][this.innerChild.Name] = "4"; // * 5
                innerValue1.Add(new Dictionary<string, object>());
                innerValue1[1][this.innerChild.Name] = "5"; // * 5
                outerValue[1][this.innerRepeat.Name] = innerValue1.ToArray();

                app.ApplicationData[this.outerRepeat.Name] = outerValue.ToArray();

                MultiExpressionEvaluator evaluator = new MultiExpressionEvaluator(app, this.controlList);
                ApplicationData result = evaluator.EvaluateAll();

                /* RootControl | RootCalc | OuterChild | OuterCalc | InnerChild | InnerCalc | InnerCalcWithDependency
                 *           9 |       27 |          7 |        14 |         10 |        50 |                      91
                 *           9 |       27 |          7 |        14 |          8 |        40 |                      81
                 *           9 |       27 |          6 |        12 |          4 |        20 |                      59
                 *           9 |       27 |          6 |        12 |          5 |        25 |                      64
                 */

                var outerResult = (Dictionary<string, object>[])result[this.outerRepeat.Name];
                var outer0Inner = (Dictionary<string, object>[])outerResult[0][this.innerRepeat.Name];
                var outer1Inner = (Dictionary<string, object>[])outerResult[1][this.innerRepeat.Name];
                Assert.AreEqual("91", outer0Inner[0][this.innerCalcWithDependency.Name]);
                Assert.AreEqual("81", outer0Inner[1][this.innerCalcWithDependency.Name]);
                Assert.AreEqual("59", outer1Inner[0][this.innerCalcWithDependency.Name]);
                Assert.AreEqual("64", outer1Inner[1][this.innerCalcWithDependency.Name]);
            }
            public void ApplicationDataMissingValue()
            {
                Application application = new Application(new ApplicationData(), Guid.NewGuid().ToString("N"));
                MappedFieldList fieldMap = new MappedFieldList
                {
                    new MappedField { MapType = MapType.Field, Source = "ReleaseYear", Target = "FinalDestination2" }
                };
                new XmlEndpointRequestMapper().Map(application, fieldMap, this.xmlDoc);

                XmlNodeList nodeList = this.xmlDoc.GetElementsByTagName("FinalDestination2");
                Assert.AreEqual(1, nodeList.Count);
                Assert.AreEqual(string.Empty, nodeList[0].InnerText);
            }
            public void ApplicationDataMissingValue()
            {
                Application application = new Application(new ApplicationData(), Guid.NewGuid().ToString("N"));
                MappedFieldList fieldMap = new MappedFieldList
                {
                    new MappedField { MapType = MapType.Field, Source = "ReleaseYear", Target = "FinalDestination2" }
                };
                Dictionary<string, string> dictionary = new Dictionary<string, string>();

                new HttpVarEndpointRequestMapper().Map(application, fieldMap, dictionary);

                Assert.AreEqual(string.Empty, dictionary["FinalDestination2"]);
            }
            public void ApplicationDataMissingValue()
            {
                Application application = new Application(new ApplicationData(), Guid.NewGuid().ToString("N"));
                MappedFieldList fieldMap = new MappedFieldList
                {
                    new MappedField { MapType = MapType.Field, Source = "ReleaseYear", Target = "FinalDestination2" }
                };
                JObject jobj = new JObject();

                new JsonEndpointRequestMapper().Map(application, fieldMap, jobj);

                Assert.AreEqual(string.Empty, jobj.GetValue("FinalDestination2"));
            }
            public void GetClassPropertyValueNested()
            {
                Application application = new Application
                {
                    CreatedBy = new AuthenticatedApplicationUser
                    {
                        DisplayName = "Foo Bar"
                    }
                };

                string value = application.GetTokenValue("CreatedBy.DisplayName").ToString();
                Assert.AreEqual("Foo Bar", value);
            }
        public AccessLevel GetApplicationAccess(SecureSession session, Application application, RoleList roleList, int versionNumber)
        {
            string resourceString;
            string userId = session.AuthenticatedUser == null ? string.Empty : session.AuthenticatedUser.Id;
            string formName = string.Format("Test_Data.ApplicationPermissions.FORM-{0}-USER-{1}.json", application.FormId.PadLeft(2, '0'), userId);
            if (AssemblyResourceReader.TryReadAsString(formName, out resourceString))
            {
                var applicationEntitlements = JsonConvert.DeserializeObject<ApplicationEntitlementList>(resourceString);
                applicationEntitlements = new ApplicationEntitlementList(applicationEntitlements.Where(e => e.ProductId == application.FormId && e.ProductVersion == application.FormVersion && e.StateName == application.WorkflowState && roleList.Contains(e.RoleId)));
                return applicationEntitlements.Max(e => e.AccessLevel);
            }

            return AccessLevel.NoAccess;
        }
        public void WriteApplicationPdfWithEveryControl()
        {
            ControlList list = ControlListActivator.CreateControlList();
            ApplicationPdfWriter writer = new ApplicationPdfWriter();
            Application application = new Application { ApplicationData = new ApplicationData() };

            foreach (Control control in list)
            {
                ValueControl valueControl = control as ValueControl;
                ContainerControl containerControl = control as ContainerControl;
                CalculationControl calculationControl = control as CalculationControl;

                if (valueControl == null && containerControl == null && calculationControl == null)
                {
                    continue;
                }

                object value;
                switch (control.Type)
                {
                    case ControlType.CheckboxGroup:
                        value = new string[0];
                        break;

                    case ControlType.Repeater:
                        value = new object[0];
                        break;

                    case ControlType.Likert:
                        value = new Dictionary<string, object>();
                        break;

                    default:
                        value = string.Empty;
                        break;
                }

                application.ApplicationData.Add(control.Name, value);
            }

            using (MemoryStream stream = new MemoryStream())
            {
                writer.WritePdfToStream(application, list, stream);
            }
        }
        public List<ControlAccess> GetControlsAccess(
            SecureSession session,
            Application application,
            ControlList controlList,
            RoleList roleList,
            int versionNumber,
            AccessLevel? defaultAccessLevel = null)
        {
            string resourceString;
            if (AssemblyResourceReader.TryReadAsString(string.Format("Test_Data.ControlPermissions.FORM-{0}-USER-{1}.json", application.FormId.PadLeft(2, '0'), session.AuthenticatedUser.Id), out resourceString))
            {
                var entitlements = JsonConvert.DeserializeObject<ControlEntitlementList>(resourceString);
                entitlements.Merge();
                return new List<ControlAccess>(entitlements.Select(e => new ControlAccess(e.ControlId, e.AccessLevel)));
            }

            return new List<ControlAccess>();
        }
        /// <summary>
        /// Creates a returns a POST request.
        /// </summary>
        /// <param name="endpoint">Contains information on what sort of request to create.</param>
        /// <param name="application">The application.</param>
        /// <param name="requestFieldMap">The list of request fields to map.</param>
        /// <param name="obfuscatedRequestBody">The request body.</param>
        /// <returns>A new <see cref="HttpWebRequest" /> uses the POST method.</returns>
        private HttpWebRequest CreatePostRequest(ServiceEndpoint endpoint, Application application, MappedFieldList requestFieldMap, out string obfuscatedRequestBody)
        {
            string content = string.Empty;
            string contentType = string.Empty;
            obfuscatedRequestBody = string.Empty;

            switch (endpoint.RequestFormat)
            {
                case ServiceDataFormat.HttpVariables:
                    contentType = InternetMediaType.ApplicationXFormEncodedData;
                    content = this.GetHttpVariableRequestContent(application, requestFieldMap).ToHttpVariables();
                    obfuscatedRequestBody = this.ObfuscateRequest(content, HttpResources.HttpRequestFieldValueLocator, requestFieldMap);
                    break;

                case ServiceDataFormat.Json:
                    contentType = InternetMediaType.ApplicationJson;
                    content = this.GetJsonRequestContent(application, requestFieldMap);
                    obfuscatedRequestBody = this.ObfuscateRequest(content, HttpResources.JsonRequestFieldValueLocator, requestFieldMap);
                    break;

                case ServiceDataFormat.Xml:
                    contentType = InternetMediaType.TextXml;
                    content = this.GetXmlRequestContent(endpoint.RequestRoot, application, requestFieldMap);
                    obfuscatedRequestBody = this.ObfuscateRequest(content, HttpResources.XmlRequestFieldValueLocator, requestFieldMap);
                    break;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint.Url);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = contentType;

            byte[] bytes = Encoding.UTF8.GetBytes(content);
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            return request;
        }
        /// <summary>
        /// Populates <paramref name="target"/> with static and <paramref name="source"/> values
        /// as defined by <paramref name="fieldMap"/>.
        /// </summary>
        /// <param name="source">The application from which to get field values.</param>
        /// <param name="fieldMap">A definition of field mappings.</param>
        /// <param name="target">The target object to populate with mapped key/values.</param>
        internal void Map(Application source, MappedFieldList fieldMap, XmlDocument target)
        {
            XmlNode root = target.FirstChild;
            foreach (MappedField map in fieldMap)
            {
                switch (map.MapType)
                {
                    case MapType.Value:
                    case MapType.PrivateValue:
                        root.AddElement(map.Target, map.Source);
                        break;

                    case MapType.Field:
                        object tokenValue = source.GetTokenValue(map.Source);
                        if (tokenValue == null)
                        {
                            root.AddElement(map.Target, string.Empty);
                        }
                        else
                        {
                            var value = tokenValue as IEnumerable<object>;
                            if (value != null)
                            {
                                this.GetNestedValue(value, map, root);
                            }
                            else
                            {
                                root.AddElement(map.Target, tokenValue.ToString());
                            }
                        }

                        break;

                    default:
                        throw new InvalidOperationException(string.Format(ExceptionMessages.InvalidMapType, map.MapType));
                }
            }
        }
        /// <summary>
        /// Get data from all configured external sources.
        /// </summary>
        /// <param name="formId">The form id.</param>
        /// <param name="formVersion">The form version.</param>
        /// <param name="pageId">The page id.</param>
        /// <param name="updatedApp">The posted application.</param>
        /// <param name="existingData">The existing saved application data, which will be <see langword="null"/> if the application has never been saved.</param>
        /// <returns>The updated application data after all data has been retrieved.</returns>
        public ApplicationData GetExternalData(string formId, int? formVersion, int pageId, Application updatedApp, ApplicationData existingData)
        {
            ProductDataSourceConfiguration dataSourceConfig = this.applicationManager.GetProductDataSourceConfiguration(formId, formVersion);
            if (dataSourceConfig == null || dataSourceConfig.DataSources == null || dataSourceConfig.DataSources.Count == 0)
            {
                return null;
            }

            bool updated = false;

            PageList pages = this.applicationManager.GetProduct(formId, formVersion).FormDefinition.Pages;

            foreach (ProductDataSource dataSource in dataSourceConfig.DataSources)
            {
                if (this.KeysHaveChanged(dataSource, updatedApp.ApplicationData, existingData) && this.DetermineOptimalPageId(dataSource, pages) == pageId)
                {
                    ServiceEndpoint endpoint = this.dataAccess.GetServiceEndpoint(dataSource.ServiceEndpointId);
                    this.communicator.SendRequest(endpoint, dataSource, updatedApp, updatedApp.ApplicationData);
                    updated = true;
                }
            }

            return updated ? updatedApp.ApplicationData : null;
        }
        /// <summary>
        /// Searches an external data source and returns the formatted results.
        /// </summary>
        /// <param name="formId">The form id.</param>
        /// <param name="formVersion">The form version.</param>
        /// <param name="controlName">The control name.</param>
        /// <param name="searchTerm">The search term.</param>
        /// <param name="application">The application containing the posted application data.</param>
        /// <returns>The formatted results from the external data source.</returns>
        public object[] SearchExternalData(string formId, int? formVersion, string controlName, string searchTerm, Application application)
        {
            SearchControl control = this.applicationManager.GetProduct(formId, formVersion).FormDefinition.Pages.AllControls.FindRecursive<SearchControl>(controlName);
            ServiceEndpoint endpoint = this.dataAccess.GetServiceEndpoint(control.SearchSource.ServiceEndpointId);
            application.ApplicationData.Add(controlName, searchTerm);
            string resultJson = this.communicator.SendRequest(endpoint, control.SearchSource, application, null);

            object[] results;
            try
            {
                results = JsonConvert.DeserializeObject<object[]>(resultJson);
            }
            catch (JsonSerializationException)
            {
                results = new[]
                          {
                              JsonConvert.DeserializeObject<object>(resultJson)
                          };
            }

            return results;
        }
        public void TestInitialise()
        {
            this.roleList.Add(new Role { Id = "role-1" });
            this.roleList.Add(new Role { Id = "role-2" });
            this.roleList.Add(new Role { Id = "originator", SystemDefined = true, RoleName = "originator" });
            Dictionary<string, string> user1Roles = new Dictionary<string, string>
                                                    {
                    { "role-2", "role-2" }
                };
            Dictionary<string, string> user2Roles = new Dictionary<string, string>
                                                    {
                    { "role-2", "role-2" }
                };
            Dictionary<string, string> user3Roles = new Dictionary<string, string>
                                                    {
                    { "role-1", "role-1" }
                };

            this.userList.Add(new User { Id = "user-1", EmailAddress = "*****@*****.**", Roles = user1Roles });
            this.userList.Add(new User { Id = "user-2", EmailAddress = "*****@*****.**", Roles = user2Roles });
            this.userList.Add(new User { Id = "user-3", EmailAddress = "*****@*****.**", Roles = user3Roles });

            this.action = new EmailWorkflowTransitionAction
                          {
                AttachPdf = false,
                Condition = null,
                Content = "The email body goes here",
                Recipients = this.recipientList,
                Subject = "The subject line",
                EmailLinks = new List<string>()
            };
            this.application = new Application
                               {
                Id = "123456",
                FormId = "654321",
                ApplicationData = new ApplicationData()
            };

            this.systemSettings.Uris[SystemUriType.BaseSite] = "test.iapply.web";

            this.emptyPageList = new PageList
                                 {
                                     new UserPage
                                     {
                                         Controls = new ControlList()
                                     }
                                 };

            this.getUserFn = criteria =>
            {
                UserList users = new UserList();
                if (criteria.RoleIds != null)
                {
                    foreach (var role in criteria.RoleIds)
                    {
                        users.AddRange(this.userList.Where(u => u.HasRole(role)));
                    }
                }

                if (criteria.UserIds != null)
                {
                    foreach (var user in criteria.UserIds)
                    {
                        users.AddRange(this.userList.Where(u => u.Id == user));
                    }
                }

                return users;
            };
        }