public ActionResult LoadMetaDataForm(SetupModel model)
        {
            if (model.SelectedMetadataStructureId == -1)
            {
                ModelState.AddModelError("SelectedMetadataStructureId", "Please select a metadata structure.");
            }

            if (ModelState.IsValid)
            {
                using (var metadataStructureManager = new MetadataStructureManager())
                    using (var entityManager = new EntityManager())
                        using (var researchPlanManager = new ResearchPlanManager())
                        {
                            var md = metadataStructureManager.Repo.Get(a => a.Id == model.SelectedMetadataStructureId).FirstOrDefault();

                            //get entitytype
                            var entityType = entityManager.FindByName("Publication");

                            if (md != null)
                            {
                                CreateTaskmanager taskManager = new CreateTaskmanager();
                                taskManager.AddToBus(CreateTaskmanager.METADATASTRUCTURE_ID, md.Id);

                                taskManager.AddToBus(CreateTaskmanager.SAVE_WITH_ERRORS, true);
                                taskManager.AddToBus(CreateTaskmanager.NO_IMPORT_ACTION, true);

                                taskManager.AddToBus(CreateTaskmanager.INFO_ON_TOP_TITLE, "Edit Publication");
                                taskManager.AddToBus(CreateTaskmanager.INFO_ON_TOP_DESCRIPTION, "<p>Here you can enter metadata for your new dataset. The form varies according to the metadata structure you selected in the first step. Mandatory fields are indicated with an red asterisk. You can add, remove, or re - order elements(e.g.multiple Creators) using the buttons at the right.</p>");

                                // get existing researchPlan
                                string       researchPlanName = "Research plan";
                                ResearchPlan researchPlan     = researchPlanManager.Repo.Get(r => researchPlanName.Equals(r.Title)).FirstOrDefault();
                                taskManager.AddToBus(CreateTaskmanager.RESEARCHPLAN_ID, researchPlan.Id);

                                //create unstructured datastructure
                                DataStructure dataStructure = CreateDataStructure("Publication") as UnStructuredDataStructure;
                                taskManager.AddToBus(CreateTaskmanager.DATASTRUCTURE_ID, dataStructure.Id);

                                HttpContext.Session["CreateDatasetTaskmanager"] = taskManager;
                                setAdditionalFunctions();

                                var view = this.Render("DCM", "Form", "StartMetadataEditor", new RouteValueDictionary()
                                {
                                });

                                return(Content(view.ToHtmlString(), "text/html"));
                            }

                            else
                            {
                                return(Content("Metadata structure not exsits"));
                            }
                        }
            }
            else
            {
                return(Content("Metadata structure not exsits"));
            }
        }
        /// <summary>
        /// Store the incoming xmldocument in the bus of the Create TaskManager with
        /// the METADATA_XML key
        /// </summary>
        /// <param name="metadataXml"></param>
        private void SetXml(XDocument metadataXml)
        {
            TaskManager = (CreateTaskmanager)Session["CreateDatasetTaskmanager"];

            // load metadatastructure with all packages and attributes

            if (metadataXml != null)
            {
                // locat path
                //string path = Path.Combine(AppConfiguration.GetModuleWorkspacePath("DCM"), "metadataTemp.Xml");

                TaskManager.AddToBus(CreateTaskmanager.METADATA_XML, metadataXml);

                //setup loaded
                if (TaskManager.Bus.ContainsKey(CreateTaskmanager.SETUP_LOADED))
                {
                    TaskManager.Bus[CreateTaskmanager.SETUP_LOADED] = true;
                }
                else
                {
                    TaskManager.Bus.Add(CreateTaskmanager.SETUP_LOADED, true);
                }
            }
        }
        // GET: CreatePublication
        public ActionResult Index()
        {
            string mulitbleMetadataStructure = Helper.Settings.get("MultibleMetadataStructures").ToString();

            if (mulitbleMetadataStructure == "true")
            {
                SetupModel model = new SetupModel();

                using (MetadataStructureManager metadataStructureManager = new MetadataStructureManager())
                {
                    IEnumerable <MetadataStructure> metadataStructureList = metadataStructureManager.Repo.Get();

                    foreach (MetadataStructure metadataStructure in metadataStructureList)
                    {
                        if (xmlDatasetHelper.IsActive(metadataStructure.Id) &&
                            HasEntityTypeName(metadataStructure, "Publication"))
                        {
                            string title = metadataStructure.Name;

                            model.MetadataStructureList.Add(new ViewSelectItem(metadataStructure.Id, title));
                        }
                    }

                    model.MetadataStructureList.OrderBy(p => p.Title);
                }

                return(View("ChooseMetadataStructure", model));
            }
            else
            {
                using (var metadataStructureManager = new MetadataStructureManager())
                    using (var entityManager = new EntityManager())
                        using (var researchPlanManager = new ResearchPlanManager())
                        {
                            //get metadatastruture
                            var metadataStructureName = Helper.Settings.get("DefaultMetadataStructure");

                            var md = metadataStructureManager.Repo.Get(a => a.Name == metadataStructureName.ToString()).FirstOrDefault();

                            //get entitytype
                            var entityType = entityManager.FindByName("Publication");

                            if (md != null)
                            {
                                CreateTaskmanager taskManager = new CreateTaskmanager();
                                taskManager.AddToBus(CreateTaskmanager.METADATASTRUCTURE_ID, md.Id);

                                taskManager.AddToBus(CreateTaskmanager.SAVE_WITH_ERRORS, true);
                                taskManager.AddToBus(CreateTaskmanager.NO_IMPORT_ACTION, true);

                                taskManager.AddToBus(CreateTaskmanager.INFO_ON_TOP_TITLE, "Create Publication");
                                taskManager.AddToBus(CreateTaskmanager.INFO_ON_TOP_DESCRIPTION, "<p>Here you can enter metadata for your new dataset. The form varies according to the metadata structure you selected in the first step. Mandatory fields are indicated with an red asterisk. You can add, remove, or re - order elements(e.g.multiple Creators) using the buttons at the right.</p>");


                                // get existing researchPlan
                                string       researchPlanName = "Research plan";
                                ResearchPlan researchPlan     = researchPlanManager.Repo.Get(r => researchPlanName.Equals(r.Title)).FirstOrDefault();
                                taskManager.AddToBus(CreateTaskmanager.RESEARCHPLAN_ID, researchPlan.Id);

                                //create unstructured datastructure
                                DataStructure dataStructure = CreateDataStructure("Publication") as UnStructuredDataStructure;
                                taskManager.AddToBus(CreateTaskmanager.DATASTRUCTURE_ID, dataStructure.Id);

                                HttpContext.Session["CreateDatasetTaskmanager"] = taskManager;
                                setAdditionalFunctions();

                                var view = this.Render("DCM", "Form", "StartMetadataEditor", new RouteValueDictionary()
                                {
                                });

                                return(Content(view.ToHtmlString(), "text/html"));
                            }

                            else
                            {
                                return(Content("Metadata structure not exsits"));
                            }
                        }
            }
        }
        //
        // GET: /DCM/CreateDataset/
        /// <summary>
        /// Load the createDataset action with different parameter type options
        /// type eg ("DataStructureId", "DatasetId", "MetadataStructureId")
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult Index(long id = -1, string type = "")
        {
            ViewBag.Title = PresentationModel.GetViewTitleForTenant("Create Dataset", this.Session.GetTenant());

            Session["CreateDatasetTaskmanager"] = null;
            if (TaskManager == null)
            {
                TaskManager = (CreateTaskmanager)Session["CreateDatasetTaskmanager"];
            }

            if (TaskManager == null)
            {
                TaskManager = new CreateTaskmanager();

                Session["CreateDatasetTaskmanager"]  = TaskManager;
                Session["MetadataStructureViewList"] = LoadMetadataStructureViewList();
                Session["DataStructureViewList"]     = LoadDataStructureViewList();
                Session["DatasetViewList"]           = LoadDatasetViewList();

                setAdditionalFunctions();

                //set Entity to TaskManager
                TaskManager.AddToBus(CreateTaskmanager.ENTITY_CLASS_PATH, "BExIS.Dlm.Entities.Data.Dataset");

                SetupModel Model = GetDefaultModel();

                //if id is set and its type dataset
                if (id != -1 && type.ToLower().Equals("datasetid"))
                {
                    ViewBag.Title = PresentationModel.GetViewTitleForTenant("Copy Dataset", this.Session.GetTenant());


                    Dataset dataset = this.GetUnitOfWork().GetReadOnlyRepository <Dataset>().Get(id);
                    Model.SelectedDatasetId           = id;
                    Model.SelectedMetadataStructureId = dataset.MetadataStructure.Id;
                    Model.SelectedDataStructureId     = dataset.DataStructure.Id;
                    Model.BlockMetadataStructureId    = true;
                    Model.BlockDatasetId = true;
                }

                if (id != -1 && type.ToLower().Equals("metadatastructureid"))
                {
                    ViewBag.Title = PresentationModel.GetViewTitleForTenant("Copy Dataset", this.Session.GetTenant());
                    Model.SelectedMetadataStructureId = id;
                }

                if (id != -1 && type.ToLower().Equals("datastructureid"))
                {
                    ViewBag.Title = PresentationModel.GetViewTitleForTenant("Copy Dataset", this.Session.GetTenant());
                    Model.SelectedDataStructureId = id;
                    if (TaskManager.Bus.ContainsKey(CreateTaskmanager.METADATASTRUCTURE_ID))
                    {
                        Model.SelectedMetadataStructureId = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.METADATASTRUCTURE_ID]);
                    }
                }

                return(View(Model));
            }

            return(View());
        }
        /// <summary>
        /// Submit a Dataset based on the imformations
        /// in the CreateTaskManager
        /// </summary>
        public long SubmitDataset(bool valid)
        {
            #region create dataset
            DatasetManager       dm  = new DatasetManager();
            DataStructureManager dsm = new DataStructureManager();
            ResearchPlanManager  rpm = new ResearchPlanManager();
            XmlDatasetHelper     xmlDatasetHelper = new XmlDatasetHelper();
            string title      = "";
            long   datasetId  = 0;
            bool   newDataset = true;

            try
            {
                TaskManager = (CreateTaskmanager)Session["CreateDatasetTaskmanager"];

                if (TaskManager.Bus.ContainsKey(CreateTaskmanager.DATASTRUCTURE_ID) &&
                    TaskManager.Bus.ContainsKey(CreateTaskmanager.RESEARCHPLAN_ID) &&
                    TaskManager.Bus.ContainsKey(CreateTaskmanager.METADATASTRUCTURE_ID))
                {
                    // for e new dataset
                    if (!TaskManager.Bus.ContainsKey(CreateTaskmanager.ENTITY_ID))
                    {
                        long datastructureId     = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.DATASTRUCTURE_ID]);
                        long researchPlanId      = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.RESEARCHPLAN_ID]);
                        long metadataStructureId = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.METADATASTRUCTURE_ID]);

                        DataStructure dataStructure = dsm.StructuredDataStructureRepo.Get(datastructureId);
                        //if datastructure is not a structured one
                        if (dataStructure == null)
                        {
                            dataStructure = dsm.UnStructuredDataStructureRepo.Get(datastructureId);
                        }

                        ResearchPlan rp = rpm.Repo.Get(researchPlanId);

                        MetadataStructureManager msm = new MetadataStructureManager();
                        MetadataStructure        metadataStructure = msm.Repo.Get(metadataStructureId);

                        var ds = dm.CreateEmptyDataset(dataStructure, rp, metadataStructure);
                        datasetId = ds.Id;

                        // add security
                        if (GetUsernameOrDefault() != "DEFAULT")
                        {
                            EntityPermissionManager entityPermissionManager = new EntityPermissionManager();
                            entityPermissionManager.Create <User>(GetUsernameOrDefault(), "Dataset", typeof(Dataset), ds.Id, Enum.GetValues(typeof(RightType)).Cast <RightType>().ToList());
                        }
                    }
                    else
                    {
                        datasetId  = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.ENTITY_ID]);
                        newDataset = false;
                    }

                    TaskManager = (CreateTaskmanager)Session["CreateDatasetTaskmanager"];

                    if (dm.IsDatasetCheckedOutFor(datasetId, GetUsernameOrDefault()) || dm.CheckOutDataset(datasetId, GetUsernameOrDefault()))
                    {
                        DatasetVersion workingCopy = dm.GetDatasetWorkingCopy(datasetId);

                        if (TaskManager.Bus.ContainsKey(CreateTaskmanager.METADATA_XML))
                        {
                            XDocument xMetadata = (XDocument)TaskManager.Bus[CreateTaskmanager.METADATA_XML];
                            workingCopy.Metadata = Xml.Helpers.XmlWriter.ToXmlDocument(xMetadata);
                        }

                        //set status

                        if (workingCopy.StateInfo == null)
                        {
                            workingCopy.StateInfo = new Vaiona.Entities.Common.EntityStateInfo();
                        }

                        if (valid)
                        {
                            workingCopy.StateInfo.State = DatasetStateInfo.Valid.ToString();
                        }
                        else
                        {
                            workingCopy.StateInfo.State = DatasetStateInfo.NotValid.ToString();
                        }

                        title = xmlDatasetHelper.GetInformationFromVersion(workingCopy.Id, NameAttributeValues.title);
                        if (string.IsNullOrEmpty(title))
                        {
                            title = "No Title available.";
                        }

                        TaskManager.AddToBus(CreateTaskmanager.ENTITY_TITLE, title);//workingCopy.Metadata.SelectNodes("Metadata/Description/Description/Title/Title")[0].InnerText);
                        TaskManager.AddToBus(CreateTaskmanager.ENTITY_ID, datasetId);

                        dm.EditDatasetVersion(workingCopy, null, null, null);
                        dm.CheckInDataset(datasetId, "Metadata was submited.", GetUsernameOrDefault(), ViewCreationBehavior.None);

                        //add to index
                        // ToDo check which SearchProvider it is, default luceneprovider

                        // BUG: invalid call to ddm method
                        // TODO: mODULARITY ->Call DDM Reindex

                        /*
                         * <Export tag="internalApi" id="SearchIndex"
                         * title="Reindex Search" description="Reindex Search" icon=""
                         * controller="SearchIndex" action="Get"
                         * extends="" />
                         */
                        // WORKAROUND: do not reindex
                        //ISearchProvider provider = IoCFactory.Container.ResolveForSession<ISearchProvider>() as ISearchProvider;
                        //provider?.UpdateSingleDatasetIndex(datasetId, IndexingAction.CREATE);

                        if (this.IsAccessibale("DDM", "SearchIndex", "ReIndexSingle"))
                        {
                            var x = this.Run("DDM", "SearchIndex", "ReIndexSingle", new RouteValueDictionary()
                            {
                                { "id", datasetId }
                            });
                        }

                        LoggerFactory.LogData(datasetId.ToString(), typeof(Dataset).Name, Vaiona.Entities.Logging.CrudState.Created);


                        if (newDataset)
                        {
                            var es = new EmailService();
                            es.Send(MessageHelper.GetCreateDatasetHeader(),
                                    MessageHelper.GetCreateDatasetMessage(datasetId, title, GetUsernameOrDefault()),
                                    ConfigurationManager.AppSettings["SystemEmail"]
                                    );
                        }
                        else
                        {
                            var es = new EmailService();
                            es.Send(MessageHelper.GetUpdateDatasetHeader(),
                                    MessageHelper.GetUpdateDatasetMessage(datasetId, title, GetUsernameOrDefault()),
                                    ConfigurationManager.AppSettings["SystemEmail"]
                                    );
                        }
                    }


                    return(datasetId);
                }
            }
            catch (Exception ex)
            {
                var es = new EmailService();
                es.Send(MessageHelper.GetUpdateDatasetHeader(),
                        ex.Message,
                        ConfigurationManager.AppSettings["SystemEmail"]
                        );
            }
            finally
            {
                dm.Dispose();
                rpm.Dispose();
                dsm.Dispose();
            }


            #endregion create dataset

            return(-1);
        }
        public ActionResult StoreSelectedDatasetSetup(SetupModel model)
        {
            CreateTaskmanager TaskManager      = (CreateTaskmanager)Session["CreateDatasetTaskmanager"];
            DatasetManager    datasetManager   = new DatasetManager();
            XmlDatasetHelper  xmlDatasetHelper = new XmlDatasetHelper();

            try
            {
                if (model == null)
                {
                    model = GetDefaultModel();
                    return(PartialView("Index", model));
                }

                model = LoadLists(model);

                if (ModelState.IsValid)
                {
                    TaskManager.AddToBus(CreateTaskmanager.METADATASTRUCTURE_ID, model.SelectedMetadataStructureId);
                    TaskManager.AddToBus(CreateTaskmanager.DATASTRUCTURE_ID, model.SelectedDataStructureId);

                    // set datastructuretype
                    TaskManager.AddToBus(CreateTaskmanager.DATASTRUCTURE_TYPE, GetDataStructureType(model.SelectedDataStructureId));

                    //dataset is selected
                    if (model.SelectedDatasetId != 0 && model.SelectedDatasetId != -1)
                    {
                        if (datasetManager.IsDatasetCheckedIn(model.SelectedDatasetId))
                        {
                            DatasetVersion datasetVersion = datasetManager.GetDatasetLatestVersion(model.SelectedDatasetId);
                            TaskManager.AddToBus(CreateTaskmanager.RESEARCHPLAN_ID,
                                                 datasetVersion.Dataset.ResearchPlan.Id);
                            TaskManager.AddToBus(CreateTaskmanager.ENTITY_TITLE,
                                                 xmlDatasetHelper.GetInformationFromVersion(datasetVersion.Id, NameAttributeValues.title));

                            // set datastructuretype
                            TaskManager.AddToBus(CreateTaskmanager.DATASTRUCTURE_TYPE,
                                                 GetDataStructureType(model.SelectedDataStructureId));

                            // set MetadataXml From selected existing Dataset
                            XDocument metadata = XmlUtility.ToXDocument(datasetVersion.Metadata);
                            SetXml(metadata);
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Dataset is just in processing");
                        }
                    }
                    else
                    {
                        ResearchPlanManager rpm = new ResearchPlanManager();
                        TaskManager.AddToBus(CreateTaskmanager.RESEARCHPLAN_ID, rpm.Repo.Get().First().Id);
                    }

                    return(RedirectToAction("StartMetadataEditor", "Form"));
                }

                return(View("Index", model));
            }
            finally
            {
                datasetManager.Dispose();
            }
        }
        /// <summary>
        /// ReLoad the createDataset action with different parameter type options
        /// type eg ("DataStructureId", "DatasetId", "MetadataStructureId")
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult ReloadIndex(long id = -1, string type = "")
        {
            ViewBag.Title = PresentationModel.GetViewTitleForTenant("...", this.Session.GetTenant());

            if (TaskManager == null)
            {
                TaskManager = (CreateTaskmanager)Session["CreateDatasetTaskmanager"];
            }
            DatasetManager datasetManager = new DatasetManager();
            SetupModel     Model          = GetDefaultModel();

            //if id is set and its type dataset
            if (id != -1 && type.ToLower().Equals("datasetid"))
            {
                Dataset dataset = this.GetUnitOfWork().GetReadOnlyRepository <Dataset>().Get(id);
                Model.SelectedDatasetId           = id;
                Model.SelectedMetadataStructureId = dataset.MetadataStructure.Id;
                Model.SelectedDataStructureId     = dataset.DataStructure.Id;
                Model.BlockMetadataStructureId    = true;
                Model.BlockDatasetId = false;

                TaskManager.AddToBus(CreateTaskmanager.COPY_OF_ENTITY_ID, id);
            }

            if (id != -1 && type.ToLower().Equals("metadatastructureid"))
            {
                TaskManager.AddToBus(CreateTaskmanager.METADATASTRUCTURE_ID, id);
                Model.SelectedMetadataStructureId = id;

                if (TaskManager.Bus.ContainsKey(CreateTaskmanager.DATASTRUCTURE_ID))
                {
                    Model.SelectedDataStructureId = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.DATASTRUCTURE_ID]);
                }

                if (TaskManager.Bus.ContainsKey(CreateTaskmanager.COPY_OF_ENTITY_ID))
                {
                    Model.SelectedDatasetId = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.COPY_OF_ENTITY_ID]);

                    Dataset dataset = this.GetUnitOfWork().GetReadOnlyRepository <Dataset>().Get(id);
                    Model.BlockMetadataStructureId = true;
                    Model.BlockDatasetId           = false;
                }
            }

            if (id != -1 && type.ToLower().Equals("datastructureid"))
            {
                TaskManager.AddToBus(CreateTaskmanager.DATASTRUCTURE_ID, id);
                Model.SelectedDataStructureId = id;

                if (TaskManager.Bus.ContainsKey(CreateTaskmanager.METADATASTRUCTURE_ID))
                {
                    Model.SelectedMetadataStructureId = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.METADATASTRUCTURE_ID]);
                }

                if (TaskManager.Bus.ContainsKey(CreateTaskmanager.COPY_OF_ENTITY_ID))
                {
                    Model.SelectedDatasetId = Convert.ToInt64(TaskManager.Bus[CreateTaskmanager.COPY_OF_ENTITY_ID]);

                    Dataset dataset = this.GetUnitOfWork().GetReadOnlyRepository <Dataset>().Get(id);
                    Model.BlockMetadataStructureId = true;
                    Model.BlockDatasetId           = false;
                }
            }

            return(View("Index", Model));
        }