Пример #1
0
        private void buttonFormStorage_Click(object sender, EventArgs e)
        {
            FormStorage purchase = new FormStorage();

            purchase.StartPosition = FormStartPosition.CenterScreen;
            purchase.Show();
        }
Пример #2
0
        public EventEditor(EventEntry entry, FormStorage<EventStatus> storage)
        {
            _entry = entry;
            _eventMode = storage.Value;
            _storage = storage;

            InitializeComponent();

            if(_eventMode == EventStatus.Create)
            {
                this.Text += " - Create Event";
            }
            else
            {
                this.Text += " - Modify Event";

                buttonRemove.Enabled = true;
                textEventName.Text = _entry.EventName;
                timeStart.Value = _entry.EventActivationTime;
                timeEnd.Value = _entry.EventDeactivationTime;
                textDescription.Text = _entry.Description;
            }

            if (_storage.Value == EventStatus.Print)
            {
                this.buttonAccept.Visible = false;
                this.buttonCancel.Visible = false;
                this.buttonRemove.Visible = false;
                this.Shown += new EventHandler(Print);
            }
        }
        /// <summary>
        /// Returns a list of users granted access to an Umbraco Form.
        /// </summary>
        /// <param name="userService">The user service.</param>
        /// <param name="formId">The form identifier.</param>
        /// <returns></returns>
        public FormSecurity PermissionsToForm(IUserService userService, Guid formId)
        {
            if (userService == null)
            {
                throw new ArgumentNullException(nameof(userService));
            }

            var formSecurity = new FormSecurity();

            using (FormStorage formStorage = new FormStorage())
            {
                var form = formStorage.GetForm(formId);
                if (form != null)
                {
                    formSecurity.FormName = form.Name;
                }
            }

            using (UserFormSecurityStorage formSecurityStorage = new UserFormSecurityStorage())
            {
                var permissions = formSecurityStorage.GetUserFormSecurityForAllUsers(formId).Where <UserFormSecurity>(permission => permission.HasAccess == true);
                foreach (var permission in permissions)
                {
                    var userId = Int32.Parse(permission.User, CultureInfo.InvariantCulture);
                    formSecurity.Users.Add(new FormUser()
                    {
                        UserId          = userId,
                        UserDisplayName = userService.GetUserById(userId).Name
                    });
                }
            }

            return(formSecurity);
        }
        /// <summary>
        /// Each Umbraco User should have an Umbraco Forms permissions record for each form.
        /// This preserves existing permissions and adds a 'deny' permission if there is no record.
        /// </summary>
        /// <param name="userId">The user.</param>
        /// <param name="forEveryone">if set to <c>true</c> overwrite all existing permissions with 'deny'.</param>
        public void RemoveDefaultAccessToForms(int userId, bool forEveryone)
        {
            using (FormStorage formStorage = new FormStorage())
            {
                using (UserFormSecurityStorage formSecurityStorage = new UserFormSecurityStorage())
                {
                    IEnumerable <Form> allForms = formStorage.GetAllForms();
                    foreach (Form form in allForms)
                    {
                        var formSecurityForUser = formSecurityStorage.GetUserFormSecurity(userId, form.Id).FirstOrDefault();
                        var hasSecurityAlready  = (formSecurityForUser != null);
                        if (!hasSecurityAlready)
                        {
                            formSecurityForUser      = UserFormSecurity.Create();
                            formSecurityForUser.User = userId.ToString();
                            formSecurityForUser.Form = form.Id;
                        }
                        formSecurityForUser.HasAccess = false;

                        if (!hasSecurityAlready)
                        {
                            formSecurityStorage.InsertUserFormSecurity(formSecurityForUser);
                        }
                        else if (forEveryone)
                        {
                            formSecurityStorage.UpdateUserFormSecurity(formSecurityForUser);
                        }
                    }
                }
            }
        }
Пример #5
0
        /// <summary>
        /// The method called to render the contents of the tree structure
        /// </summary>
        /// <param name="id"></param>
        /// <param name="queryStrings">All of the query string parameters passed from jsTree</param>
        /// <returns></returns>
        /// <remarks>
        /// We are allowing an arbitrary number of query strings to be pased in so that developers are able to persist custom data from the front-end
        /// to the back end to be used in the query for model data.
        /// </remarks>
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            // check if we're rendering the root node's children
            if (id == Constants.System.Root.ToInvariantString())
            {
                var tree = new TreeNodeCollection();

                // Add a tree node for each form to which the current user has access
                using (FormStorage formStorage = new FormStorage())
                {
                    IEnumerable <UmbracoForms.Core.Form> forms = formStorage.GetForms();
                    foreach (UmbracoForms.Core.Form form in forms)
                    {
                        if (UmbracoForms.Web.FormsSecurity.HasAccessToForm(form.Id))
                        {
                            tree.Add(CreateTreeNode(form.Id.ToString(), id, queryStrings, form.Name, "icon-autofill"));
                        }
                    }
                }

                // Sort the forms alphabetically by name
                tree.Sort(new TreeNodeComparer());

                return(tree);
            }
            // this tree doesn't support rendering more than 1 level
            throw new NotSupportedException();
        }
Пример #6
0
        public static string AddFieldsFromContour(this DynaForm dynaform, string formGuid)
        {
            var retval = "";
            using (var recordStorage = new RecordStorage())
            using (var formStorage = new FormStorage())
            {
                var form = formStorage.GetForm(new Guid(formGuid));
                foreach (var field in form.AllFields.OrderBy(f => f.SortOrder))
                {
                    var inputType = InputType.text;
                    var fieldName = "f" + field.Id.ToString().Replace('-', '_');
                    var defaultValue = "";
                    if (field.Values.Count > 0)
                        defaultValue = field.Values[0].ToString();
                    var cssName = "";
                    if (field.Mandatory)
                        cssName = "required";

                    if (field.FieldType.ToString() == "Umbraco.Forms.Core.Providers.FieldTypes.DropDownList")
                    {
                        dynaform.AddFormField(fieldName, field.Caption, type: InputType.select, defaultValue: defaultValue, cssName: cssName);
                    }
                    else if (field.FieldType.ToString() == "Umbraco.Forms.Core.Providers.FieldTypes.Hidden")
                    {
                        dynaform.AddFormField(fieldName, field.Caption, type: InputType.hidden, defaultValue: defaultValue, cssName: cssName);
                    }
                    else
                    {
                        dynaform.AddFormField(fieldName, field.Caption, type: InputType.text, defaultValue: defaultValue, required: field.Mandatory, errorMessage: field.RequiredErrorMessage, cssName: cssName);
                    }

                }
            }
            return retval;
        }
Пример #7
0
        public StudySelector(FormStorage<string> s)
        {
            _storage = s;

            InitializeComponent();

            this.listMajors.DataSource = CollegeData.Majors.Keys.ToList();
        }
Пример #8
0
        public static string SaveToContour(this DynaForm dynaform, string formGuid, out string insertedRecordId, string userIpAddress = "", int umbracoPageId = 0)
        {
            var message = "";
            insertedRecordId = "";

            using (var recordStorage = new RecordStorage())
            using (var formStorage = new FormStorage())
            {
                var form = formStorage.GetForm(new Guid(formGuid));

                using (var recordService = new RecordService(form))
                {
                    recordService.Open();

                    var record = recordService.Record;
                    record.IP = userIpAddress;
                    record.UmbracoPageId = umbracoPageId;
                    recordStorage.InsertRecord(record, form);

                    foreach (var field in recordService.Form.AllFields)
                    {

                        string currentFieldValue = "";
                        string contourFieldName = field.Caption.TrimStart('#');

                        if (dynaform.ModelDictionary.ContainsKey("f" + field.Id.ToString().Replace('-', '_')))
                        {
                            currentFieldValue = dynaform.ModelDictionary["f" + field.Id.ToString().Replace('-', '_')].ToString();
                        }
                        else if (dynaform.ModelDictionary.ContainsKey(contourFieldName))
                        {
                            currentFieldValue = dynaform.ModelDictionary[contourFieldName].ToString();
                        }

                        var key = Guid.NewGuid();
                        var recordField = new RecordField
                        {
                            Field = field,
                            Key = key,
                            Record = record.Id,
                            Values = new List<object> { currentFieldValue }
                        };

                        using (var recordFieldStorage = new RecordFieldStorage())
                            recordFieldStorage.InsertRecordField(recordField);

                        record.RecordFields.Add(key, recordField);

                        insertedRecordId = record.Id.ToString();
                    }
                    recordService.Submit();
                    recordService.SaveFormToRecord();

                }
                message=form.MessageOnSubmit;
            }
            return message;
        }
Пример #9
0
        public void EventThread(EventEntry entry, EventStatus eventMode)
        {
            FormStorage<EventStatus> storage = new FormStorage<EventStatus>(eventMode);
            Application.Run(new EventEditor(entry, storage));

            if(_eventEditors.ContainsKey(Thread.CurrentThread))
            {
                _eventEditors.Remove(Thread.CurrentThread);
            }

            SAPS.Instance.Invoke(new EventDelegate(UpdateEvents), new object[] { entry, storage.Value });
        }
Пример #10
0
        public ApplicationEditor(DatabaseEntry entry, FormStorage<ApplicationStatus> storage)
        {
            _entry = entry;
            _storage = storage;
            _tempMajors = new BindingList<string>();
            _tempMinors = new BindingList<string>();

            InitializeComponent();

            this.comboBoxGender.DataSource = Enum.GetValues(typeof(Gender));
            this.comboVote.DataSource = Enum.GetValues(typeof(Vote));
            this.comboVote.SelectedIndex = this.comboVote.FindString(Vote.Undecided.ToString());
            this.timeSubmission.Value = _entry.SubmissionDate;
            this.textFirstName.Text = _entry.FirstName;
            this.textMiddleName.Text = _entry.MiddleName;
            this.textLastName.Text = _entry.LastName;
            this.comboBoxGender.SelectedIndex = this.comboBoxGender.FindString(_entry.Gender.ToString());
            this.timeDOB.Value = _entry.DateOfBirth;
            this.textSocial.Text = _entry.SocialSecurity;
            this.textAddress.Text = _entry.StreetAddress;
            this.textCity.Text = _entry.City;
            this.textState.Text = _entry.State;
            this.textZip.Text = _entry.Zip;
            this.textPhone.Text = _entry.Phone;
            this.textGPA.Text = _entry.GPA.ToString();
            this.textScore.Text = _entry.ACTSAT.ToString();
            this.textRank.Text = _entry.ClassRank.ToString();
            foreach (string major in _entry.Majors)
            {
                _tempMajors.Add(major);
            }
            this.listMajors.DataSource = _tempMajors;
            foreach (string minor in _entry.Minors)
            {
                _tempMinors.Add(minor);
            }
            this.listMinors.DataSource = _tempMinors;
            this.listVotes.DataSource = new BindingSource(_entry.votes, null);
            this.textDescriptionComments.Text = _entry.Comments;

            if (_storage.Value == ApplicationStatus.Print)
            {
                buttonAddMajor.Visible = false;
                buttonRemoveMajor.Visible = false;
                buttonAddMinor.Visible = false;
                buttonRemoveMinor.Visible = false;
                buttonCancel.Visible = false;
                buttonRemove.Visible = false;
                buttonSubmit.Visible = false;
                comboVote.Visible = false;
                this.Shown += new EventHandler(Print);
            }
        }
Пример #11
0
        public void ApplicationThread(DatabaseEntry entry, ApplicationStatus status)
        {
            FormStorage<ApplicationStatus> storage = new FormStorage<ApplicationStatus>(status);
            Application.Run(new ApplicationEditor(entry, storage));

            if(_applicationEditors.ContainsKey(Thread.CurrentThread))
            {
                _applicationEditors.Remove(Thread.CurrentThread);
            }

            SAPS.Instance.Invoke(new ApplicationDelegate(UpdateApplications), new object[] { entry, storage.Value });
        }
Пример #12
0
        public HttpResponseMessage DeleteFolder(string folderId, bool deleteForms)
        {
            var folder = PerplexFolder.Get(folderId);

            if (folder == null)
            {
                return new HttpResponseMessage(HttpStatusCode.NotFound)
                       {
                           ReasonPhrase = "Folder with id " + folderId + " not found."
                       }
            }
            ;

            // Delete forms if requested, of this folder and all descendant folders
            if (deleteForms)
            {
                using (FormStorage formStorage = new FormStorage())
                {
                    var formIds = new List <string>(folder.Forms);
                    formIds.AddRange(folder.GetDescendantFolders().SelectMany(f => f.Forms));

                    // Forms of this folder
                    foreach (string formId in formIds)
                    {
                        Guid guid;
                        if (!Guid.TryParse(formId, out guid))
                        {
                            continue;
                        }

                        var form = formStorage.GetForm(guid);
                        if (form != null)
                        {
                            formStorage.DeleteForm(form);
                        }
                    }
                }
            }

            PerplexFolder parentFolder = folder.GetParent();

            // Remove this folder
            folder.Remove();

            // Save to disk
            PerplexFolder.SaveAll();

            // Respond with the parent folder, so we can refresh it
            return(Request.CreateResponse(HttpStatusCode.OK, parentFolder));
        }
        private IEnumerable <Record> GetApprovedRecords(int pageId, Guid formId)
        {
            using (var formStorage = new FormStorage())
            {
                using (var recordStorage = new RecordStorage())
                {
                    var form = formStorage.GetForm(formId);

                    return(recordStorage.GetAllRecords(form)
                           .Where(x => x.UmbracoPageId == pageId && x.State == FormState.Approved)
                           .ToList());
                }
            }
        }
Пример #14
0
        public Search(Dictionary<string, string> searchTerms, System.Type type, FormStorage<bool> storage)
        {
            _searchTerms = searchTerms;
            _storage = storage;
            _searchList = new BindingList<string>();

            InitializeComponent();

            List<string> list = type.GetProperties().Select(p => p.Name).ToList();

            this.comboCriteria.DataSource = type.GetProperties().Select(p => p.Name).ToList();
            this.listSearchTerms.DataSource = _searchList;
            this.buttonRemove.Enabled = false;
        }
 public IEnumerable <Guid> ListForms()
 {
     try
     {
         using (var formStorage = new FormStorage())
         {
             return(formStorage.GetAllForms().Select(form => form.Id));
         }
     }
     catch (Exception exception)
     {
         LogHelper.Error <UmbracoFormsRetentionApiController>(exception.Message, exception);
         throw;
     }
 }
 /// <summary>
 /// Checks whether a back office User has access to a particular form.
 /// </summary>
 /// <param name="userId">The user identifier.</param>
 /// <param name="formId">The form identifier.</param>
 /// <returns></returns>
 public bool UserHasAccessToForm(int userId, Guid formId)
 {
     using (FormStorage formStorage = new FormStorage())
     {
         using (UserFormSecurityStorage formSecurityStorage = new UserFormSecurityStorage())
         {
             var form = formStorage.GetForm(formId);
             var formSecurityForUser = formSecurityStorage.GetUserFormSecurity(userId, formId).FirstOrDefault();
             if (formSecurityForUser == null || !formSecurityForUser.HasAccess)
             {
                 return(false);
             }
         }
     }
     return(true);
 }
        /// <summary>
        /// Resets forms security, which removes all permissions and gives everyone access to every form
        /// </summary>
        /// <param name="userService">The user service.</param>
        /// <exception cref="ArgumentNullException">userService</exception>
        public void ResetFormsSecurity(IUserService userService)
        {
            if (userService == null)
            {
                throw new ArgumentNullException(nameof(userService));
            }

            // For every Umbraco User including disabled accounts, remove their Umbraco Forms permissions (both deny and allow).
            // This actually grants everyone Manage Forms permission because the default is to allow everyone.
            var page  = 0;
            var total = 0;
            var users = userService.GetAll(page, 10, out total);

            while (users.Any())
            {
                foreach (var user in users)
                {
                    using (UserSecurityStorage userSecurityStorage = new UserSecurityStorage())
                    {
                        var userFormSecurityList = userSecurityStorage.GetUserSecurity(user.Id.ToString());
                        foreach (var userSecurity in userFormSecurityList)
                        {
                            userSecurityStorage.DeleteUserSecurity(userSecurity);
                        }
                    }
                }

                page++;
                users = userService.GetAll(page, 10, out total);
            }

            // For every form in Umbraco Forms, remove all the user permissions (both deny and allow).
            // This actually grants everyone access to every form because the default is to allow everyone.
            using (FormStorage formStorage = new FormStorage())
            {
                using (UserFormSecurityStorage formSecurityStorage = new UserFormSecurityStorage())
                {
                    IEnumerable <Form> allForms = formStorage.GetAllForms();
                    foreach (Form form in allForms)
                    {
                        formSecurityStorage.DeleteAllUserFormSecurityForForm(form.Id);
                    }
                }
            }
        }
        public void DeleteComments(int pageId, Guid formId)
        {
            using (var formStorage = new FormStorage())
            {
                using (var recordStorage = new RecordStorage())
                {
                    var form = formStorage.GetForm(formId);

                    var records = recordStorage.GetAllRecords(form)
                                  .Where(x => x.UmbracoPageId == pageId)
                                  .ToList();

                    foreach (var record in records)
                    {
                        recordStorage.DeleteRecord(record, form);
                    }
                }
            }
        }
        public FormWithRecords(string FormGuidString)
        {
            //Set basic properties
            this.FormGuid = new Guid(FormGuidString);

            //The "Library" functions cause "There is already an open DataReader associated with this Command which must be closed first." errors
            //see: https://our.umbraco.org/forum/umbraco-forms/78207-working-with-record-data-there-is-already-an-open-datareader-associated
            //this.RecordsApproved = Library.GetApprovedRecordsFromForm(FormGuidString).Items;
            //this.RecordsAll = Library.GetRecordsFromForm(FormGuidString).Items;
            //Alternative:
            using (var formStorage = new FormStorage())
            {
                using (var recordStorage = new RecordStorage())
                {
                    var form       = formStorage.GetForm(this.FormGuid);
                    var allRecords = recordStorage.GetAllRecords(form).ToList();

                    this.RecordsAll      = allRecords;
                    this.RecordsApproved = allRecords.Where(x => x.State == FormState.Approved).ToList();
                }
            }

            // Get form info
            using (FormStorage formStorage = new FormStorage())
            {
                this.Form = formStorage.GetForm(this.FormGuid);
            }

            //Get all fields
            var fields        = new List <Field>();
            var exampleRecord = RecordsAll.First();

            foreach (var fieldItem in exampleRecord.RecordFields)
            {
                var recField = fieldItem.Value;
                var field    = recField.Field;
                fields.Add(field);
            }
            this.Fields = fields;
        }
		/// <summary>
		/// Gets the field values for the specified field on the specified form.
		/// </summary>
		/// <param name="formName">The name of the Contour form.</param>
		/// <param name="fieldCaption">The caption for the field.</param>
		/// <returns>
		/// The field values and labels.
		/// </returns>
		public static List<ValueLabelStrings> GetFieldValues(string formName, string fieldCaption) {

			// Validation.
			if (string.IsNullOrWhiteSpace(formName) || string.IsNullOrWhiteSpace(fieldCaption)) {
				return null;
			}

			// Get cache of values for specified form/field.
			var cache = null as InstanceCache<List<ValueLabelStrings>>;
			lock (FieldValuesLock) {
				var key = new KeyValueStrings(formName, fieldCaption);
				if (!FieldValues.TryGetValue(key, out cache)) {
					cache = new InstanceCache<List<ValueLabelStrings>>();
					FieldValues[key] = cache;
				}
			}

			// Get values from cache.
			return cache.Get(TimeSpan.FromHours(3), () => {
				var results = new List<ValueLabelStrings>();
				using (var formStorage = new FormStorage()) {
					var form = formStorage.GetForm(formName);
					using (var recordService = new RecordService(form)) {
						recordService.Open();
						foreach (var field in recordService.Form.AllFields) {
							if (fieldCaption.InvariantEquals(field.Caption)) {
								field.PreValueSource.Type.LoadSettings(field.PreValueSource);
								foreach (var item in field.PreValueSource.Type.GetPreValues(field)) {
									results.Add(new ValueLabelStrings(item.Id.ToString(), item.Value));
								}
							}
						}
					}
				}
				return results;
			});

		}
 public IEnumerable <Guid> ListEntries(Guid formId)
 {
     try
     {
         using (var formStorage = new FormStorage())
         {
             var form = formStorage.GetForm(formId);
             if (form == null)
             {
                 return(new Guid[0]);
             }
             using (var recordStorage = new RecordStorage())
             {
                 return(recordStorage.GetAllRecords(form, false).Select(record => record.UniqueId));
             }
         }
     }
     catch (Exception exception)
     {
         LogHelper.Error <UmbracoFormsRetentionApiController>(exception.Message, exception);
         throw;
     }
 }
		/// <summary>
		/// Stores a form submission to Contour.
		/// </summary>
		/// <param name="formName">The name of the form.</param>
		/// <param name="fieldValues">The values to store to contour.</param>
		/// <param name="ipAddress">The user's IP address.</param>
		/// <param name="pageId">The ID of the page the user entered the values on.</param>
		/// <returns>True, if the data was stored successfully; otherwise, false.</returns>
		public static bool StoreRecord(string formName, Dictionary<string, List<object>> fieldValues,
			string ipAddress, int pageId) {

			// Variables.
			var success = true;

			// Ensure keys are lowercase.
			fieldValues = GetLowercaseKeys(fieldValues);

			// Add record.
			using (var formStorage = new FormStorage()) {
				var form = formStorage.GetForm(formName);
				var tempGuid = Guid.Empty;
				success = success && StoreRecord(form, fieldValues, ipAddress, pageId, out tempGuid);
			}

			// Succeeded?
			return success;

		}
		/// <summary>
		/// Returns the GUID that identifies the form with the specified name.
		/// </summary>
		/// <param name="formName">The name of the Contour form.</param>
		/// <returns>The form GUID.</returns>
		public static Guid GetFormGuid(string formName) {
			using (var formStorage = new FormStorage()) {
				var form = formStorage.GetForm(formName);
				if (form == null) {
					return Guid.Empty;
				} else {
					return form.Id;
				}
			}
		}
        public HttpResponseMessage DeleteFolder(string folderId, bool deleteForms)
        {
            var folder = PerplexFolder.Get(folderId);
            if (folder == null) return new HttpResponseMessage(HttpStatusCode.NotFound) { ReasonPhrase = "Folder with id " + folderId + " not found." };

            // Delete forms if requested, of this folder and all descendant folders
            if (deleteForms)
            {
                using (FormStorage formStorage = new FormStorage())
                {
                    var formIds = new List<string>(folder.Forms);
                    formIds.AddRange(folder.GetDescendantFolders().SelectMany(f => f.Forms));

                    // Forms of this folder
                    foreach (string formId in formIds)
                    {
                        Guid guid;
                        if (!Guid.TryParse(formId, out guid)) continue;

                        var form = formStorage.GetForm(guid);
                        if(form != null)
                        {
                            formStorage.DeleteForm(form);
                        }
                    }
                }
            }

            PerplexFolder parentFolder = folder.GetParent();

            // Remove this folder
            folder.Remove();

            // Save to disk
            PerplexFolder.SaveAll();

            // Respond with the parent folder, so we can refresh it
            return Request.CreateResponse(HttpStatusCode.OK, parentFolder);
        }
Пример #25
0
        public static string EmailRecord(String recordId)
        {
            String emailTo = Utils.GetPostParameter("email").ToString();
            String emailFrom = umbraco.UmbracoSettings.NotificationEmailSender;

            FormStorage fs = new FormStorage();
            RecordStorage rs = new RecordStorage();

            Record record = rs.GetRecord(Guid.Parse(recordId));

            Umbraco.Forms.Core.Form form = fs.GetForm(record.Form);

            string data = "<p><b>Form:</b> " + form.Name + "</p>";
            data += "<p><b>State:</b><br/>" + record.State.ToString() + "</p>";
            data += "<p><b>Created:</b><br/>" + record.Created.ToString() + "</p>";
            data += "<p><b>Ip:</b><br/>" + record.IP + "</p>";

            foreach (Field field in form.AllFields)
            {
                string value = string.Empty;
                if (record.GetRecordField(field.Id) != null && record.GetRecordField(field.Id).Values.Count > 0)
                {
                    value = record.GetRecordField(field.Id).Values[0].ToString();
                }
                data += "<p><b>" + field.Caption + ":</b><br/>" + value + "</p>";
            }

            try
            {
                umbraco.library.SendMail(emailFrom, emailTo, "Contour record", data, true);
            }
            catch
            {
                return new MessageBox("Error to send record ", new Button("Close")).UmGo("Warning");
            }

            return new MessageBox("Record sent successfully", new Button("Ok", new Call("ViewData", new string[] { recordId })))
                .UmGo();
        }
Пример #26
0
        public BindingList<DatabaseEntry> Search()
        {
            FormStorage<bool> storage = new FormStorage<bool>(false);
            Dictionary<string, string> searchTerms = new Dictionary<string,string>();
            Search search = new Search(searchTerms, typeof(DatabaseEntry), storage);

            search.ShowDialog();

            if (storage.Value && searchTerms.Count != 0)
            {
                BindingList<DatabaseEntry> searchList = new BindingList<DatabaseEntry>();
                foreach (DatabaseEntry entry in _availableEntries)
                {
                    searchList.Add(entry);
                }

                foreach (KeyValuePair<string, string> pair in searchTerms)
                {
                    for(int i = 0; i < searchList.Count; i++)
                    {
                        if (pair.Value == "Majors" || pair.Value == "Minors")
                        {
                            bool contains = false;

                            BindingList<string> keyList = (BindingList<string>)typeof(DatabaseEntry).GetProperty(pair.Value).GetValue(searchList[i]);

                            foreach (string major in keyList)
                            {
                                if (major.Contains(pair.Key))
                                {
                                    contains = true;
                                }
                            }
                            if(!contains)
                            {
                                i--;
                                searchList.Remove(searchList[i + 1]);
                            }
                        }
                        else
                        {
                            object property = typeof(DatabaseEntry).GetProperty(pair.Value).GetValue(searchList[i]);
                            if (property != null && !property.ToString().Contains(pair.Key))
                            {
                                i--;
                                searchList.Remove(searchList[i + 1]);
                            }
                        }
                    }
                }

                return searchList;
            }

            return _availableEntries;
        }
Пример #27
0
        public static string ListRecord(String formGuid, String pageStr)
        {
            FormState state = FormState.Approved;
            Range range = Range.Day;
            Show show = Show.five;
            int page = int.Parse(pageStr);

            if (Utils.GetPostParameter("State") != null && !string.IsNullOrEmpty(Utils.GetPostParameter("State").ToString()))
                HttpContext.Current.Session["State"] = Utils.GetPostParameter("State").ToString();

            if (Utils.GetPostParameter("Range") != null && !string.IsNullOrEmpty(Utils.GetPostParameter("Range").ToString()))
                HttpContext.Current.Session["Range"] = Utils.GetPostParameter("Range").ToString();

            if (Utils.GetPostParameter("Show") != null && !string.IsNullOrEmpty(Utils.GetPostParameter("Show").ToString()))
                HttpContext.Current.Session["Show"] = Utils.GetPostParameter("Show").ToString();

            if (HttpContext.Current.Session["State"] != null && !string.IsNullOrEmpty(HttpContext.Current.Session["State"].ToString()))
                state = (FormState)Enum.Parse(typeof(FormState), HttpContext.Current.Session["State"].ToString());

            if (HttpContext.Current.Session["Range"] != null && !string.IsNullOrEmpty(HttpContext.Current.Session["Range"].ToString()))
                range = (Range)Enum.Parse(typeof(Range), HttpContext.Current.Session["Range"].ToString());

            if (HttpContext.Current.Session["Show"] != null && !string.IsNullOrEmpty(HttpContext.Current.Session["Show"].ToString()))
                show = (Show)Enum.Parse(typeof(Show), HttpContext.Current.Session["Show"].ToString());

            FormStorage fs = new FormStorage();
            RecordsViewer rv = new RecordsViewer();

            RecordStorage recordStorage = new RecordStorage();

            Umbraco.Forms.Core.Form form = fs.GetForm(Guid.Parse(formGuid));

            System.Collections.Generic.List<Record> records = rv.GetRecords(0, 0, form, Sorting.descending, new List<FormState> { state });

            List calls = new List();

            calls.AddListItem(new ListItem("<b>Filter</b>",
                subtitle: state.ToString() + ", Last " + range.ToString() + ", " + (int)show + " records per page",
                icon: GenericIcon.Filter,
                action: new Call("ConfigFilter", new string[] { formGuid })));

            DateTime minDate = DateTime.Now;
            switch (range)
            {
                case Range.hour:
                    minDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0);
                    break;

                case Range.Month:
                    minDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    break;

                case Range.Year:
                    minDate = new DateTime(DateTime.Now.Year, 1, 1);
                    break;

                case Range.Decade:
                    minDate = DateTime.MinValue;
                    break;

                case Range.Day:
                default:
                    minDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                    break;
            }

            if (records.Where(r => r.Created > minDate).Any())
            {

                int total = records.Where(r => r.Created > minDate).Count();
                IEnumerable<Record> results = records.Where(r => r.Created > minDate).OrderByDescending(r => r.Created).Skip((page - 1) * (int)show).Take((int)show);

                Button nextButton = null;
                if (total > (results.Count() + (page - 1) * (int)show))
                    nextButton = new Button(icon: GenericIcon.ArrowRight, action: new Call("ListRecord", new string[] { formGuid, (page + 1).ToString() }));

                calls.AddListItem(new ListItem("<b>Total result:</b> " + total.ToString(), subtitle: "Page <b>" + page.ToString() + "</b> to <b>" + (((int)(total / (int)show)) + 1).ToString() + "</b>", contextual_button: nextButton));

                foreach (Record record in results)
                {
                    calls.AddListItem(new ListItem(record.Created.ToString(),
                    subtitle: "Ip: " + record.IP,
                    action: new Call("ViewData", new string[] { record.Id.ToString() })));
                }

            }
            else
            {
                calls.AddListItem(new ListItem("<b>Total result:</b> 0", subtitle: "Page <b>0</b> to <b>0</b>"));
            }

            return calls.UmGo();
        }
        public ActionResult Activate(string optin)
        {
            bool   fail     = false;
            string redirect = string.Empty;

            if (!string.IsNullOrWhiteSpace(optin))
            {
                try
                {
                    Guid recordGuid = new Guid(optin);
                    if (recordGuid != null)
                    {
                        RecordStorage recordStorage = new RecordStorage();
                        FormStorage   formStorage   = new FormStorage();

                        Record record = recordStorage.GetRecordByUniqueId(recordGuid);
                        // get corresponding form for this record
                        Umbraco.Forms.Core.Form form = formStorage.GetForm(record.Form);

                        // - approve this record, so that form approval workflow kicks in!
                        RecordService.Instance.Approve(record, form);

                        // - redirect to target page (if configured)
                        WorkflowStorage workflowStorage = new WorkflowStorage();
                        foreach (var workflow in workflowStorage.GetAllWorkFlows(form))
                        {
                            // - find the FormsExt.Workflows.Redirect workflow item (if added/configured)
                            if (workflow.ExecutesOn == FormState.Approved && workflow.Active && workflow.Type.ToString().Equals("FormsExt.Workflows.Redirect", StringComparison.InvariantCultureIgnoreCase))
                            {
                                // - only act on this workflow step if these settings exist!
                                if (!string.IsNullOrEmpty(workflow.Settings["TargetNode"]))
                                {
                                    int targetnodeId = -1;
                                    int.TryParse(workflow.Settings["TargetNode"], out targetnodeId);

                                    if (targetnodeId != -1)
                                    {
                                        // - read settings
                                        bool appendQuerystringParams = false;
                                        if (workflow.Settings.ContainsKey("AppendQuerystringParams"))
                                        {
                                            bool.TryParse(workflow.Settings["AppendQuerystringParams"], out appendQuerystringParams);
                                        }
                                        bool appendHiddenFields = false;
                                        if (workflow.Settings.ContainsKey("AppendHiddenFields"))
                                        {
                                            bool.TryParse(workflow.Settings["AppendHiddenFields"], out appendHiddenFields);
                                        }

                                        redirect += "?";

                                        // - attach querystring params?
                                        if (appendQuerystringParams)
                                        {
                                            foreach (string param in Request.QueryString.Keys)
                                            {
                                                redirect += param + "=" + Server.UrlEncode(Request.QueryString[param]) + "&";
                                            }
                                        }

                                        // - attach hidden fields?
                                        if (appendHiddenFields)
                                        {
                                            foreach (Guid key in record.RecordFields.Keys)
                                            {
                                                RecordField recfield;
                                                record.RecordFields.TryGetValue(key, out recfield);
                                                if (recfield != null)
                                                {
                                                    foreach (var val in recfield.Values)
                                                    {
                                                        if (recfield.Field.FieldType.Name.Equals("Hidden", StringComparison.InvariantCultureIgnoreCase))
                                                        {
                                                            // - this is a hidden field, add to params
                                                            redirect += recfield.Field.Alias + "=" + Server.UrlEncode(recfield.ValuesAsString()) + "&";
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        // - get page url ("nice url")
                                        string pageurl = Umbraco.TypedContent(targetnodeId).UrlAbsolute();

                                        redirect = redirect.Trim("&");
                                        redirect = pageurl + redirect;

                                        fail = false;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        fail = true;
                    }
                }
                catch (Exception ex)
                {
                    fail = true;
                    LogHelper.WarnWithException(this.GetType(), string.Format("Unable opt-in via '{1}': {0}", ex.Message, Request.QueryString.ToString()), ex);
                }
            }
            else
            {
                fail = true;
                LogHelper.Warn(this.GetType(), string.Format("Unable opt-in via '{1}': No opt-in token given", Request.QueryString.ToString()));
            }

            if (fail)
            {
                string subscribeErrorUrl = System.Configuration.ConfigurationManager.AppSettings["FormsExt:NewsletterSubscribeError"];
                if (!string.IsNullOrWhiteSpace(subscribeErrorUrl))
                {
                    System.Web.HttpContext.Current.Response.Redirect(subscribeErrorUrl, false);
                    return(null);
                }
                else
                {
                    return(Content("<h1>Sorry, that didn't work out.</h1>"));
                }
            }
            else
            {
                // - redirect if URL provided
                if (!string.IsNullOrWhiteSpace(redirect))
                {
                    Response.Redirect(redirect, false);
                    return(null);
                }
                else
                {
                    return(Content("<h1>👍</h1>"));
                }
            }
        }
Пример #29
0
        public void Migrate(string connString)
        {
            var sql = DataLayerHelper.CreateSqlHelper(connString);

            // fix RecordFields where DataType is set to 'String' but data is stored as different type
            FixDataTypes(sql);

            // Migrate PreValue Sources

            var migratedPreValueSourceIds = new HashSet <Guid>();

            using (var mPreValueSourceStorage = new PrevalueSourceStorage(sql))
                using (var preValueSourceStorage = new Forms.Data.Storage.PrevalueSourceStorage())
                {
                    foreach (var mPvs in mPreValueSourceStorage.GetAllPrevalueSources())
                    {
                        if (mPvs.Type != null) // Skip unsupported pre-value source types
                        {
                            var pvs = new Umbraco.Forms.Core.FieldPreValueSource()
                            {
                                Id       = mPvs.Id,
                                Name     = mPvs.Name,
                                Type     = mPvs.Type,
                                Settings = mPvs.Settings
                            };

                            // Important: We need to use the update method, as the insert method would
                            // assign a new GUID as the ID of the pre-value source and thus
                            // break the migration.
                            //
                            // The update method works just as the insert method, with the only difference being that
                            // no ID is assigned and different events are fired.
                            preValueSourceStorage.UpdatePreValueSource(pvs);
                        }
                    }

                    // Get IDs of all pre-value sources in destination environment.
                    migratedPreValueSourceIds.UnionWith(preValueSourceStorage
                                                        .GetAll()
                                                        .Select(pvs => pvs.Id));
                }

            // Migrate Forms

            if (!IgnoreRecords)
            {
                // Fix the UFRecordDataString Value field length to be compatible with the old data.
                FixDataStringLength(sql);
            }

            using (var fs = new FormStorage(sql))
            {
                foreach (var form in fs.GetAllForms(false))
                {
                    var v4Form = new Umbraco.Forms.Core.Form();

                    v4Form.Id   = form.Id;
                    v4Form.Name = form.Name;
                    v4Form.DisableDefaultStylesheet = form.DisableDefaultStylesheet;
                    v4Form.FieldIndicationType      = (FormFieldIndication)System.Enum.Parse(typeof(FormFieldIndication), ((int)form.FieldIndicationType).ToString());
                    v4Form.GoToPageOnSubmit         = form.GoToPageOnSubmit;
                    v4Form.HideFieldValidation      = form.HideFieldValidation;
                    v4Form.Indicator             = form.Indicator;
                    v4Form.InvalidErrorMessage   = form.InvalidErrorMessage;
                    v4Form.ManualApproval        = form.ManualApproval;
                    v4Form.MessageOnSubmit       = form.MessageOnSubmit;
                    v4Form.RequiredErrorMessage  = form.RequiredErrorMessage;
                    v4Form.ShowValidationSummary = form.ShowValidationSummary;
                    v4Form.StoreRecordsLocally   = form.StoreRecordsLocally;
                    v4Form.XPathOnSubmit         = form.XPathOnSubmit;

                    foreach (var page in form.Pages)
                    {
                        var v4Page = new Umbraco.Forms.Core.Page();

                        if (!IgnoreObsoleteProperties)
                        {
                            v4Page.Id   = page.Id;
                            v4Page.Form = v4Form.Id;
                        }
                        v4Page.Caption = page.Caption;


                        foreach (var fieldset in page.FieldSets)
                        {
                            var v4Fieldset = new Umbraco.Forms.Core.FieldSet();
                            v4Fieldset.Id = fieldset.Id;
                            if (!IgnoreObsoleteProperties)
                            {
                                v4Fieldset.Page = v4Page.Id;
                            }
                            v4Fieldset.Caption = fieldset.Caption;

                            var v4Container = new Umbraco.Forms.Core.FieldsetContainer();
                            v4Container.Width = 12;

                            foreach (var field in fieldset.Fields)
                            {
                                var v4Field = new Umbraco.Forms.Core.Field();
                                v4Field.Id                   = field.Id;
                                v4Field.Caption              = field.Caption;
                                v4Field.ToolTip              = field.ToolTip;
                                v4Field.FieldTypeId          = field.FieldTypeId;
                                v4Field.InvalidErrorMessage  = field.InvalidErrorMessage;
                                v4Field.Mandatory            = field.Mandatory;
                                v4Field.RequiredErrorMessage = field.RequiredErrorMessage;
                                v4Field.RegEx                = field.RegEx;

                                using (var pvs = new PreValueStorage(sql))
                                {
                                    var prevalues = new List <string>();
                                    foreach (var prevalue in pvs.GetAllPreValues(field).OrderBy(x => x.SortOrder))
                                    {
                                        prevalues.Add(prevalue.Value);
                                    }
                                    v4Field.PreValues = prevalues;
                                }

                                if (field.PreValueSourceId != Guid.Empty &&
                                    migratedPreValueSourceIds.Contains(field.PreValueSourceId))
                                {
                                    v4Field.PreValueSourceId = field.PreValueSourceId;
                                }

                                v4Field.Condition = new Core.FieldCondition();
                                if (!IgnoreObsoleteProperties)
                                {
                                    v4Field.Condition.Id = field.Condition.Id;
                                }
                                v4Field.Condition.Enabled    = field.Condition.Enabled;
                                v4Field.Condition.ActionType = (Core.FieldConditionActionType)System.Enum.Parse(typeof(Core.FieldConditionActionType), ((int)field.Condition.ActionType).ToString());;
                                v4Field.Condition.LogicType  = (Core.FieldConditionLogicType)System.Enum.Parse(typeof(Core.FieldConditionLogicType), ((int)field.Condition.LogicType).ToString());;

                                var rules = new List <Core.FieldConditionRule>();

                                if (field.Condition.Rules != null)
                                {
                                    foreach (var rule in field.Condition.Rules)
                                    {
                                        var v4Rule = new Core.FieldConditionRule();

                                        if (!IgnoreObsoleteProperties)
                                        {
                                            v4Rule.Id = rule.Id;
                                        }
                                        v4Rule.Field    = rule.Field;
                                        v4Rule.Operator = (Core.FieldConditionRuleOperator)System.Enum.Parse(typeof(Core.FieldConditionRuleOperator), ((int)rule.Operator).ToString());;
                                        v4Rule.Value    = rule.Value;

                                        rules.Add(v4Rule);
                                    }
                                }

                                v4Field.Condition.Rules = rules;

                                using (var ss = new SettingsStorage(sql))
                                {
                                    foreach (var setting in  ss.GetSettingsAsList(field.Id))
                                    {
                                        v4Field.Settings.Add(setting.Key, setting.Value);
                                    }
                                }
                                v4Container.Fields.Add(v4Field);
                            }

                            v4Fieldset.Containers.Add(v4Container);

                            v4Page.FieldSets.Add(v4Fieldset);
                        }

                        v4Form.Pages.Add(v4Page);
                    }

                    using (var s = new Forms.Data.Storage.FormStorage())
                    {
                        v4Form = s.InsertForm(v4Form);

                        v4Form.Created = form.Created;

                        // Note: The form update is also required to work around issue CON-1051
                        // (field aliases are not set in Umbraco Forms below version 4.3.0 when inserting a new form).
                        s.UpdateForm(v4Form);
                    }

                    using (var ws = new WorkflowStorage(sql))
                    {
                        var wfs = ws.GetAllWorkFlows(form);

                        foreach (var workflow in wfs.OrderBy(wf => wf.SortOrder))
                        {
                            using (var wsv4 = new Forms.Data.Storage.WorkflowStorage())
                            {
                                var v4Workflow = new Core.Workflow();
                                v4Workflow.Name       = workflow.Name;
                                v4Workflow.Id         = workflow.Id;
                                v4Workflow.Type       = workflow.Type;
                                v4Workflow.ExecutesOn = (Core.Enums.FormState)System.Enum.Parse(typeof(Core.Enums.FormState), ((int)workflow.ExecutesOn).ToString());
                                v4Workflow.Form       = v4Form.Id;
                                v4Workflow.Settings   = workflow.Settings;
                                wsv4.InsertWorkflow(v4Form, v4Workflow);
                            }
                        }
                    }

                    if (!IgnoreRecords)
                    {
                        // store records
                        using (var rs = new RecordStorage(sql))
                        {
                            var records = rs.GetAllRecords(form);
                            using (var rs4 = new Forms.Data.Storage.RecordStorage())
                            {
                                foreach (var r in records)
                                {
                                    //if (rs4.GetRecordByUniqueId(r.Form) != null)
                                    //{
                                    //    // Don't import it again.
                                    //    continue;
                                    //}

                                    var v4Record = new Core.Record();
                                    v4Record.UniqueId      = r.Id;
                                    v4Record.Form          = v4Form.Id;
                                    v4Record.Created       = r.Created;
                                    v4Record.Updated       = r.Updated;
                                    v4Record.State         = (FormState)r.State;
                                    v4Record.CurrentPage   = r.currentPage;
                                    v4Record.UmbracoPageId = r.umbracoPageId;
                                    v4Record.IP            = r.IP;
                                    v4Record.MemberKey     = r.MemberKey;
                                    // field values - added in this second step as all values are otherwise deleted and reinserted which is SLOW
                                    v4Record.RecordFields = new Dictionary <Guid, Core.RecordField>();
                                    foreach (var kvp in r.RecordFields)
                                    {
                                        var rf = kvp.Value;
                                        v4Record.RecordFields.Add(kvp.Key, new Core.RecordField
                                        {
                                            Key           = rf.Key,
                                            FieldId       = rf.FieldId,
                                            Field         = GetFormField(v4Form, rf.FieldId), // field needs to be set correctly, otherwise UFRecordData doesn't get written
                                            DataType      = (Core.FieldDataType)rf.DataType,
                                            DataTypeAlias = rf.DataTypeAlias,
                                            Values        = rf.Values
                                        });
                                    }
                                    v4Record.RecordData = v4Record.GenerateRecordDataAsJson();

                                    rs4.InsertRecord(v4Record, v4Form);

                                    // reset DateTime fields to original value, InsertRecord sets them to DateTime.Now
                                    v4Record.Created = r.Created;
                                    v4Record.Updated = r.Updated;

                                    // Update the record via the database context as we only want to update two columns
                                    // and the UpdateRecord method of the RecordStorage would delete and re-insert all the record field values.
                                    ApplicationContext.Current.DatabaseContext.Database.Update(v4Record);
                                }
                            }
                        }
                    }
                }
            }
        }
        public HttpResponseMessage CopyByGuid(Guid guid)
        {
            using (FormStorage formStorage = new FormStorage())
            {
                using (WorkflowStorage workflowStorage = new WorkflowStorage())
                {
                    Umbraco.Forms.Core.Form form = formStorage.GetForm(guid);

                    if (form == null)
                        return Request.CreateResponse(HttpStatusCode.NotFound);

                    // Get the corresponding workflows
                    List<Umbraco.Forms.Core.Workflow> workflows = new List<Umbraco.Forms.Core.Workflow>();
                    foreach (var workflowId in form.WorkflowIds)
                    {
                        workflows.Add(workflowStorage.GetWorkflow(workflowId));
                    }

                    // Clone the form, manual copy because the clone function implemented by Umbraco doesn't work (not serializable)
                    var newForm = new Umbraco.Forms.Core.Form();
                    newForm.Pages = form.Pages.ToList();
                    newForm.DataSource = form.DataSource;
                    newForm.DisableDefaultStylesheet = form.DisableDefaultStylesheet;
                    newForm.FieldIndicationType = form.FieldIndicationType;
                    newForm.GoToPageOnSubmit = form.GoToPageOnSubmit;
                    newForm.HideFieldValidation = form.HideFieldValidation;
                    newForm.Indicator = form.Indicator;
                    newForm.InvalidErrorMessage = form.InvalidErrorMessage;
                    newForm.ManualApproval = form.ManualApproval;
                    newForm.MessageOnSubmit = form.MessageOnSubmit;
                    newForm.Name = form.Name + " - copy - " + DateTime.Now.ToString("dd-MM-yyyy HH:mm");
                    newForm.NextLabel = form.NextLabel;
                    newForm.PrevLabel = form.PrevLabel;
                    newForm.RequiredErrorMessage = form.RequiredErrorMessage;
                    newForm.ShowValidationSummary = form.ShowValidationSummary;
                    newForm.StoreRecordsLocally = form.StoreRecordsLocally;
                    newForm.SubmitLabel = form.SubmitLabel;
                    newForm.SupportedDependencies = form.SupportedDependencies;
                    newForm.UseClientDependency = form.UseClientDependency;
                    newForm.WorkflowIds = new List<Guid>();
                    newForm.XPathOnSubmit = form.XPathOnSubmit;
                    newForm.CssClass = form.CssClass;

                    var submittedForm = formStorage.InsertForm(newForm);
                    if (submittedForm != null)
                    {
                        // Clear the default workflowId
                        submittedForm.WorkflowIds = new List<Guid>();
                        // Save
                        formStorage.UpdateForm(submittedForm);

                        // Create copies of the workflows
                        foreach (var workflow in workflows)
                        {
                            var newWorkflow = new Umbraco.Forms.Core.Workflow();
                            newWorkflow.Active = workflow.Active;
                            newWorkflow.ExecutesOn = workflow.ExecutesOn;
                            newWorkflow.Form = submittedForm.Id;
                            newWorkflow.Name = workflow.Name;
                            // Copy so we have no reference! - http://stackoverflow.com/a/8859151/2992405
                            newWorkflow.Settings = new Dictionary<string, string>(workflow.Settings);
                            newWorkflow.SortOrder = workflow.SortOrder;
                            newWorkflow.Type = workflow.Type;
                            newWorkflow.WorkflowTypeId = workflow.WorkflowTypeId;

                            // Save the new workflow
                            workflowStorage.InsertWorkflow(submittedForm, newWorkflow);
                        }

                        // Put the form in the same folder as the original
                        var folder = PerplexFolder.Get(f => f.Forms.Any(formId => formId == guid.ToString()));
                        if (folder != null)
                        {
                            folder.Forms.Add(newForm.Id.ToString());
                            PerplexFolder.SaveAll();

                            // Return the folder so we can expand the tree again
                            return Request.CreateResponse(HttpStatusCode.OK, folder);
                        }

                        return Request.CreateResponse(HttpStatusCode.OK);
                    }


                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }
            }
        }
Пример #31
0
        public BindingList<EventEntry> Search()
        {
            FormStorage<bool> storage = new FormStorage<bool>(false);
            Dictionary<string, string> searchTerms = new Dictionary<string, string>();
            Search search = new Search(searchTerms, typeof(EventEntry), storage);

            search.ShowDialog();

            if (storage.Value && searchTerms.Count != 0)
            {
                BindingList<EventEntry> searchList = new BindingList<EventEntry>();
                foreach(EventEntry entry in _events)
                {
                    searchList.Add(entry);
                }

                foreach (KeyValuePair<string, string> pair in searchTerms)
                {
                    for (int i = 0; i < searchList.Count; i++)
                    {
                        object property = typeof(EventEntry).GetProperty(pair.Value).GetValue(searchList[i]);
                        if (property != null && !property.ToString().Contains(pair.Key))
                        {
                            i--;
                            searchList.Remove(searchList[i + 1]);
                        }
                    }
                }

                return searchList;
            }

            return _events;
        }
Пример #32
0
        private void buttonAddMinor_Click(object sender, EventArgs e)
        {
            FormStorage<string> storage = new FormStorage<string>(string.Empty);
            StudySelector selector = new StudySelector(storage);
            selector.ShowDialog();

            if (storage.Value != string.Empty)
            {
                _tempMinors.Add(storage.Value);
            }
        }
Пример #33
0
        public HttpResponseMessage CopyByGuid(Guid guid)
        {
            using (FormStorage formStorage = new FormStorage())
            {
                using (WorkflowStorage workflowStorage = new WorkflowStorage())
                {
                    Umbraco.Forms.Core.Form form = formStorage.GetForm(guid);

                    if (form == null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound));
                    }

                    // Get the corresponding workflows
                    List <Umbraco.Forms.Core.Workflow> workflows = new List <Umbraco.Forms.Core.Workflow>();
                    foreach (var workflowId in form.WorkflowIds)
                    {
                        workflows.Add(workflowStorage.GetWorkflow(workflowId));
                    }

                    // Clone the form, manual copy because the clone function implemented by Umbraco doesn't work (not serializable)
                    var newForm = new Umbraco.Forms.Core.Form();
                    newForm.Pages      = form.Pages.ToList();
                    newForm.DataSource = form.DataSource;
                    newForm.DisableDefaultStylesheet = form.DisableDefaultStylesheet;
                    newForm.FieldIndicationType      = form.FieldIndicationType;
                    newForm.GoToPageOnSubmit         = form.GoToPageOnSubmit;
                    newForm.HideFieldValidation      = form.HideFieldValidation;
                    newForm.Indicator           = form.Indicator;
                    newForm.InvalidErrorMessage = form.InvalidErrorMessage;
                    newForm.ManualApproval      = form.ManualApproval;
                    newForm.MessageOnSubmit     = form.MessageOnSubmit;
                    newForm.Name                  = form.Name + " - copy - " + DateTime.Now.ToString("dd-MM-yyyy HH:mm");
                    newForm.NextLabel             = form.NextLabel;
                    newForm.PrevLabel             = form.PrevLabel;
                    newForm.RequiredErrorMessage  = form.RequiredErrorMessage;
                    newForm.ShowValidationSummary = form.ShowValidationSummary;
                    newForm.StoreRecordsLocally   = form.StoreRecordsLocally;
                    newForm.SubmitLabel           = form.SubmitLabel;
                    newForm.SupportedDependencies = form.SupportedDependencies;
                    newForm.UseClientDependency   = form.UseClientDependency;
                    newForm.WorkflowIds           = new List <Guid>();
                    newForm.XPathOnSubmit         = form.XPathOnSubmit;
                    newForm.CssClass              = form.CssClass;

                    var submittedForm = formStorage.InsertForm(newForm);
                    if (submittedForm != null)
                    {
                        // Clear the default workflowId
                        submittedForm.WorkflowIds = new List <Guid>();
                        // Save
                        formStorage.UpdateForm(submittedForm);

                        // Create copies of the workflows
                        foreach (var workflow in workflows)
                        {
                            var newWorkflow = new Umbraco.Forms.Core.Workflow();
                            newWorkflow.Active     = workflow.Active;
                            newWorkflow.ExecutesOn = workflow.ExecutesOn;
                            newWorkflow.Form       = submittedForm.Id;
                            newWorkflow.Name       = workflow.Name;
                            // Copy so we have no reference! - http://stackoverflow.com/a/8859151/2992405
                            newWorkflow.Settings       = new Dictionary <string, string>(workflow.Settings);
                            newWorkflow.SortOrder      = workflow.SortOrder;
                            newWorkflow.Type           = workflow.Type;
                            newWorkflow.WorkflowTypeId = workflow.WorkflowTypeId;

                            // Save the new workflow
                            workflowStorage.InsertWorkflow(submittedForm, newWorkflow);
                        }

                        // Put the form in the same folder as the original
                        var folder = PerplexFolder.Get(f => f.Forms.Any(formId => formId == guid.ToString()));
                        if (folder != null)
                        {
                            folder.Forms.Add(newForm.Id.ToString());
                            PerplexFolder.SaveAll();

                            // Return the folder so we can expand the tree again
                            return(Request.CreateResponse(HttpStatusCode.OK, folder));
                        }

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }


                    return(Request.CreateResponse(HttpStatusCode.NotFound));
                }
            }
        }
Пример #34
0
        public static string ListForm()
        {
            FormStorage fs = new FormStorage();
            System.Collections.Generic.List<Umbraco.Forms.Core.Form> forms = fs.GetAllForms();

            List calls = new List();

            foreach (Umbraco.Forms.Core.Form form in forms)
            {
                calls.AddListItem(new ListItem(form.Name,
                subtitle: "Created: " + form.Created.ToString(),
                icon: GenericIcon.FolderClose,
                action: new Call("ListRecord", new string[] { form.Id.ToString(), "1" })));
            }

            return calls.UmGo();
        }
        public void Migrate(string connString)
        {
            var sql = DataLayerHelper.CreateSqlHelper(connString);

            // fix RecordFields where DataType is set to 'String' but data is stored as different type
            FixDataTypes(sql);

            using (var fs = new FormStorage(sql))
            {
                foreach (var form in fs.GetAllForms(false))
                {
                    Umbraco.Forms.Core.Form v4Form;
                    try
                    {
                        // Check for an existing form with that GUID
                        using (var v4Fs = new Umbraco.Forms.Data.Storage.FormStorage())
                            v4Form = v4Fs.GetForm(form.Id);
                    }
                    catch (NullReferenceException)
                    {
                        // Form hasn't been imported, import it now
                        v4Form = new Umbraco.Forms.Core.Form();

                        v4Form.Id   = form.Id;
                        v4Form.Name = form.Name;
                        v4Form.DisableDefaultStylesheet = form.DisableDefaultStylesheet;
                        v4Form.FieldIndicationType      = (FormFieldIndication)System.Enum.Parse(typeof(FormFieldIndication), ((int)form.FieldIndicationType).ToString());
                        v4Form.GoToPageOnSubmit         = form.GoToPageOnSubmit;
                        v4Form.HideFieldValidation      = form.HideFieldValidation;
                        v4Form.Indicator             = form.Indicator;
                        v4Form.InvalidErrorMessage   = form.InvalidErrorMessage;
                        v4Form.ManualApproval        = form.ManualApproval;
                        v4Form.MessageOnSubmit       = form.MessageOnSubmit;
                        v4Form.RequiredErrorMessage  = form.RequiredErrorMessage;
                        v4Form.ShowValidationSummary = form.ShowValidationSummary;
                        v4Form.StoreRecordsLocally   = form.StoreRecordsLocally;
                        v4Form.XPathOnSubmit         = form.XPathOnSubmit;

                        v4Form.NextLabel   = "Next";
                        v4Form.PrevLabel   = "Previous";
                        v4Form.SubmitLabel = "Submit";

                        foreach (var page in form.Pages)
                        {
                            var v4Page = new Umbraco.Forms.Core.Page();

                            v4Page.Caption = page.Caption;


                            foreach (var fieldset in page.FieldSets)
                            {
                                var v4Fieldset = new Umbraco.Forms.Core.FieldSet();
                                v4Fieldset.Caption = fieldset.Caption;

                                var v4Container = new Umbraco.Forms.Core.FieldsetContainer();
                                v4Container.Width = 12;

                                foreach (var field in fieldset.Fields)
                                {
                                    var v4Field = new Umbraco.Forms.Core.Field();
                                    v4Field.Id                   = field.Id;
                                    v4Field.Caption              = field.Caption;
                                    v4Field.ToolTip              = field.ToolTip;
                                    v4Field.FieldTypeId          = field.FieldTypeId;
                                    v4Field.InvalidErrorMessage  = field.InvalidErrorMessage;
                                    v4Field.Mandatory            = field.Mandatory;
                                    v4Field.RequiredErrorMessage = field.RequiredErrorMessage;
                                    v4Field.RegEx                = field.RegEx;

                                    using (var pvs = new PreValueStorage(sql))
                                    {
                                        var prevalues = new List <string>();
                                        foreach (var prevalue in pvs.GetAllPreValues(field).OrderBy(x => x.SortOrder))
                                        {
                                            prevalues.Add(prevalue.Value);
                                        }
                                        v4Field.PreValues = prevalues;
                                    }

                                    v4Field.Condition            = new Core.FieldCondition();
                                    v4Field.Condition.Enabled    = field.Condition.Enabled;
                                    v4Field.Condition.ActionType = (Core.FieldConditionActionType)System.Enum.Parse(typeof(Core.FieldConditionActionType), ((int)field.Condition.ActionType).ToString());;
                                    v4Field.Condition.LogicType  = (Core.FieldConditionLogicType)System.Enum.Parse(typeof(Core.FieldConditionLogicType), ((int)field.Condition.LogicType).ToString());;

                                    var rules = new List <Core.FieldConditionRule>();
                                    foreach (var rule in field.Condition.Rules)
                                    {
                                        var v4Rule = new Core.FieldConditionRule();

                                        v4Rule.Field    = rule.Field;
                                        v4Rule.Operator = (Core.FieldConditionRuleOperator)System.Enum.Parse(typeof(Core.FieldConditionRuleOperator), ((int)rule.Operator).ToString());;
                                        v4Rule.Value    = rule.Value;

                                        rules.Add(v4Rule);
                                    }
                                    v4Field.Condition.Rules = rules;

                                    using (var ss = new SettingsStorage(sql))
                                    {
                                        foreach (var setting in ss.GetSettingsAsList(field.Id))
                                        {
                                            v4Field.Settings.Add(setting.Key, setting.Value);
                                        }
                                    }
                                    v4Container.Fields.Add(v4Field);
                                }

                                v4Fieldset.Containers.Add(v4Container);

                                v4Page.FieldSets.Add(v4Fieldset);
                            }

                            v4Form.Pages.Add(v4Page);
                        }

                        using (var s = new Forms.Data.Storage.FormStorage())
                        {
                            v4Form = s.InsertForm(v4Form);
                        }

                        using (var ws = new WorkflowStorage(sql))
                        {
                            var wfs = ws.GetAllWorkFlows(form);

                            foreach (var workflow in wfs)
                            {
                                using (var wsv4 = new Forms.Data.Storage.WorkflowStorage())
                                {
                                    var v4Workflow = new Core.Workflow();
                                    v4Workflow.Name       = workflow.Name;
                                    v4Workflow.Id         = workflow.Id;
                                    v4Workflow.Type       = workflow.Type;
                                    v4Workflow.ExecutesOn = (Core.Enums.FormState)System.Enum.Parse(typeof(Core.Enums.FormState), ((int)workflow.ExecutesOn).ToString());
                                    v4Workflow.Form       = v4Form.Id;
                                    v4Workflow.Settings   = workflow.Settings;
                                    wsv4.InsertWorkflow(v4Form, v4Workflow);
                                }
                            }
                        }
                    }

                    if (IgnoreRecords)
                    {
                        continue;
                    }

                    // If we're importing data, this could take a while...
                    HttpContext.Current.Server.ScriptTimeout = 90000;

                    // Fix the UFRecordDataString Value field length to be compatible with the old data.
                    FixDataStringLength(sql);

                    // store records
                    using (var rs = new RecordStorage(sql))
                    {
                        var records = rs.GetAllRecords(form);
                        using (var rs4 = new Forms.Data.Storage.RecordStorage())
                        {
                            foreach (var r in records)
                            {
                                if (rs4.GetRecordByUniqueId(r.Id) != null)
                                {
                                    // Don't import it again.
                                    continue;
                                }

                                var v4Record = new Core.Record();
                                v4Record.Form          = v4Form.Id;
                                v4Record.Created       = r.Created;
                                v4Record.Updated       = r.Updated;
                                v4Record.State         = (FormState)r.State;
                                v4Record.CurrentPage   = r.currentPage;
                                v4Record.UmbracoPageId = r.umbracoPageId;
                                v4Record.IP            = r.IP;
                                v4Record.MemberKey     = r.MemberKey;
                                // field values - added in this second step as all values are otherwise deleted and reinserted which is SLOW
                                v4Record.RecordFields = new Dictionary <Guid, Core.RecordField>();
                                foreach (var kvp in r.RecordFields)
                                {
                                    var rf = kvp.Value;
                                    v4Record.RecordFields.Add(kvp.Key, new Core.RecordField
                                    {
                                        Key           = rf.Key,
                                        FieldId       = rf.FieldId,
                                        Field         = GetFormField(v4Form, rf.FieldId), // field needs to be set correctly, otherwise UFRecordData doesn't get written
                                        DataType      = (Core.FieldDataType)rf.DataType,
                                        DataTypeAlias = rf.DataTypeAlias,
                                        Values        = rf.Values
                                    });
                                }
                                v4Record.RecordData = v4Record.GenerateRecordDataAsJson();

                                rs4.InsertRecord(v4Record, v4Form);

                                // reset DateTime fields to original value, InsertRecord sets them to DateTime.Now
                                v4Record.Created = r.Created;
                                v4Record.Updated = r.Updated;

                                rs4.UpdateRecord(v4Record, v4Form);
                            }
                        }
                    }
                }
            }
        }
Пример #36
0
        public static string ViewData(String recordId)
        {
            FormStorage fs = new FormStorage();
            RecordStorage rs = new RecordStorage();

            Record record = rs.GetRecord(Guid.Parse(recordId));

            Umbraco.Forms.Core.Form form = fs.GetForm(record.Form);

            List calls = new List();

            calls.AddListItem(new ListItem("<b>Approve</b>",
                subtitle: "Approve record",
                icon: GenericIcon.Check,
                action: new Call("CheckRecordConfirm", new string[] { recordId })));

            calls.AddListItem(new ListItem("<b>Delete</b>",
                subtitle: "Delete record",
                icon: GenericIcon.Trash,
                action: new Call("DeleteRecordConfirm", new string[] { recordId })));

            calls.AddListItem(new ListItem("<b>Email</b>",
                subtitle: "Email record",
                icon: GenericIcon.EnvelopeAlt,
                action: new Call("EmailRecordForm", new string[] { recordId })));

            String data = string.Empty;

            data += "<p><b>State:</b><br/>" + record.State.ToString() + "</p><br />";
            data += "<p><b>Created:</b><br/>" + record.Created.ToString() + "</p><br />";
            data += "<p><b>Ip:</b><br/>" + record.IP + "</p><br />";

            foreach (Field field in form.AllFields)
            {
                string value = string.Empty;
                if (record.GetRecordField(field.Id) != null && record.GetRecordField(field.Id).Values.Count > 0)
                {
                    value = record.GetRecordField(field.Id).Values[0].ToString();
                }
                data += "<p><b>" + field.Caption + ":</b><br/>" + value + "</p><br />";
            }

            calls.AddListItem(new ListItem("<b>Record</b><br/><br />",
                subtitle: data));

            return calls.UmGo();
        }
Пример #37
0
        public void Migrate(string connString)
        {
            var sql = DataLayerHelper.CreateSqlHelper(connString);

            using (var fs = new FormStorage(sql))
            {
                foreach (var form in fs.GetAllForms(false))
                {
                    var v4Form = new Umbraco.Forms.Core.Form();

                    v4Form.Id   = form.Id;
                    v4Form.Name = form.Name;
                    v4Form.DisableDefaultStylesheet = form.DisableDefaultStylesheet;
                    v4Form.FieldIndicationType      = (FormFieldIndication)System.Enum.Parse(typeof(FormFieldIndication), ((int)form.FieldIndicationType).ToString());;
                    v4Form.GoToPageOnSubmit         = form.GoToPageOnSubmit;
                    v4Form.HideFieldValidation      = form.HideFieldValidation;
                    v4Form.Indicator             = form.Indicator;
                    v4Form.InvalidErrorMessage   = form.InvalidErrorMessage;
                    v4Form.ManualApproval        = form.ManualApproval;
                    v4Form.MessageOnSubmit       = form.MessageOnSubmit;
                    v4Form.RequiredErrorMessage  = form.RequiredErrorMessage;
                    v4Form.ShowValidationSummary = form.ShowValidationSummary;
                    v4Form.StoreRecordsLocally   = form.StoreRecordsLocally;
                    v4Form.XPathOnSubmit         = form.XPathOnSubmit;

                    v4Form.NextLabel   = "Next";
                    v4Form.PrevLabel   = "Previous";
                    v4Form.SubmitLabel = "Submit";

                    foreach (var page in form.Pages)
                    {
                        var v4Page = new Umbraco.Forms.Core.Page();

                        v4Page.Caption = page.Caption;


                        foreach (var fieldset in page.FieldSets)
                        {
                            var v4Fieldset = new Umbraco.Forms.Core.FieldSet();
                            v4Fieldset.Caption = fieldset.Caption;

                            var v4Container = new Umbraco.Forms.Core.FieldsetContainer();
                            v4Container.Width = 12;

                            foreach (var field in fieldset.Fields)
                            {
                                var v4Field = new Umbraco.Forms.Core.Field();
                                v4Field.Id                   = field.Id;
                                v4Field.Caption              = field.Caption;
                                v4Field.ToolTip              = field.ToolTip;
                                v4Field.FieldTypeId          = field.FieldTypeId;
                                v4Field.InvalidErrorMessage  = field.InvalidErrorMessage;
                                v4Field.Mandatory            = field.Mandatory;
                                v4Field.RequiredErrorMessage = field.RequiredErrorMessage;
                                v4Field.RegEx                = field.RegEx;

                                using (var pvs = new PreValueStorage(sql))
                                {
                                    var prevalues = new List <string>();
                                    foreach (var prevalue in pvs.GetAllPreValues(field).OrderBy(x => x.SortOrder))
                                    {
                                        prevalues.Add(prevalue.Value);
                                    }
                                    v4Field.PreValues = prevalues;
                                }

                                v4Field.Condition            = new Core.FieldCondition();
                                v4Field.Condition.Enabled    = field.Condition.Enabled;
                                v4Field.Condition.ActionType = (Core.FieldConditionActionType)System.Enum.Parse(typeof(Core.FieldConditionActionType), ((int)field.Condition.ActionType).ToString());;
                                v4Field.Condition.LogicType  = (Core.FieldConditionLogicType)System.Enum.Parse(typeof(Core.FieldConditionLogicType), ((int)field.Condition.LogicType).ToString());;

                                var rules = new List <Core.FieldConditionRule>();
                                foreach (var rule in field.Condition.Rules)
                                {
                                    var v4Rule = new Core.FieldConditionRule();

                                    v4Rule.Field    = rule.Field;
                                    v4Rule.Operator = (Core.FieldConditionRuleOperator)System.Enum.Parse(typeof(Core.FieldConditionRuleOperator), ((int)rule.Operator).ToString());;
                                    v4Rule.Value    = rule.Value;

                                    rules.Add(v4Rule);
                                }
                                v4Field.Condition.Rules = rules;

                                using (var ss = new SettingsStorage(sql))
                                {
                                    foreach (var setting in  ss.GetSettingsAsList(field.Id))
                                    {
                                        v4Field.Settings.Add(setting.Key, setting.Value);
                                    }
                                }
                                v4Container.Fields.Add(v4Field);
                            }

                            v4Fieldset.Containers.Add(v4Container);

                            v4Page.FieldSets.Add(v4Fieldset);
                        }

                        v4Form.Pages.Add(v4Page);
                    }

                    using (var ws = new WorkflowStorage(sql))
                    {
                        var wfs = ws.GetAllWorkFlows(form);

                        foreach (var workflow in wfs)
                        {
                            using (var wsv4 = new Forms.Data.Storage.WorkflowStorage())
                            {
                                var v4Workflow = new Core.Workflow();
                                v4Workflow.Name       = workflow.Name;
                                v4Workflow.Id         = workflow.Id;
                                v4Workflow.Type       = workflow.Type;
                                v4Workflow.ExecutesOn = (Core.Enums.FormState)System.Enum.Parse(typeof(Core.Enums.FormState), ((int)workflow.ExecutesOn).ToString());;;
                                v4Workflow.Settings   = workflow.Settings;
                                wsv4.InsertWorkflow(v4Form, v4Workflow);
                            }
                        }
                    }


                    using (var s = new Forms.Data.Storage.FormStorage()) {
                        s.InsertForm(v4Form);
                    }
                }
            }
        }