Exemplo n.º 1
0
        public void TestCreateNewPersist()
        {
            var customData = new byte[4096 * 16 + 27];
            var rnd        = new Random();

            for (var i = 0; i < customData.Length; i++)
            {
                customData[i] = (byte)rnd.Next(0, 256);
            }

            using (var ms = new MemoryStream())
            {
                var recordStorage = new RecordStorage(new BlockStorage(ms));
                var recordId      = recordStorage.Create(customData);

                // First record, shoud has id of 1..
                Assert.AreEqual(1, recordId);

                // Test read back the data
                Assert.True(customData.SequenceEqual(recordStorage.Find(1)));

                // Now test persistant
                var recordStorage2 = new RecordStorage(new BlockStorage(ms));
                Assert.True(customData.SequenceEqual(recordStorage2.Find(1)));
            }
        }
Exemplo n.º 2
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;
        }
Exemplo n.º 3
0
        /// <summary>
        /// </summary>
        /// <param name="pathToDb">Path to cow db.</param>
        public MapDatabase(string pathToDb)
        {
            if (pathToDb == null)
            {
                throw new ArgumentNullException("pathToDb");
            }

            // As soon as CowDatabase is constructed, open the steam to talk to the underlying files
            this.mainDatabaseFile   = new FileStream(pathToDb, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, Block.Size);
            this.primaryIndexFile   = new FileStream(pathToDb + ".pidx", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, Block.Size);
            this.secondaryIndexFile = new FileStream(pathToDb + ".sidx", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, Block.Size);

            // Construct the RecordStorage that use to store main cow data
            this.records = new RecordStorage(new BlockStorage(this.mainDatabaseFile, Block.Size, 48));

            // Construct the primary and secondary indexes
            this.primaryIndex = new Tree <Guid, uint>(
                new TreeDiskNodeManager <Guid, uint>(
                    new GuidSerializer(),
                    new TreeUIntSerializer(),
                    new RecordStorage(new BlockStorage(this.primaryIndexFile, Block.Size))
                    ),
                false
                );

            this.secondaryIndex = new Tree <Tuple <string, int>, uint>(
                new TreeDiskNodeManager <Tuple <string, int>, uint>(
                    new StringIntSerializer(),
                    new TreeUIntSerializer(),
                    new RecordStorage(new BlockStorage(this.secondaryIndexFile, Block.Size))
                    ),
                true
                );
        }
        public void DeleteEntry(Guid entryId)
        {
            try
            {
                using (var recordStorage = new RecordStorage())
                {
                    var record = recordStorage.GetRecordByUniqueId(entryId);
                    if (record == null)
                    {
                        return;
                    }

                    var form = record.GetForm();
                    if (form == null)
                    {
                        return;
                    }

                    LogHelper.Info <UmbracoFormsRetentionApiController>($"Deleting record '{record.UniqueId}' for form '{form.Name}' with id '{form.Id}'.");
                    recordStorage.DeleteRecord(record, form);
                }
            }
            catch (Exception exception)
            {
                LogHelper.Error <UmbracoFormsRetentionApiController>(exception.Message, exception);
                throw;
            }
        }
Exemplo n.º 5
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;
        }
Exemplo n.º 6
0
        protected override void OnDisappearing()
        {
            Model.End();
            RecordStorage.SaveLocalData();
            var page = new QuizResultPage(new QuizResultViewModel(Model));

            NavigationPage.SetHasNavigationBar(page, false);
            Navigation.PushAsync(page);
            base.OnDisappearing();
        }
Exemplo n.º 7
0
        public void TestTrackingOfLargeFreeBlockList()
        {
            var tmp = Path.Combine(System.IO.Path.GetTempPath(), "data.bin");

            try
            {
                using (var ms = new FileStream(tmp, FileMode.Create))
                {
                    var recordStorage = new RecordStorage(new BlockStorage(ms));

                    // Create 10,000 records
                    var ids = new Dictionary <uint, bool>();
                    for (var i = 0; i < 15342; i++)
                    {
                        ids.Add(recordStorage.Create(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }), true);
                    }

                    // Now delete them all
                    foreach (var kv in ids)
                    {
                        recordStorage.Delete(kv.Key);
                    }

                    // Create records and make sure they reuse these ids,
                    // And make use it reuses the second block (15343) of free block tracking record as well
                    var reusedSecondFreeBlockTracker = false;
                    for (var i = 15342; i >= 0; i--)
                    {
                        var id = recordStorage.Create(new byte[] { 0x00, 0x01, 0x02, 0x03 });
                        if (id == 15343)
                        {
                            reusedSecondFreeBlockTracker = true;
                        }
                        else
                        {
                            Assert.IsTrue(ids.ContainsKey(id));
                        }
                    }

                    Assert.True(reusedSecondFreeBlockTracker);

                    // Make sure it still continue increment the id..
                    Assert.AreEqual(15344, recordStorage.Create(new byte[] { 0x00, 0x01, 0x02, 0x03 }));
                }
            }
            finally
            {
                if (File.Exists(tmp))
                {
                    File.Delete(tmp);
                    Console.WriteLine("Deleted: " + tmp);
                }
            }
        }
        /// <summary>
        /// Called bu Umbraco Forms to execute the workflow.
        /// </summary>
        /// <param name="record">The record.</param>
        /// <param name="e">The <see cref="RecordEventArgs"/> instance containing the event data.</param>
        /// <returns></returns>
        public override WorkflowExecutionStatus Execute(Record record, RecordEventArgs e)
        {
            try
            {
                if (record == null)
                {
                    return(WorkflowExecutionStatus.Failed);
                }

                if (e == null)
                {
                    return(WorkflowExecutionStatus.Failed);
                }

                // Look for a field with the well-known alias "formEntryID" and insert the unique ids in it
                var updateRecord = false;
                foreach (var field in record.RecordFields)
                {
                    if (field.Value.Alias.ToUpperInvariant() == "FORMENTRYID")
                    {
                        field.Value.Values.Clear();
                        field.Value.Values.Add(e.Form.Id.ToString());
                        field.Value.Values.Add(record.UniqueId.ToString());
                        updateRecord = true;
                        break;
                    }
                }

                // Update the record with the id
                if (updateRecord)
                {
                    using (RecordStorage recordStorage = new RecordStorage())
                    {
                        // (note recordStorage.UpdateRecord() doesn't work for the first workflow - see http://issues.umbraco.org/issue/CON-1482)
                        record.RecordData = record.GenerateRecordDataAsJson();
                        if (record.Id > 0)
                        {
                            record = recordStorage.UpdateRecord(record, e.Form);
                        }
                        else
                        {
                            record = recordStorage.InsertRecord(record, e.Form);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                LogHelper.Error <SaveIdAsFieldWorkflow>(exception.Message, exception);
                return(WorkflowExecutionStatus.Failed);
            }
            return(WorkflowExecutionStatus.Completed);
        }
Exemplo n.º 9
0
        public void TestDeletion()
        {
            var d1 = GenerateRandomData(1029);
            var d2 = GenerateRandomData(14 * 1024 * 4);
            var d3 = GenerateRandomData(3591);

            var d4 = GenerateRandomData(4444);
            var d5 = GenerateRandomData(5555);
            var d6 = GenerateRandomData(6666);

            using (var ms = new MemoryStream())
            {
                var recordStorage = new RecordStorage(new BlockStorage(ms));
                var r1            = recordStorage.Create(d1);
                var r2            = recordStorage.Create(d2);
                var r3            = recordStorage.Create(d3);

                Assert.AreEqual(1, r1);
                Assert.AreEqual(2, r2);
                Assert.AreEqual(4, r3);

                Assert.True(recordStorage.Find(r1).SequenceEqual(d1));
                Assert.True(recordStorage.Find(r2).SequenceEqual(d2));
                Assert.True(recordStorage.Find(r3).SequenceEqual(d3));

                // Delete off 2, free 2 records
                recordStorage.Delete(r2);

                Assert.True(recordStorage.Find(r2) == null);

                // INsert 2 new records, should take id of 2,3,4
                var r4 = recordStorage.Create(d4);
                var r5 = recordStorage.Create(d5);
                var r6 = recordStorage.Create(d6);
                Assert.AreEqual(3, r4);
                Assert.AreEqual(2, r5);
                Assert.AreEqual(5, r6);

                // Check that data is not being corrupted if we use the reusable block
                Assert.True(recordStorage.Find(r4).SequenceEqual(d4));
                Assert.True(recordStorage.Find(r5).SequenceEqual(d5));
                Assert.True(recordStorage.Find(r6).SequenceEqual(d6));

                // Test persistance
                var recordStorage2 = new RecordStorage(new BlockStorage(ms));
                Assert.True(recordStorage2.Find(r1).SequenceEqual(d1));
                Assert.True(recordStorage2.Find(r3).SequenceEqual(d3));
                Assert.True(recordStorage2.Find(r4).SequenceEqual(d4));
                Assert.True(recordStorage2.Find(r5).SequenceEqual(d5));
                Assert.True(recordStorage2.Find(r6).SequenceEqual(d6));
            }
        }
        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());
                }
            }
        }
Exemplo n.º 11
0
        public void TestUpdateBlockToMuchBiggerSize()
        {
            var recordStorage = new RecordStorage(new BlockStorage(new MemoryStream(), 8192, 48));
            var x1            = UnitTestHelper.RandomData(2491);
            var x2            = UnitTestHelper.RandomData(9182);
            var x3            = UnitTestHelper.RandomData(5182);

            recordStorage.Create(x1);                            // Use 1 block
            recordStorage.Create(x2);                            // Use 2 blocks
            recordStorage.Create(x3);                            // Use 1 block

            var x2u = UnitTestHelper.RandomData(8192 * 11 + 19); // Use 12 blocks

            recordStorage.Update(2, x2u);

            Assert.IsTrue(recordStorage.Find(1).SequenceEqual(x1));
            Assert.IsTrue(recordStorage.Find(2).SequenceEqual(x2u));
            Assert.IsTrue(recordStorage.Find(4).SequenceEqual(x3));
        }
        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);
                    }
                }
            }
        }
Exemplo n.º 13
0
        public static string CheckRecord(String recordId)
        {
            try
            {
                RecordStorage rs = new RecordStorage();
                Record record = rs.GetRecord(Guid.Parse(recordId));
                RecordService s = new RecordService(record);
                s.Approve();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("This license is invalid"))
                    return new MessageBox("Record approved successfully", new Button("Ok", new Call("ViewData", new string[] { recordId }))).UmGo();
                else
                    return new MessageBox("Error to approved this record", new Button("Close")).UmGo("Warning");
            }

            return new MessageBox("Record approved successfully", new Button("Ok", new Call("ViewData", new string[] { recordId })))
                .UmGo();
        }
Exemplo n.º 14
0
        public void TestUpdateBlockToSmallerSize()
        {
            var recordStorage = new RecordStorage(new BlockStorage(new MemoryStream(), 8192, 48));
            var x1            = UnitTestHelper.RandomData(2491);
            var x2            = UnitTestHelper.RandomData(9182);
            var x3            = UnitTestHelper.RandomData(5182);

            recordStorage.Create(x1);                  // Use 1 block
            recordStorage.Create(x2);                  // Use 2 blocks
            recordStorage.Create(x3);                  // Use 1 block

            var x2u = UnitTestHelper.RandomData(1177); // Use 1 block, so this record should be truncated

            recordStorage.Update(2, x2u);

            Assert.IsTrue(recordStorage.Find(1).SequenceEqual(x1));
            Assert.IsTrue(recordStorage.Find(2).SequenceEqual(x2u));
            Assert.IsTrue(recordStorage.Find(4).SequenceEqual(x3));

            Assert.IsTrue(recordStorage.Create(UnitTestHelper.RandomData(10)) == 3); // Check if block #3 being reused
        }
        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;
        }
Exemplo n.º 16
0
        public IRecordStorage LoadTodoStorage(TransactionDownloadData <Transaction> transactionDownload)
        {
            try
            {
                var data = transactionDownload.GetDecryptedData("todo");
                if (data != null)
                {
                    using (var unpacker = new Unpacker(data))
                    {
                        var recordType = (TodoRecordTypes)RecordStorage.ReadRecordType(unpacker);

                        Type type = null;
                        if (recordType == TodoRecordTypes.ListName)
                        {
                            type = typeof(TodoRecordStorage <TodoListNameRecord>);
                        }
                        else if (recordType == TodoRecordTypes.Task)
                        {
                            type = typeof(TodoRecordStorage <TodoTaskRecord>);
                        }
                        else if (recordType == TodoRecordTypes.TaskStatus)
                        {
                            type = typeof(TodoRecordStorage <TodoTaskStatusRecord>);
                        }

                        if (type != null)
                        {
                            return((IRecordStorage)Activator.CreateInstance(type, unpacker));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.IgnoreException(ex);
            }

            return(null);
        }
Exemplo n.º 17
0
        public DocumentDatabase(IndexModel indexModel)
        {
            var path = $"{AppDomain.CurrentDomain.BaseDirectory}data/{indexModel.DatabaseName}";

            FileOperations.CheckOrCreateDirectory(path);
            path         += $"/{indexModel.IndexName}";
            _dbFileStream = new FileStream(path + ".col", FileMode.OpenOrCreate, FileAccess.ReadWrite,
                                           FileShare.None, 4096);
            _indexFileStream = new FileStream(path + ".pidx", FileMode.OpenOrCreate, FileAccess.ReadWrite,
                                              FileShare.None, 4096);
            _secondaryFileStream = new FileStream(path + ".sidx", FileMode.OpenOrCreate, FileAccess.ReadWrite,
                                                  FileShare.None, 4096);

            // Construct the RecordStorage that use to store main cow data
            _records = new RecordStorage(new BlockStorage(_dbFileStream, 4096));

            // Construct the primary and secondary indexes
            _index = new Tree <Guid, uint>(
                new TreeDiskNodeManager <Guid, uint>(
                    new GuidSerializer(),
                    new TreeUIntSerializer(),
                    new RecordStorage(new BlockStorage(_indexFileStream, 4096))
                    )
                );

            _secondaryIndex = new Tree <string, Dictionary <string, Guid> >(
                new TreeDiskNodeManager <string, Dictionary <string, Guid> >(
                    new StringSerializer(),
                    new DictSerializer(),
                    new RecordStorage(
                        new BlockStorage(_secondaryFileStream, 4096)
                        )
                    ),
                true);

            _documentSerializer = new DocumentSerializer();
            _indexingOperations = new IndexingOperations();
            IndexModel          = indexModel;
        }
 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;
     }
 }
        public DateTime?RetentionDate(Guid entryId)
        {
            try
            {
                using (var recordStorage = new RecordStorage())
                {
                    var record = recordStorage.GetRecordByUniqueId(entryId);
                    if (record == null)
                    {
                        return(null);
                    }

                    foreach (var field in record.RecordFields)
                    {
                        if (field.Value.Alias == "deleteAfter")
                        {
                            if (field.Value.HasValue() && !String.IsNullOrEmpty(field.Value.ValuesAsString()))
                            {
                                DateTime retentionDate;
                                if (DateTime.TryParse(field.Value.ValuesAsString(), out retentionDate))
                                {
                                    return(retentionDate);
                                }
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                LogHelper.Error <UmbracoFormsRetentionApiController>(exception.Message, exception);
                throw;
            }
            return(null);
        }
        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);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 21
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();
        }
Exemplo n.º 22
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();
        }
Exemplo n.º 23
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();
        }
Exemplo n.º 24
0
        public static string DeleteRecord(String recordId)
        {
            string formGuid = null;

            try
            {
                RecordStorage rs = new RecordStorage();
                Record record = rs.GetRecord(Guid.Parse(recordId));
                RecordService s = new RecordService(record);
                formGuid = record.Form.ToString();
                s.Delete();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("This license is invalid"))
                    return new MessageBox("Record deleted successfully", new Button("Ok", new Call("ListRecord", new string[] { formGuid, "1" }))).UmGo();
                else
                    return new MessageBox("Error to delete this record", new Button("Close")).UmGo("Warning");
            }

            return new MessageBox("Record deleted successfully", new Button("Ok", new Call("ListRecord", new string[] { formGuid, "1" })))
                .UmGo();
        }
		/// <summary>
		/// Stores a form record.
		/// </summary>
		/// <param name="form">The form to store a record to.</param>
		/// <param name="fieldValues">The field values to store.</param>
		/// <param name="ipAddress">The user's IP address.</param>
		/// <param name="pageId">The current page ID.</param>
		/// <param name="recordId">Outputs the ID of the record stored to Contour.</param>
		/// <returns>True, if the record was stored; otherwise, false.</returns>
		private static bool StoreRecord(Form form, Dictionary<string, List<object>> fieldValues,
			string ipAddress, int pageId, out Guid recordId) {
			using (var recordStorage = new RecordStorage())
			using (var recordService = new RecordService(form)) {

				// Open record service.
				recordService.Open();

				// Create record.
				var record = recordService.Record;
				record.IP = ipAddress;
				record.UmbracoPageId = pageId;
				record = recordStorage.InsertRecord(record, form);

				// Assign field values for record.
				foreach (var field in recordService.Form.AllFields) {

					// Check which field this is.
					var knownField = false;
					var values = default(List<object>);
					if (fieldValues.TryGetValue((field.Caption ?? string.Empty).ToLower(), out values)) {
						knownField = true;
					}

					// If the field is one of those that are known, store it.
					if (knownField && values != null && values.Any(x => x != null)) {

						// Create field.
						var key = Guid.NewGuid();
						var recordField = new RecordField {
							Field = field,
							Key = key,
							Record = record.Id,
							Values = values
						};

						// Store field.
						using (var recordFieldStorage = new RecordFieldStorage()) {
							recordFieldStorage.InsertRecordField(recordField);
						}

						// Add field to record.
						record.RecordFields.Add(key, recordField);

					}

				}

				// Submit / save record.
				recordService.Submit();
				var result = recordService.SaveFormToRecord();
				recordId = record.Id;
				return result;

			}
		}
Exemplo n.º 26
0
        /// <summary>
        /// Called bu Umbraco Forms to execute the workflow.
        /// </summary>
        /// <param name="record">The record.</param>
        /// <param name="e">The <see cref="RecordEventArgs"/> instance containing the event data.</param>
        /// <returns></returns>
        public override WorkflowExecutionStatus Execute(Record record, RecordEventArgs e)
        {
            try
            {
                if (record == null)
                {
                    return(WorkflowExecutionStatus.Failed);
                }

                if (e == null)
                {
                    return(WorkflowExecutionStatus.Failed);
                }

                List <Exception> settingsErrors = this.ValidateSettings();
                if (settingsErrors != null && Enumerable.Any <Exception>(settingsErrors))
                {
                    foreach (Exception exception in settingsErrors)
                    {
                        LogHelper.Error <RetentionAfterSetDateWorkflow>(exception.Message, exception);
                    }
                    return(WorkflowExecutionStatus.Failed);
                }

                var days = 0;
                int.TryParse(Days, out days);

                var weeks = 0;
                int.TryParse(Weeks, out weeks);

                var months = 0;
                int.TryParse(Months, out months);

                var years = 0;
                int.TryParse(Years, out years);

                // Look for a field with the well-known alias "deleteAfter" and insert a retention date in it
                var updateRecord = false;
                foreach (var field in record.RecordFields)
                {
                    if (field.Value.Alias.ToUpperInvariant() == "DELETEAFTER")
                    {
                        field.Value.Values.Clear();
                        field.Value.Values.Add(DateTime.Today.AddDays(days).AddDays(weeks * 7).AddMonths(months).AddYears(years).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
                        updateRecord = true;
                        break;
                    }
                }

                // Update the record with the retention date
                if (updateRecord)
                {
                    using (RecordStorage recordStorage = new RecordStorage())
                    {
                        // (note recordStorage.UpdateRecord() doesn't work for the first workflow - see http://issues.umbraco.org/issue/CON-1482)
                        record.RecordData = record.GenerateRecordDataAsJson();
                        if (record.Id > 0)
                        {
                            record = recordStorage.UpdateRecord(record, e.Form);
                        }
                        else
                        {
                            record = recordStorage.InsertRecord(record, e.Form);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                LogHelper.Error <RetentionAfterSetDateWorkflow>(exception.Message, exception);
                return(WorkflowExecutionStatus.Failed);
            }
            return(WorkflowExecutionStatus.Completed);
        }
        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>"));
                }
            }
        }
Exemplo n.º 28
0
        protected override bool OnBackButtonPressed()
        {
            RecordStorage.SaveLocalData();

            return(base.OnBackButtonPressed());
        }
Exemplo n.º 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);
                                }
                            }
                        }
                    }
                }
            }
        }