public DataCreateModel CreateModel(NameValueCollection formValues, object files, Operation operation)
        {
            CultureInfo culture = CultureInfo.CreateSpecificCulture("da-DK");

            char[] trim = new char[] { '\"' };
            DataViewModel model = new DataViewModel();
            foreach (string key in formValues.Keys)
            {
                if (formValues[key].ToLower() != "null")
                {
                    switch (key)
                    {
                        case "FormId":
                            int formid = 0;
                            if (int.TryParse(formValues[key], out formid))
                            {
                                DatabaseFormsEntities db = new DatabaseFormsEntities();
                                model.Form = db.Forms.SingleOrDefault(m => m.FormId == formid);
                            }
                            break;
                        case "ViewId":
                            int viewid = 0;
                            if (int.TryParse(formValues[key], out viewid))
                            {
                                RepositoryViews repository = new RepositoryViews();
                                model.View = repository.Get(viewid);
                            }
                            break;
                        case "UniqueId":
                            model.UniqueId = formValues[key];
                            break;
                        case "UserId":
                            model.UserId = formValues[key];
                            break;
                        case "ItemId":
                            int itemid = 0;
                            if (int.TryParse(formValues[key], out itemid))
                            {
                                model.ItemId = itemid;
                            }
                            break;
                        case "Date":
                            DateTime date = DateTime.Now;
                            if (DateTime.TryParse(formValues[key], culture, DateTimeStyles.AssumeLocal, out date))
                            {
                                model.Date = date;
                            }
                            break;

                    }
                }
            }
            if (operation == Operation.Create)
            {
                model.Date = DateTime.Now;
                model.UniqueId = Guid.NewGuid().ToString();
                /*if (User.Identity.IsAuthenticated)
                {
                    model.UserName = User.Identity.Name;
                    model.UserId = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();
                }*/
            }
            if (!String.IsNullOrEmpty(model.UserName))
            {
                UserProfile profile = UserProfile.GetUserProfile(model.UserName);
                RepositoryCompanies rc = new RepositoryCompanies();
                Company company = rc.Get(profile.CompanyId);
                if (company != null)
                    model.Company = company.Name;
            }

            List<DataEmailModel> emails = new List<DataEmailModel>();
            if (!String.IsNullOrEmpty(model.Form.Email))
            {
                if (operation == Operation.Create && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnCreate))
                {
                    emails.Add(new DataEmailModel { Email = model.Form.Email, View = model.Form.ViewEmailToReceiverOnCreate });
                }
                else if (operation == Operation.Edit && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnEdit))
                {
                    emails.Add(new DataEmailModel { Email = model.Form.Email, View = model.Form.ViewEmailToReceiverOnEdit });
                }
            }
            foreach (Field field in model.Form.Fields)
            {
                if (!string.IsNullOrEmpty(field.FieldColumn))
                {
                    #region 8 Upload
                    if (field.FieldTypeId == 8) //Upload
                    {
                        bool fundet = false;
                        if (files!=null && files is System.Collections.ObjectModel.Collection<MultipartFileData>)
                        {
                            foreach (MultipartFileData file in (System.Collections.ObjectModel.Collection<MultipartFileData>)files)
                            {

                                string id = file.Headers.ContentDisposition.Name.Trim(trim);

                                int id2 = 0;
                                if (int.TryParse(id, out id2))
                                {
                                    if (field.FieldId == id2)
                                    {

                                        string filename = file.Headers.ContentDisposition.FileName.Trim(trim);
                                        if (!string.IsNullOrEmpty(filename))
                                        {
                                            fundet = true;
                                            string name = model.UniqueId + "-" + field.FieldId.ToString() + Path.GetExtension(filename).ToLower();
                                            string filePath = Path.Combine(model.Form.UploadPhysicalPath, name);
                                            field.Data = name;

                                            int width = Properties.Settings.Default.MaxWidth;
                                            int height = Properties.Settings.Default.MaxHeight;
                                            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(file.LocalFileName);
                                            FullsizeImage.Save(filePath);
                                            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                                            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

                                            if (FullsizeImage.Width <= width)
                                            {
                                                width = FullsizeImage.Width;
                                            }

                                            int NewHeight = FullsizeImage.Height * width / FullsizeImage.Width;
                                            if (NewHeight > height)
                                            {
                                                // Resize with height instead
                                                width = FullsizeImage.Width * height / FullsizeImage.Height;
                                                NewHeight = height;
                                            }

                                            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

                                            // Clear handle to original file so that we can overwrite it if necessary
                                            FullsizeImage.Dispose();
                                            string newName = "Thumb_" + Path.GetFileName(name);
                                            string newFile = Path.Combine(model.Form.UploadPhysicalPath, newName);
                                            // Save resized picture
                                            NewImage.Save(newFile);
                                            NewImage.Dispose();
                                            File.Delete(file.LocalFileName);
                                        }
                                    }
                                }
                                else {
                                    File.Delete(file.LocalFileName);
                                }
                            }

                        }
                        else if (files !=null && files is System.Web.HttpFileCollectionWrapper)
                        {
                            HttpFileCollectionWrapper files2 = ((System.Web.HttpFileCollectionWrapper)files);

                            if (files2.AllKeys.Contains(field.FieldId.ToString()))
                            {
                                HttpPostedFileBase file = files2[field.FieldId.ToString()];
                                string filename = file.FileName;
                                if (!string.IsNullOrEmpty(filename))
                                {
                                    fundet = true;
                                    string name = model.UniqueId + "-" + field.FieldId.ToString() + Path.GetExtension(filename).ToLower();
                                    string filePath = Path.Combine(model.Form.UploadPhysicalPath, name);
                                    field.Data = name;

                                    int width = Properties.Settings.Default.MaxWidth;
                                    int height = Properties.Settings.Default.MaxHeight;

                                    file.SaveAs(filePath);
                                    System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(filePath);
                                    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                                    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

                                    if (FullsizeImage.Width <= width)
                                    {
                                        width = FullsizeImage.Width;
                                    }

                                    int NewHeight = FullsizeImage.Height * width / FullsizeImage.Width;
                                    if (NewHeight > height)
                                    {
                                        // Resize with height instead
                                        width = FullsizeImage.Width * height / FullsizeImage.Height;
                                        NewHeight = height;
                                    }

                                    System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

                                    // Clear handle to original file so that we can overwrite it if necessary
                                    FullsizeImage.Dispose();
                                    string newName = "Thumb_" + Path.GetFileName(name);
                                    string newFile = Path.Combine(model.Form.UploadPhysicalPath, newName);
                                    // Save resized picture
                                    NewImage.Save(newFile);
                                    NewImage.Dispose();
                                }
                            }
                        }
                        if (!fundet && !string.IsNullOrEmpty(formValues[field.FieldId.ToString()]))
                        {
                            string[] info = formValues[field.FieldId.ToString()].Split(new char[] { ';' });
                            int index = info[1].IndexOf(",");
                            string name = model.UniqueId + "-" + field.FieldId.ToString() + info[0].Replace("data:image/", ".");
                            field.Data = name;
                            if (info[1].Length > (index + 1))
                            {
                                string image = info[1].Substring(index + 1);
                                string filePath = Path.Combine(model.Form.UploadPhysicalPath, name);
                                using (var fs = new FileStream(filePath, FileMode.Create))
                                {
                                    byte[] byteFromString;
                                    byteFromString = Convert.FromBase64String(image);
                                    fs.Write(byteFromString, 0, byteFromString.Length);

                                }
                                try
                                {
                                    int width = Properties.Settings.Default.MaxWidth;
                                    int height = Properties.Settings.Default.MaxHeight;
                                    System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(filePath);

                                    // Prevent using images internal thumbnail
                                    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                                    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

                                    if (FullsizeImage.Width <= width)
                                    {
                                        width = FullsizeImage.Width;
                                    }

                                    int NewHeight = FullsizeImage.Height * width / FullsizeImage.Width;
                                    if (NewHeight > height)
                                    {
                                        // Resize with height instead
                                        width = FullsizeImage.Width * height / FullsizeImage.Height;
                                        NewHeight = height;
                                    }

                                    System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

                                    // Clear handle to original file so that we can overwrite it if necessary
                                    FullsizeImage.Dispose();
                                    string newName = "Thumb_" + Path.GetFileName(name);
                                    string newFile = Path.Combine(model.Form.UploadPhysicalPath, newName);
                                    // Save resized picture
                                    NewImage.Save(newFile);
                                    NewImage.Dispose();
                                }
                                catch
                                { }
                            }
                        }
                    }
                    #endregion
                    else if (field.FieldTypeId == 16) //Upload
                    {
                        field.Data = formValues["Geometri"];
                    }
                    else if (field.FieldTypeId == 17) //Upload
                    {
                        field.Data = formValues["Position"];
                    }
                    else if (field.FieldTypeId == 18) //Upload
                    {
                        field.Data = formValues["Accuracy"];
                    }
                    else
                    {
                        string value = formValues[field.FieldId.ToString()];
                        field.Data = value;
                        switch (field.FieldTypeId)
                        {
                            case 7:

                                if (email.IsMatch(field.Data))
                                {
                                    string emailView = "";
                                    Field operationField = null;
                                    if (operation == Operation.Create)
                                    {
                                        emailView = field.Form.ViewEmailToSenderOnCreate;
                                        operationField = field.Form.Fields.FirstOrDefault(m => m.FieldTypeId == 12);
                                    }
                                    else if (operation == Operation.Edit)
                                    {
                                        emailView = field.Form.ViewEmailToSenderOnEdit;
                                        operationField = field.Form.Fields.FirstOrDefault(m => m.FieldTypeId == 13);
                                    }
                                    if (!String.IsNullOrEmpty(emailView) && operationField != null)
                                    {
                                        string send = formValues[operationField.FieldId.ToString()];
                                        if (!String.IsNullOrEmpty(send))
                                        {
                                            if (send != "false" && send != "off")
                                                emails.Add(new DataEmailModel { Email = field.Data, View = emailView });
                                        }

                                    }
                                }
                                break;
                            /*case 10:

                                DateTime dt;
                                if (!DateTime.TryParse(field.Data, culture, DateTimeStyles.AssumeLocal, out dt))
                                {
                                    ModelState.AddModelError(field.FieldId.ToString(), field.Data + " er ikke en gyldig dato");
                                }
                                break;*/
                        }
                        Selection selection = field.Selections.SingleOrDefault(m => m.Name == field.Data);
                        if (selection != null)
                        {

                            if (!String.IsNullOrEmpty(selection.Email))
                            {
                                if (operation == Operation.Create && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnCreate))
                                {
                                    emails.Add(new DataEmailModel { Email = selection.Email, View = model.Form.ViewEmailToReceiverOnCreate });
                                }
                                else if (operation == Operation.Edit && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnEdit))
                                {
                                    emails.Add(new DataEmailModel { Email = selection.Email, View = model.Form.ViewEmailToReceiverOnEdit });
                                }

                            }
                        }

                    }
                }
            }
            return new DataCreateModel()
            {
                Emails = emails,
                Model = model,
            };
        }
 protected override void Initialize(RequestContext requestContext)
 {
     if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
     if (FormsRepository == null) { FormsRepository = new RepositoryForms(); }
     if (CompaniesRepository == null) { CompaniesRepository = new RepositoryCompanies(); }
     base.Initialize(requestContext);
 }
 protected override void Initialize(RequestContext requestContext)
 {
     if (Repository == null) { Repository = new RepositoryCompanies(); }
     base.Initialize(requestContext);
 }
        private DataCreateModel CreateModel(DataViewModel postModel, FormCollection formValues, Operation operation)
        {
            CultureInfo culture = CultureInfo.CreateSpecificCulture("da-DK");
            RepositoryViews repository = new RepositoryViews();
            Models.View view = repository.Get(postModel.View.ViewId);

            DataViewModel model = new DataViewModel
            {
                View = view,
                Form = view.Group.Forms.Single(m => m.FormId == postModel.Form.FormId),
                Date = postModel.Date,
                UniqueId = postModel.UniqueId,
                ItemId = postModel.ItemId,
                UserName = postModel.UserName,
                UserId = postModel.UserId,
            };
            if (operation == Operation.Create)
            {
                model.Date = DateTime.Now;
                model.UniqueId = Guid.NewGuid().ToString();
                if (User.Identity.IsAuthenticated)
                {
                    model.UserName = User.Identity.Name;
                    model.UserId = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();
                }
            }
            if (!String.IsNullOrEmpty(model.UserName))
            {
                UserProfile profile = UserProfile.GetUserProfile(model.UserName);
                RepositoryCompanies rc = new RepositoryCompanies();
                Company company = rc.Get(profile.CompanyId);
                if (company != null)
                    model.Company = company.Name;
            }

            List<DataEmailModel> emails = new List<DataEmailModel>();
            if (!String.IsNullOrEmpty(model.Form.Email))
            {
                if (operation == Operation.Create && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnCreate))
                {
                    emails.Add(new DataEmailModel { Email = model.Form.Email, View = model.Form.ViewEmailToReceiverOnCreate });
                }
                else if (operation == Operation.Edit && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnEdit))
                {
                    emails.Add(new DataEmailModel { Email = model.Form.Email, View = model.Form.ViewEmailToReceiverOnEdit });
                }
            }
            foreach (Field field in model.Form.Fields)
            {
                #region 8 Upload
                if (field.FieldTypeId == 8) //Upload
                {
                    string value = formValues[field.FieldId.ToString()];
                    if (!String.IsNullOrEmpty(value))
                    {
                        field.Data = value;
                    }
                    if (Request.Files.AllKeys.Contains(field.FieldId.ToString()))
                    {
                        HttpPostedFileBase file = Request.Files[field.FieldId.ToString()];
                        if (file.ContentLength > 0)
                        {
                            string name = model.UniqueId + "-" + field.FieldId.ToString() + Path.GetExtension(file.FileName);
                            string filePath = Path.Combine(model.Form.UploadPhysicalPath, name);
                            file.SaveAs(filePath);
                            field.Data = name;
                            try
                            {
                                int width = Properties.Settings.Default.MaxWidth;
                                int height = Properties.Settings.Default.MaxHeight;
                                System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(filePath);

                                // Prevent using images internal thumbnail
                                FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                                FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

                                if (FullsizeImage.Width <= width)
                                {
                                    width = FullsizeImage.Width;
                                }

                                int NewHeight = FullsizeImage.Height * width / FullsizeImage.Width;
                                if (NewHeight > height)
                                {
                                    // Resize with height instead
                                    width = FullsizeImage.Width * height / FullsizeImage.Height;
                                    NewHeight = height;
                                }

                                System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

                                // Clear handle to original file so that we can overwrite it if necessary
                                FullsizeImage.Dispose();
                                string newName = "Thumb_" + Path.GetFileName(name);
                                string newFile = Path.Combine(model.Form.UploadPhysicalPath, newName);
                                // Save resized picture
                                NewImage.Save(newFile);
                                NewImage.Dispose();
                            }
                            catch
                            { }
                        }
                        else if (field.Required)
                        {
                            ModelState.AddModelError(field.FieldId.ToString(), field.Name + " er påkrævet");
                        }
                    }
                }
                #endregion
                else if (field.FieldTypeId == 16) //Geometry
                {
                    string value = formValues["Geometri"];
                    if (String.IsNullOrEmpty(value))
                    {
                        if (field.Required)
                        {
                            string error = field.Name + " er påkrævet";
                            ModelState.AddModelError("Geometri", error);
                        }

                    }
                    else
                    {
                        field.Data = value;
                    }
                }
                else if (field.FieldTypeId == 17) //Position
                {
                    string value = formValues["Position"];
                    if (String.IsNullOrEmpty(value))
                    {
                        if (field.Required)
                        {
                            string error = field.Name + " er påkrævet";
                            ModelState.AddModelError("Position", error);
                        }

                    }
                    else
                    {
                        field.Data = value;
                    }
                }
                else if (field.FieldTypeId == 18) //Accuracy
                {
                    string value = formValues["Accuracy"];
                    if (String.IsNullOrEmpty(value))
                    {
                        if (field.Required)
                        {
                            string error = field.Name + " er påkrævet";
                            ModelState.AddModelError("Accuracy", error);
                        }

                    }
                    else
                    {
                        field.Data = value;
                    }
                }
                else
                {
                    string value = formValues[field.FieldId.ToString()];
                    if (String.IsNullOrEmpty(value))
                    {
                        if (field.Required)
                        {
                            string error = field.Name + " er påkrævet";
                            ModelState.AddModelError(field.FieldId.ToString(), error);
                        }

                    }
                    else
                    {
                        field.Data = value;
                        switch (field.FieldTypeId)
                        {
                            case 7:

                                if (email.IsMatch(field.Data))
                                {
                                    string emailView = "";
                                    Field operationField = null;
                                    if (operation == Operation.Create)
                                    {
                                        emailView = field.Form.ViewEmailToSenderOnCreate;
                                        operationField = field.Form.Fields.FirstOrDefault(m => m.FieldTypeId == 12);
                                    }
                                    else if (operation == Operation.Edit)
                                    {
                                        emailView = field.Form.ViewEmailToSenderOnEdit;
                                        operationField = field.Form.Fields.FirstOrDefault(m => m.FieldTypeId == 13);
                                    }
                                    if (!String.IsNullOrEmpty(emailView) && operationField != null)
                                    {
                                        string send = formValues[operationField.FieldId.ToString()];
                                        if (!String.IsNullOrEmpty(send))
                                        {
                                            if (send != "false")
                                                emails.Add(new DataEmailModel { Email = field.Data, View = emailView });
                                        }

                                    }
                                }
                                else
                                {
                                    ModelState.AddModelError(field.FieldId.ToString(), field.Data + " er ikke en gyldig email");
                                }
                                break;
                            case 10:

                                DateTime dt;
                                if (!DateTime.TryParse(field.Data, culture, DateTimeStyles.AssumeLocal, out dt))
                                {
                                    ModelState.AddModelError(field.FieldId.ToString(), field.Data + " er ikke en gyldig dato");
                                }
                                break;
                        }
                        Selection selection = field.Selections.SingleOrDefault(m => m.Name == field.Data);
                        if (selection != null)
                        {

                            if (!String.IsNullOrEmpty(selection.Email))
                            {
                                if (operation == Operation.Create && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnCreate))
                                {
                                    emails.Add(new DataEmailModel { Email = selection.Email, View = model.Form.ViewEmailToReceiverOnCreate });
                                }
                                else if (operation == Operation.Edit && !String.IsNullOrEmpty(model.Form.ViewEmailToReceiverOnEdit))
                                {
                                    emails.Add(new DataEmailModel { Email = selection.Email, View = model.Form.ViewEmailToReceiverOnEdit });
                                }

                            }
                        }
                    }
                }
            }
            return new DataCreateModel()
            {
                Emails = emails,
                Model = model,
            };
        }
 public ActionResult Index(int id, int? itemId, int? formId, string column, bool? ascending)
 {
     RepositoryViews repositoryViews = new RepositoryViews();
     Models.View view = repositoryViews.Get(id);
     if (formId.HasValue)
         view.Group.DefaultFormId = formId.Value;
     if (itemId.HasValue)
     {
         //2 = Edit
         //3 = Delete
         //4 = Details
         if (view.ViewTypeId == 2 || view.ViewTypeId == 3 || view.ViewTypeId == 4)
         {
             RepositoryMapguide mapguide = new RepositoryMapguide();
             DataViewModel model = new DataViewModel()
             {
                 ItemId = itemId.Value,
                 View = view,
                 Form = view.Group.Forms.Single(m => m.FormId == view.Group.DefaultFormId)
             };
             model = mapguide.Get(model);
             return View(view.Name, model);
         }
     }
     else
     {
         //1 = Create
         if (view.ViewTypeId == 1)
         {
             DataViewModel model = new DataViewModel
             {
                 View = view,
                 Form = view.Group.Forms.SingleOrDefault(m => m.FormId == view.Group.DefaultFormId),
                 Date = DateTime.Now,
                 UniqueId = Guid.NewGuid().ToString()
             };
             if (User.Identity.IsAuthenticated)
             {
                 model.UserName = User.Identity.Name;
                 model.UserId = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();
                 UserProfile profile = UserProfile.GetUserProfile(User.Identity.Name);
                 RepositoryCompanies rc = new RepositoryCompanies();
                 Company company = rc.Get(profile.CompanyId);
                 if (company != null)
                     model.Company = company.Name;
             }
             return View(view.Name, model);
         }
         //5 = List All
         else if (view.ViewTypeId == 5)
         {
             RepositoryMapguide mapguide = new RepositoryMapguide();
             DataListModel model = mapguide.GetList(view, "");
             return View(view.Name, model);
         }
         //6 = List My
         else if (view.ViewTypeId == 6)
         {
             RepositoryMapguide mapguide = new RepositoryMapguide();
             DataListModel model = null;
             if (User.Identity.IsAuthenticated)
             {
                 model = mapguide.GetList(view, Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
             }
             else
             {
                 model = mapguide.GetList(view, "");
             }
             return View(view.Name, model);
         }
     }
     return View("Error");
 }
        public DataListModel GetList(Models.View view, List<DataSelectionModel> dataSelections)
        {
            Form form = view.Group.Forms.Single(m => m.FormId == view.Group.DefaultFormId);
            List<Field> columns = new List<Field>();
            foreach (Field field in form.Fields.Where(m => m.FieldColumn != null && !m.FieldColumn.Equals(String.Empty)).OrderBy(a => a.FieldOrder))
            {
                Permission permission = view.Permissions.FirstOrDefault(m => m.FieldId == field.FieldId);
                if (permission == null)
                {
                    columns.Add(field);
                }
                else
                {
                    if (permission.PermissionTypeId != 0)
                    {
                        columns.Add(field);
                    }
                }

            }
            DataListModel model = new DataListModel
            {
                View = view,
                Form = form,
                Columns = columns
            };
            RepositoryCompanies repositoryCompanies = new RepositoryCompanies();
            DataSelectionModel layer = null;
            foreach (DataSelectionModel selection in dataSelections)
            {
                if (selection.name == form.Name)
                {
                    layer = selection;
                    break;
                }
            }
            if (layer != null)
            {
                foreach (List<string> row in layer.aElements)
                {
                    DataListItemModel listItem = new DataListItemModel();
                    for (int i = 0; i < layer.nProperties; i++)
                    {
                        if (!String.IsNullOrEmpty(row[i]))
                        {
                            string upperPropertyName = layer.aPropertiesName[i].ToUpper();
                            switch (upperPropertyName)
                            {
                                case "ID":
                                    int id = 0;
                                    int.TryParse(row[i], out id);
                                    listItem.ItemId = id;
                                    break;
                                case "UNIQUEID":
                                    listItem.UniqueId = row[i];
                                    break;
                                case "USERID":
                                    listItem.UserId = row[i];
                                    MembershipUser user = Membership.GetUser(new Guid(listItem.UserId));
                                    if (user != null)
                                    {
                                        listItem.UserName = user.UserName;
                                        UserProfile profile = UserProfile.GetUserProfile(user.UserName);
                                        Company company = repositoryCompanies.Get(profile.CompanyId);
                                        if (company != null)
                                            listItem.Company = company.Name;
                                    }
                                    break;
                                case "DATO":
                                    DateTime dt = DateTime.Now;
                                    DateTime.TryParse(row[i], culture, DateTimeStyles.AssumeLocal, out dt);
                                    listItem.Date = dt;
                                    break;
                                default:
                                    foreach (Field field in model.Columns)
                                    {

                                        if (layer.aPropertiesName[i].ToUpper() == field.FieldColumn.ToUpper())
                                        {
                                            if (field.FieldTypeId == 10)
                                            {

                                                DateTime dt1 = DateTime.Now;
                                                DateTime.TryParse(row[i], culture, DateTimeStyles.AssumeLocal, out dt1);
                                                listItem.Data.Add(field.FieldColumn, dt1.ToString("d", culture));
                                            }
                                            else
                                            {
                                                listItem.Data.Add(field.FieldColumn, row[i]);
                                            }
                                            break;
                                        }
                                    }
                                    break;
                            }
                        }
                    }
                    model.ListItemModels.Add(listItem);
                }
            }
            return model;
        }
        public DataViewModel Get(DataViewModel m)
        {
            RepositoryCompanies repositoryCompanies = new RepositoryCompanies();
            NumberFormatInfo nfi = new NumberFormatInfo();
            nfi.NumberDecimalSeparator = ".";
            nfi.NumberGroupSeparator = ",";
            Form form = m.Form;
            View view = m.View;
            List<Field> columns = new List<Field>();
            Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>();
            string select = "";
            bool fId = false;
            bool fUserId = false;
            bool fUniqueId = false;
            bool fDato = false;
            foreach (Field field in form.Fields.Where(a => a.FieldColumn != null && !a.FieldColumn.Equals(String.Empty)).OrderBy(b => b.FieldOrder))
            {
                Permission permission = view.Permissions.FirstOrDefault(a => a.FieldId == field.FieldId);
                //if (permission == null )//|| permission.PermissionTypeId != 0)
                //{
                    columns.Add(field);
                    switch(field.FieldColumn.ToUpper())
                    {

                        case "ID":
                            select = select + "," + field.FieldColumn;
                            fId = true;
                            break;
                        case "UNIQUEID":
                            select = select + "," + field.FieldColumn;
                            fUniqueId = true;
                            break;
                        case "USERID":
                            select = select + "," + field.FieldColumn;
                            fUserId = true;
                            break;
                        case "DATO":
                            select = select + "," + field.FieldColumn;
                            fDato = true;
                            break;
                        default:
                            if (field.FieldTypeId == 16 || field.FieldTypeId == 17)
                            {
                                select = select + "," + field.FieldColumn+".STAsText() AS " + field.FieldColumn;
                            }
                            else
                            {
                                select = select + "," + field.FieldColumn;
                            }
                            break;
                    }

                //}

            }
            if(!fUniqueId)
                select = select + ",uniqueid";
            if (!fUserId)
                select = select + ",userid";
            if (!fDato)
                select = select + ",dato";
            if (!fId)
                select = select + ",id";
            select = "SELECT " + select.Substring(1);
            DataTable dt = new DataTable();
            using (SqlConnection connection = new SqlConnection(m.Form.ResourceName))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = select +" FROM "+ m.Form.ClassName + " WHERE Id="+m.ItemId.ToString();
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(dt);
            }
            DataViewModel model = new DataViewModel
            {
                View = m.View,
                Form = m.Form,
            };
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (!row.IsNull(i))
                    {

                        string propertyName = dt.Columns[i].ColumnName;
                        string propertyNameUpper = propertyName.ToUpper();
                        switch (propertyNameUpper)
                        {
                            case "ID":
                                model.ItemId = (int)row[i];
                                foreach (Field field in model.Form.Fields)
                                {
                                    if (!string.IsNullOrEmpty(field.FieldColumn))
                                    {
                                        if (field.FieldColumn.ToUpper() == propertyNameUpper)
                                        {
                                            field.Data = row[i].ToString();
                                        }
                                    }
                                }
                                break;
                            case "UNIQUEID":
                                model.UniqueId = (string)row[i];
                                break;
                            case "USERID":
                                if (row[i] != DBNull.Value && row[i].ToString() != "")
                                {
                                    model.UserId = (string)row[i];
                                    UserInfo user = null;
                                    if (users.ContainsKey(model.UserId))
                                        user = users[model.UserId];
                                    else
                                    {
                                        MembershipUser user1 = Membership.GetUser(new Guid(model.UserId));
                                        if (user1 != null)
                                        {
                                            user = new UserInfo();
                                            user.UserName = user1.UserName;
                                            UserProfile profile = UserProfile.GetUserProfile(user1.UserName);
                                            if (profile != null)
                                            {
                                                Company company = repositoryCompanies.Get(profile.CompanyId);
                                                if (company != null)
                                                {
                                                    user.CompanyName = company.Name;
                                                }
                                            }
                                        }
                                        users.Add(model.UserId, user);
                                    }
                                    if (user != null)
                                    {
                                        model.UserName = user.UserName;
                                        model.Company = user.CompanyName;
                                    }
                                }
                                break;
                            case "DATO":
                                model.Date = (DateTime)row[i];
                                break;
                            default:
                                foreach (Field field in model.Form.Fields)
                                {
                                    if (!string.IsNullOrEmpty(field.FieldColumn))
                                    {
                                        if (field.FieldColumn.ToUpper() == propertyNameUpper)
                                        {

                                            if (field.FieldTypeId == 10)
                                            {
                                                DateTime dt1 = (DateTime)row[i];
                                                field.Data = dt1.ToString("dd-MM-yyy");
                                            }
                                            else
                                            {
                                                field.Data = row[i].ToString();
                                            }
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }
            }
            return model;
        }
        public DataListModel GetList(View view, string userId)
        {
            RepositoryCompanies repositoryCompanies = new RepositoryCompanies();
            List<Field> columns = new List<Field>();
            Form form = view.Group.Forms.Single(m => m.FormId == view.Group.DefaultFormId);
            string select = "";
            bool fId = false;
            bool fUserId = false;
            bool fUniqueId = false;
            bool fDato = false;
            foreach (Field field in form.Fields.Where(a => a.FieldColumn != null && !a.FieldColumn.Equals(String.Empty)).OrderBy(b => b.FieldOrder))
            {
                Permission permission = view.Permissions.FirstOrDefault(a => a.FieldId == field.FieldId);
                if (permission == null || permission.PermissionTypeId != 0)
                {
                    columns.Add(field);
                    switch (field.FieldColumn.ToUpper())
                    {
                        case "ID":
                            select = select + "," + field.FieldColumn;
                            fId = true;
                            break;
                        case "UNIQUEID":
                            select = select + "," + field.FieldColumn;
                            fUniqueId = true;
                            break;
                        case "USERID":
                            select = select + "," + field.FieldColumn;
                            fUserId = true;
                            break;
                        case "DATO":
                            select = select + "," + field.FieldColumn;
                            fDato = true;
                            break;
                        default:
                            if (field.FieldTypeId == 16)
                            {
                                select = select + "," + field.FieldColumn + ".STAsText() AS " + field.FieldColumn;
                            }
                            else
                            {
                                select = select + "," + field.FieldColumn;
                            }

                            break;
                    }

                }

            }
            if (!fUniqueId)
                select = select + ",UniqueId";
            if (!fUserId)
                select = select + ",UserId";
            if (!fDato)
                select = select + ",Dato";
            if (!fId)
                select = select + ",Id";
            select = "SELECT " + select.Substring(1);

            DataListModel model = new DataListModel
            {
                View = view,
                Form = form,
                Columns = columns
            };
            DataTable dt = new DataTable();
            using (SqlConnection connection = new SqlConnection(form.ResourceName))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = select+" FROM " + form.ClassName;
                if (!String.IsNullOrEmpty(userId))
                {
                    command.CommandText = command.CommandText + " WHERE UserId = '" + userId + "'";
                }
                command.CommandText += " order by dato desc";
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(dt);
            }
            Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>();
            foreach (DataRow row in dt.Rows)
            {
                DataListItemModel listItem = new DataListItemModel();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (!row.IsNull(i))
                    {

                        string propertyName = dt.Columns[i].ColumnName;
                        string propertyNameUpper = propertyName.ToUpper();
                        switch (propertyNameUpper)
                        {
                            case "ID":
                                listItem.ItemId = (int)row[i];
                                if(fId)
                                    listItem.Data.Add(propertyName, row[i].ToString());
                                break;
                            case "UNIQUEID":

                                listItem.UniqueId = (string)row[i];
                                if (fUniqueId)
                                    listItem.Data.Add(propertyName, row[i].ToString());
                                break;
                            case "USERID":
                                if (row[i] != DBNull.Value && row[i].ToString() != "")
                                {
                                    listItem.UserId = (string)row[i];
                                    if (fUserId)
                                        listItem.Data.Add(propertyName, row[i].ToString());
                                    UserInfo user = null;
                                    if (users.ContainsKey(listItem.UserId))
                                        user = users[listItem.UserId];
                                    else
                                    {
                                        MembershipUser user1 = Membership.GetUser(new Guid(listItem.UserId));
                                        if (user1 != null)
                                        {
                                            user = new UserInfo();
                                            user.UserName = user1.UserName;
                                            UserProfile profile = UserProfile.GetUserProfile(user1.UserName);
                                            if (profile != null)
                                            {
                                                Company company = repositoryCompanies.Get(profile.CompanyId);
                                                if (company != null)
                                                {
                                                    user.CompanyName = company.Name;
                                                }
                                            }
                                        }
                                        users.Add(listItem.UserId, user);
                                    }
                                    if (user != null)
                                    {
                                        listItem.UserName = user.UserName;
                                        listItem.Company = user.CompanyName;
                                    }
                                }
                                break;
                            case "DATO":
                                listItem.Date = (DateTime)row[i];
                                if (fDato)
                                    listItem.Data.Add(propertyName, row[i].ToString());
                                break;
                            default:
                                listItem.Data.Add(propertyName, row[i].ToString());
                                break;
                        }
                    }
                }
                model.ListItemModels.Add(listItem);
            }
            return model;
        }