예제 #1
0
        public void AddRightToEntityPermission(long subjectId, long entityId, long instanceId, int rightType)
        {
            var entityPermissionManager = new EntityPermissionManager();

            try
            {
                var entityPermission = entityPermissionManager.Find(subjectId, entityId, instanceId);

                if (entityPermission == null)
                {
                    entityPermissionManager.Create(subjectId, entityId, instanceId, rightType);
                }
                else
                {
                    if ((entityPermission.Rights & rightType) != 0)
                    {
                        return;
                    }
                    entityPermission.Rights += rightType;
                    entityPermissionManager.Update(entityPermission);
                }
            }
            finally
            {
                entityPermissionManager.Dispose();
            }
        }
        public void AddInstanceToPublic(long entityId, long instanceId)
        {
            var entityPermissionManager = new EntityPermissionManager();

            try
            {
                var entityPermission = entityPermissionManager.Find(null, entityId, instanceId);

                if (entityPermission == null)
                {
                    entityPermissionManager.Create(null, entityId, instanceId, (int)RightType.Read);

                    if (this.IsAccessible("DDM", "SearchIndex", "ReIndexSingle"))
                    {
                        var x = this.Run("DDM", "SearchIndex", "ReIndexSingle", new RouteValueDictionary()
                        {
                            { "id", instanceId }
                        });
                    }
                }
            }
            finally
            {
                entityPermissionManager.Dispose();
            }
        }
        public JsonResult Submit(bool valid)
        {
            // create and submit Dataset
            using (var createDatasetController = new CreateDatasetController())
            {
                try
                {
                    // how to hold the seesion: https://stackoverflow.com/questions/31388357/session-is-null-when-calling-method-from-one-controller-to-another-mvc
                    createDatasetController.ControllerContext = new ControllerContext(this.Request.RequestContext, createDatasetController);
                    long datasetId = createDatasetController.SubmitDataset(valid, "Publication");

                    //get groups from setting file
                    var adminGroup     = Helper.Settings.get("adminGroup").ToString();
                    var pubAdminGroup  = Helper.Settings.get("pubAdminGroup").ToString();
                    var pubInternGroup = Helper.Settings.get("pubInternGroup").ToString();


                    using (EntityPermissionManager entityPermissionManager = new EntityPermissionManager())
                    {
                        if (!String.IsNullOrEmpty(adminGroup))
                        {
                            entityPermissionManager.Create <Group>("administrator", "Publication", typeof(Dataset), datasetId, Enum.GetValues(typeof(RightType)).Cast <RightType>().ToList());
                        }
                        if (!String.IsNullOrEmpty(pubAdminGroup))
                        {
                            entityPermissionManager.Create <Group>("publicationAdmin", "Publication", typeof(Dataset), datasetId, new List <RightType>()
                            {
                                RightType.Read, RightType.Write, RightType.Delete
                            });
                        }
                        if (!String.IsNullOrEmpty(pubInternGroup))
                        {
                            entityPermissionManager.Create <Group>("1_publicationIntern", "Publication", typeof(Dataset), datasetId, new List <RightType>()
                            {
                                RightType.Read
                            });
                        }
                    }

                    return(Json(new { result = "redirect", url = Url.Action("Index", "UploadPublication", new { area = "Pub", entityId = datasetId }) }, JsonRequestBehavior.AllowGet));
                }
                catch (Exception ex)
                {
                    return(Json(new { result = "error", message = ex.Message }, JsonRequestBehavior.AllowGet));
                }
            }
        }
예제 #4
0
        public void AddInstanceToPublic(long entityId, long instanceId)
        {
            var entityPermissionManager = new EntityPermissionManager();

            try
            {
                var entityPermission = entityPermissionManager.Find(null, entityId, instanceId);

                if (entityPermission == null)
                {
                    entityPermissionManager.Create(null, entityId, instanceId, (int)RightType.Read);
                }
            }
            finally
            {
                entityPermissionManager.Dispose();
            }
        }
        public ActionResult Create(CreateResourceStructureModel model)
        {
            using (ResourceStructureManager rsManager = new ResourceStructureManager())
                using (var pManager = new EntityPermissionManager())
                    using (var entityTypeManager = new EntityManager())
                        using (UserManager userManager = new UserManager())
                        {
                            //check name
                            ResourceStructure temp = rsManager.GetResourceStructureByName(StringHelper.CutSpaces(model.Name));
                            if (temp != null)
                            {
                                ModelState.AddModelError("NameExist", "Name already exist");
                            }

                            if (ModelState.IsValid)
                            {
                                ResourceStructure rS = rsManager.Create(model.Name, model.Description, null, null);

                                //Start -> add security ----------------------------------------
                                var userTask = userManager.FindByNameAsync(HttpContext.User.Identity.Name);
                                userTask.Wait();
                                var user = userTask.Result;

                                Entity entityType = entityTypeManager.FindByName("ResourceStructure");

                                //31 is the sum from all rights:  Read = 1, Write = 4, Delete = 8, Grant = 16
                                int rights = (int)RightType.Read + (int)RightType.Write + (int)RightType.Delete + (int)RightType.Grant;
                                pManager.Create(user, entityType, rS.Id, rights);


                                //End -> add security ------------------------------------------


                                ResourceStructureModel rSmodel = new ResourceStructureModel(rS);
                                rSmodel.FirstCreated = true;
                                return(View("_editResourceStructure", rSmodel));
                            }

                            else
                            {
                                return(View("_createResourceStructure", model));
                            }
                        }
        }
        // [HttpPost]
        public ActionResult Create(ActivityModel model)
        {
            using (ActivityManager aManager = new ActivityManager())
            {
                // check name
                Activity temp = aManager.GetActivityByName(StringHelper.CutSpaces(model.Name));
                if (temp != null)
                {
                    ModelState.AddModelError("NameExist", "Name already exist");
                }

                if (ModelState.IsValid)
                {
                    Activity a = aManager.CreateActivity(model.Name, model.Description, model.Disable);

                    // Start -> add security ----------------------------------------
                    using (EntityPermissionManager pManager = new EntityPermissionManager())
                        using (SubjectManager subManager = new SubjectManager())
                            using (var entityTypeManager = new EntityManager())
                                using (UserManager userManager = new UserManager())
                                {
                                    var userTask = userManager.FindByNameAsync(HttpContext.User.Identity.Name);
                                    userTask.Wait();
                                    var user = userTask.Result;

                                    Entity entityType = entityTypeManager.FindByName("Activity");

                                    // 31 is the sum from all rights:  Read = 1, Write = 4, Delete = 8, Grant = 16
                                    int rights = (int)RightType.Read + (int)RightType.Write + (int)RightType.Delete + (int)RightType.Grant;
                                    pManager.Create(user, entityType, a.Id, rights);

                                    // End -> add security ------------------------------------------
                                }

                    // return View("ActivityManager");
                    return(Json(new { success = true }));
                }
                else
                {
                    return(PartialView("_createActivity", model));
                }
            }
        }
예제 #7
0
        public HttpResponseMessage Post([FromBody] PostApiDatasetModel dataset)
        {
            var    request        = Request.CreateResponse();
            User   user           = null;
            string error          = "";
            long   datasetId      = 0;
            long   researchPlanId = 1;

            using (DatasetManager datasetManager = new DatasetManager())
                using (DataStructureManager dataStructureManager = new DataStructureManager())
                    using (ResearchPlanManager researchPlanManager = new ResearchPlanManager())
                        using (UserManager userManager = new UserManager())
                            using (EntityPermissionManager entityPermissionManager = new EntityPermissionManager())
                                using (MetadataStructureManager metadataStructureManager = new MetadataStructureManager())
                                {
                                    try
                                    {
                                        #region security

                                        string token = this.Request.Headers.Authorization?.Parameter;

                                        if (String.IsNullOrEmpty(token))
                                        {
                                            request.Content = new StringContent("Bearer token not exist.");

                                            return(request);
                                        }

                                        user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault();

                                        if (user == null)
                                        {
                                            request.Content = new StringContent("Token is not valid.");

                                            return(request);
                                        }

                                        #endregion security

                                        #region incomming values check

                                        // check incomming values
                                        if (dataset.Title == null)
                                        {
                                            error += "title not existing.";
                                        }
                                        if (dataset.Description == null)
                                        {
                                            error += "description not existing.";
                                        }
                                        if (dataset.MetadataStructureId == 0)
                                        {
                                            error += "metadata structure id should not be null. ";
                                        }
                                        if (dataset.DataStructureId == 0)
                                        {
                                            error += "datastructure id should not be null. ";
                                        }

                                        if (!string.IsNullOrEmpty(error))
                                        {
                                            request.Content = new StringContent(error);

                                            return(request);
                                        }

                                        #endregion incomming values check

                                        #region create dataset

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

                                        if (dataStructure == null)
                                        {
                                            request.Content = new StringContent("A data structure with id " + dataset.DataStructureId + "does not exist.");
                                            return(request);
                                        }

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

                                        if (rp == null)
                                        {
                                            request.Content = new StringContent("A research plan with id " + researchPlanId + "does not exist.");
                                            return(request);
                                        }

                                        MetadataStructure metadataStructure = metadataStructureManager.Repo.Get(dataset.MetadataStructureId);

                                        if (metadataStructure == null)
                                        {
                                            request.Content = new StringContent("A metadata structure with id " + dataset.MetadataStructureId + "does not exist.");
                                            return(request);
                                        }

                                        var newDataset = datasetManager.CreateEmptyDataset(dataStructure, rp, metadataStructure);
                                        datasetId = newDataset.Id;

                                        // add security
                                        entityPermissionManager.Create <User>(user.UserName, "Dataset", typeof(Dataset), newDataset.Id, Enum.GetValues(typeof(RightType)).Cast <RightType>().ToList());

                                        //add title and description to the metadata

                                        if (datasetManager.IsDatasetCheckedOutFor(datasetId, user.UserName) || datasetManager.CheckOutDataset(datasetId, user.UserName))
                                        {
                                            DatasetVersion workingCopy = datasetManager.GetDatasetWorkingCopy(datasetId);

                                            XmlMetadataWriter xmlMetadataWriter = new XmlMetadataWriter(XmlNodeMode.xPath);
                                            XDocument         xdoc = xmlMetadataWriter.CreateMetadataXml(dataset.MetadataStructureId);
                                            workingCopy.Metadata = XmlUtility.ToXmlDocument(xdoc);
                                            XmlDatasetHelper xmlDatasetHelper = new XmlDatasetHelper();
                                            workingCopy.Metadata    = xmlDatasetHelper.SetInformation(workingCopy, workingCopy.Metadata, NameAttributeValues.title, dataset.Title);
                                            workingCopy.Title       = dataset.Title;
                                            workingCopy.Metadata    = xmlDatasetHelper.SetInformation(workingCopy, workingCopy.Metadata, NameAttributeValues.description, dataset.Description);
                                            workingCopy.Description = dataset.Description;


                                            ////set modification
                                            workingCopy.ModificationInfo = new EntityAuditInfo()
                                            {
                                                Performer  = user.UserName,
                                                Comment    = "Metadata",
                                                ActionType = AuditActionType.Create
                                            };

                                            datasetManager.EditDatasetVersion(workingCopy, null, null, null);
                                            datasetManager.CheckInDataset(datasetId, "Title and description were added to the dataset via the api.", user.UserName, ViewCreationBehavior.None);
                                        }

                                        request.Content = new StringContent("the dataset " + dataset.Title + "(" + datasetId + ") was successfully created.");
                                        return(request);

                                        #endregion create dataset
                                    }
                                    catch (Exception ex)
                                    {
                                        request.Content = new StringContent(ex.Message);
                                        return(request);
                                    }
                                }
        }
        //[MeasurePerformance]
        //temporary solution: norman
        //For original solution, look into Aquadiva Code
        public List <Error> FinishUpload(EasyUploadTaskManager taskManager)
        {
            DataStructureManager dsm = new DataStructureManager();
            DatasetManager       dm  = new DatasetManager();
            DataContainerManager dam = new DataContainerManager();
            //SubjectManager sm = new SubjectManager();
            EntityPermissionManager entityPermissionManager = new EntityPermissionManager();

            List <Error> temp = new List <Error>();

            try
            {
                using (IUnitOfWork unitOfWork = this.GetUnitOfWork())
                {
                    // initialize all necessary manager

                    DataTuple[] rows = null;

                    //First, try to validate - if there are errors, return immediately
                    string       JsonArray        = TaskManager.Bus[EasyUploadTaskManager.SHEET_JSON_DATA].ToString();
                    List <Error> ValidationErrors = ValidateRows(JsonArray);
                    if (ValidationErrors.Count != 0)
                    {
                        temp.AddRange(ValidationErrors);
                        return(temp);
                    }

                    string timestamp = DateTime.UtcNow.ToString("r");
                    string title     = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.FILENAME]);

                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.DESCRIPTIONTITLE))
                    {
                        string tmp = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.DESCRIPTIONTITLE]);
                        if (!String.IsNullOrWhiteSpace(tmp))
                        {
                            title = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.DESCRIPTIONTITLE]);
                        }
                    }

                    StructuredDataStructure   sds         = null;
                    List <VariableIdentifier> identifiers = new List <VariableIdentifier>(); //Used in Excel reader
                    //Try to find an exact matching datastructure
                    Boolean foundReusableDataStructure = false;

                    List <RowModel> headers = (List <RowModel>)TaskManager.Bus[EasyUploadTaskManager.ROWS];

                    //For some reason, MappedHeaders might be in a different order in this list than what's indicated by its IDs - to prevent mismatching, sort the headers
                    headers.Sort((m1, m2) => m1.Index.CompareTo(m2.Index));

                    List <StructuredDataStructure> allDatastructures = dsm.StructuredDataStructureRepo.Get().ToList();
                    foreach (StructuredDataStructure existingStructure in allDatastructures)
                    {
                        if (!foundReusableDataStructure)
                        {
                            //For now a datastructure is considered an exact match if it contains variables with
                            //the same names (labels), datatypes and units in the correct order
                            List <Variable> variablesOfExistingStructure = existingStructure.Variables.ToList();
                            foundReusableDataStructure = true;
                            if (variablesOfExistingStructure.Count != headers.Count)
                            {
                                foundReusableDataStructure = false;
                            }
                            else
                            {
                                for (int i = 0; i < variablesOfExistingStructure.Count; i++)
                                {
                                    Variable exVar         = variablesOfExistingStructure.ElementAt(i);
                                    RowModel currentHeader = headers.ElementAt(i);
                                    if (exVar.Label != currentHeader.Name ||
                                        exVar.Unit.Id != currentHeader.SelectedUnit.UnitId ||
                                        exVar.DataAttribute.DataType.Id != currentHeader.SelectedDataType.DataTypeId)
                                    {
                                        foundReusableDataStructure = false;
                                    }
                                }
                            }
                            if (foundReusableDataStructure)
                            {
                                sds = existingStructure;
                                foreach (Variable exVar in variablesOfExistingStructure)
                                {
                                    VariableIdentifier vi = new VariableIdentifier
                                    {
                                        name = exVar.Label,
                                        id   = exVar.Id
                                    };
                                    identifiers.Add(vi);
                                }
                            }
                        }
                    }

                    if (!foundReusableDataStructure)
                    {
                        sds = dsm.CreateStructuredDataStructure(title, title + " " + timestamp, "", "", DataStructureCategory.Generic);
                    }

                    TaskManager.AddToBus(EasyUploadTaskManager.DATASTRUCTURE_ID, sds.Id);
                    TaskManager.AddToBus(EasyUploadTaskManager.DATASTRUCTURE_TITLE, title + " " + timestamp);

                    if (!TaskManager.Bus.ContainsKey(EasyUploadTaskManager.DATASET_TITLE))
                    {
                        TaskManager.AddToBus(EasyUploadTaskManager.DATASET_TITLE, title);
                        TaskManager.AddToBus(EasyUploadTaskManager.TITLE, title);
                    }

                    MetadataStructure metadataStructure = null;
                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.SCHEMA))
                    {
                        long metadataStructureId = Convert.ToInt64(TaskManager.Bus[EasyUploadTaskManager.SCHEMA]);
                        metadataStructure = unitOfWork.GetReadOnlyRepository <MetadataStructure>()
                                            .Get(m => m.Id == metadataStructureId).FirstOrDefault();
                    }
                    else
                    {
                        //Default option but shouldn't happen because previous steps can't be finished without selecting the metadata-structure
                        metadataStructure = unitOfWork.GetReadOnlyRepository <MetadataStructure>()
                                            .Get(m => m.Name.ToLower().Contains("eml")).FirstOrDefault();
                    }
                    ResearchPlan rp = unitOfWork.GetReadOnlyRepository <ResearchPlan>().Get().FirstOrDefault();
                    TaskManager.AddToBus(EasyUploadTaskManager.RESEARCHPLAN_ID, rp.Id);
                    TaskManager.AddToBus(EasyUploadTaskManager.RESEARCHPLAN_TITLE, rp.Title);

                    #region Progress Information

                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.CURRENTPACKAGESIZE))
                    {
                        TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGESIZE] = 0;
                    }
                    else
                    {
                        TaskManager.Bus.Add(EasyUploadTaskManager.CURRENTPACKAGESIZE, 0);
                    }

                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.CURRENTPACKAGE))
                    {
                        TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGE] = 0;
                    }
                    else
                    {
                        TaskManager.Bus.Add(EasyUploadTaskManager.CURRENTPACKAGE, 0);
                    }

                    #endregion Progress Information

                    if (!foundReusableDataStructure)
                    {
                        #region Set Variables and information for new DataStructure

                        XmlDocument xmldoc       = new XmlDocument();
                        XmlElement  extraElement = xmldoc.CreateElement("extra");
                        XmlElement  orderElement = xmldoc.CreateElement("order");

                        //Sorting necessary to prevent problems when inserting the tuples
                        headers.OrderBy(r => r.Index);

                        var dataTypeRepo      = unitOfWork.GetReadOnlyRepository <DataType>();
                        var unitRepo          = unitOfWork.GetReadOnlyRepository <Unit>();
                        var dataAttributeRepo = unitOfWork.GetReadOnlyRepository <DataAttribute>();

                        List <DataAttribute> allDataAttributes = dataAttributeRepo.Get().ToList();

                        foreach (RowModel header in headers)
                        {
                            int i = headers.IndexOf(header);

                            DataType dataType            = dataTypeRepo.Get(header.SelectedDataType.DataTypeId);
                            Unit     CurrentSelectedUnit = unitRepo.Get(header.SelectedUnit.UnitId);

                            DataAttribute CurrentDataAttribute = new DataAttribute();
                            //If possible, map the chosen variable name, unit and datatype to an existing DataAttribute (Exact match)
                            DataAttribute existingDataAttribute = allDataAttributes.Where(da => da.Name.ToLower().Equals(TrimAndLimitString(header.SelectedDataAttribute.Name).ToLower()) &&
                                                                                          da.Unit.Dimension == CurrentSelectedUnit.Dimension).FirstOrDefault();
                            if (existingDataAttribute != null)
                            {
                                CurrentDataAttribute = existingDataAttribute;
                            }
                            else
                            {
                                //No matching DataAttribute => Create a new one
                                CurrentDataAttribute = dam.CreateDataAttribute(TrimAndLimitString(header.Name), header.Name, header.SelectedDataAttribute.Description, false, false, "", MeasurementScale.Categorial, DataContainerType.ReferenceType, "", dataType, CurrentSelectedUnit, null, null, null, null, null, null);
                            }

                            Variable           newVariable = dsm.AddVariableUsage(sds, CurrentDataAttribute, true, header.Name, "", "", "", CurrentSelectedUnit);
                            VariableIdentifier vi          = new VariableIdentifier
                            {
                                name = newVariable.Label,
                                id   = newVariable.Id
                            };
                            identifiers.Add(vi);

                            XmlElement newVariableXml = xmldoc.CreateElement("variable");
                            newVariableXml.InnerText = Convert.ToString(newVariable.Id);

                            orderElement.AppendChild(newVariableXml);
                        }
                        extraElement.AppendChild(orderElement);
                        xmldoc.AppendChild(extraElement);

                        sds.Extra       = xmldoc;
                        sds.Name        = "generated import structure " + timestamp;
                        sds.Description = "automatically generated structured data structure by user " + GetUsernameOrDefault() + " for file " + title + " on " + timestamp;

                        #endregion Set Variables and information for new DataStructure
                    }

                    Dataset ds = null;
                    ds = dm.CreateEmptyDataset(sds, rp, metadataStructure);

                    long datasetId = ds.Id;
                    long sdsId     = sds.Id;

                    if (dm.IsDatasetCheckedOutFor(datasetId, GetUsernameOrDefault()) || dm.CheckOutDataset(datasetId, GetUsernameOrDefault()))
                    {
                        DatasetVersion    dsv = dm.GetDatasetWorkingCopy(datasetId);
                        long              METADATASTRUCTURE_ID = metadataStructure.Id;
                        XmlMetadataWriter xmlMetadatWriter     = new XmlMetadataWriter(XmlNodeMode.xPath);
                        XDocument         metadataX            = xmlMetadatWriter.CreateMetadataXml(METADATASTRUCTURE_ID);
                        XmlDocument       metadataXml          = XmlMetadataWriter.ToXmlDocument(metadataX);
                        dsv.Metadata = metadataXml;
                        try
                        {
                            dsv.Metadata = xmlDatasetHelper.SetInformation(dsv, metadataXml, NameAttributeValues.title, title);
                            dsv.Title    = title;
                        }
                        catch (NullReferenceException ex)
                        {
                            //Reference of the title node is missing
                            throw new NullReferenceException("The extra-field of this metadata-structure is missing the title-node-reference!");
                        }
                        dm.EditDatasetVersion(dsv, null, null, null);
                    }

                    #region security

                    // add security
                    if (GetUsernameOrDefault() != "DEFAULT")
                    {
                        foreach (RightType rightType in Enum.GetValues(typeof(RightType)).Cast <RightType>())
                        {
                            //The user gets full permissions
                            // add security
                            if (GetUsernameOrDefault() != "DEFAULT")
                            {
                                entityPermissionManager.Create <User>(GetUsernameOrDefault(), "Dataset", typeof(Dataset), ds.Id, Enum.GetValues(typeof(RightType)).Cast <RightType>().ToList());
                            }
                        }
                    }

                    #endregion security

                    #region excel reader

                    int packageSize  = 100000;
                    int numberOfRows = 0;
                    //HACK ?
                    TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGESIZE] = packageSize;

                    int counter = 0;

                    dm.CheckOutDatasetIfNot(ds.Id, GetUsernameOrDefault()); // there are cases, the dataset does not get checked out!!
                    if (!dm.IsDatasetCheckedOutFor(ds.Id, GetUsernameOrDefault()))
                    {
                        throw new Exception(string.Format("Not able to checkout dataset '{0}' for  user '{1}'!", ds.Id, GetUsernameOrDefault()));
                    }

                    DatasetVersion workingCopy = dm.GetDatasetWorkingCopy(ds.Id);

                    counter++;
                    TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGE] = counter;

                    //rows = reader.ReadFile(Stream, TaskManager.Bus[TaskManager.FILENAME].ToString(), oldSds, (int)id, packageSize).ToArray();

                    List <string> selectedDataAreaJsonArray   = (List <string>)TaskManager.Bus[EasyUploadTaskManager.SHEET_DATA_AREA];
                    string        selectedHeaderAreaJsonArray = TaskManager.Bus[EasyUploadTaskManager.SHEET_HEADER_AREA].ToString();
                    List <int[]>  areaDataValuesList          = new List <int[]>();
                    foreach (string area in selectedDataAreaJsonArray)
                    {
                        areaDataValuesList.Add(JsonConvert.DeserializeObject <int[]>(area));
                    }
                    int[] areaHeaderValues = JsonConvert.DeserializeObject <int[]>(selectedHeaderAreaJsonArray);

                    Orientation orientation = 0;

                    switch (TaskManager.Bus[EasyUploadTaskManager.SHEET_FORMAT].ToString())
                    {
                    case "LeftRight":
                        orientation = Orientation.rowwise;
                        break;

                    case "Matrix":
                        //orientation = Orientation.matrix;
                        break;

                    default:
                        orientation = Orientation.columnwise;
                        break;
                    }

                    String worksheetUri = null;
                    //Get the Uri to identify the correct worksheet
                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.ACTIVE_WOKSHEET_URI))
                    {
                        worksheetUri = TaskManager.Bus[EasyUploadTaskManager.ACTIVE_WOKSHEET_URI].ToString();
                    }

                    int batchSize = (new Object()).GetUnitOfWork().PersistenceManager.PreferredPushSize;
                    int batchnr   = 1;
                    foreach (int[] areaDataValues in areaDataValuesList)
                    {
                        //First batch starts at the start of the current data area
                        int currentBatchStartRow = areaDataValues[0] + 1;
                        while (currentBatchStartRow <= areaDataValues[2] + 1) //While the end of the current data area has not yet been reached
                        {
                            //End row is start row plus batch size
                            int currentBatchEndRow = currentBatchStartRow + batchSize;

                            //Set the indices for the reader
                            EasyUploadFileReaderInfo fri = new EasyUploadFileReaderInfo
                            {
                                DataStartRow = currentBatchStartRow,
                                //End row is either at the end of the batch or the end of the marked area
                                //DataEndRow = (currentBatchEndRow > areaDataValues[2] + 1) ? areaDataValues[2] + 1 : currentBatchEndRow,
                                DataEndRow = Math.Min(currentBatchEndRow, areaDataValues[2] + 1),
                                //Column indices as marked in a previous step
                                DataStartColumn = areaDataValues[1] + 1,
                                DataEndColumn   = areaDataValues[3] + 1,

                                //Header area as marked in a previous step
                                VariablesStartRow    = areaHeaderValues[0] + 1,
                                VariablesStartColumn = areaHeaderValues[1] + 1,
                                VariablesEndRow      = areaHeaderValues[2] + 1,
                                VariablesEndColumn   = areaHeaderValues[3] + 1,

                                Offset      = areaDataValues[1],
                                Orientation = orientation
                            };
                            //Create a new reader each time because the reader saves ALL tuples it read and therefore the batch processing wouldn't work
                            EasyUploadExcelReader reader = new EasyUploadExcelReader(sds, fri);
                            // open file
                            Stream = reader.Open(TaskManager.Bus[EasyUploadTaskManager.FILEPATH].ToString());

                            //Set variable identifiers because they might differ from the variable names in the file
                            reader.setSubmittedVariableIdentifiers(identifiers);

                            //Read the rows and convert them to DataTuples
                            rows = reader.ReadFile(Stream, TaskManager.Bus[EasyUploadTaskManager.FILENAME].ToString(), fri, (int)datasetId, worksheetUri);

                            //After reading the rows, add them to the dataset
                            if (rows != null)
                            {
                                dm.EditDatasetVersion(workingCopy, rows.ToList(), null, null);
                                numberOfRows += rows.Count();
                            }

                            //Close the Stream so the next ExcelReader can open it again
                            Stream.Close();

                            //Debug information
                            int lines   = (areaDataValues[2] + 1) - (areaDataValues[0] + 1);
                            int batches = lines / batchSize;
                            batchnr++;

                            //Next batch starts after the current one
                            currentBatchStartRow = currentBatchEndRow + 1;
                        }
                    }

                    #endregion excel reader

                    //set modification
                    workingCopy.ModificationInfo = new EntityAuditInfo()
                    {
                        Performer  = GetUsernameOrDefault(),
                        Comment    = "Data",
                        ActionType = AuditActionType.Create
                    };

                    dm.EditDatasetVersion(workingCopy, null, null, null);

                    dm.CheckInDataset(ds.Id, "Import " + numberOfRows + " rows", GetUsernameOrDefault());

                    //Reindex search
                    if (this.IsAccessible("DDM", "SearchIndex", "ReIndexSingle"))
                    {
                        this.Run("DDM", "SearchIndex", "ReIndexSingle", new RouteValueDictionary()
                        {
                            { "id", datasetId }
                        });
                    }

                    TaskManager.AddToBus(EasyUploadTaskManager.DATASET_ID, ds.Id);

                    return(temp);
                }
            }
            catch (Exception ex)
            {
                temp.Add(new Error(ErrorType.Other, "An error occured during the upload. " +
                                   "Please try again later. If this problem keeps occuring, please contact your administrator."));
                return(temp);
            }
            finally
            {
                dsm.Dispose();
                dm.Dispose();
                dam.Dispose();
                //sm.Dispose();
                entityPermissionManager.Dispose();
            }
        }
예제 #9
0
        public void GenerateSeedData()
        {
            #region ENTITIES

            List <EntityStruct> entities = new List <EntityStruct>();
            entities.Add(new EntityStruct("SingleResource", typeof(SingleResource), typeof(BExIS.Rbm.Services.Resource.SingleResourceStore)));
            entities.Add(new EntityStruct("ResourceStructure", typeof(ResourceStructure), typeof(BExIS.Rbm.Services.ResourceStructure.ResourceStructureStore)));
            entities.Add(new EntityStruct("ResourceStructureAttribute", typeof(ResourceStructureAttribute), typeof(BExIS.Rbm.Services.ResourceStructure.ResourceStructureAttributeStore)));
            entities.Add(new EntityStruct("Activity", typeof(Activity), typeof(BExIS.Rbm.Services.Booking.ActivityStore)));
            entities.Add(new EntityStruct("BookingEvent", typeof(BookingEvent), typeof(BExIS.Rbm.Services.Booking.BookingEventStore)));
            entities.Add(new EntityStruct("Notification", typeof(Notification), typeof(BExIS.Rbm.Services.Booking.NotificationStore)));
            entities.Add(new EntityStruct("Schedule", typeof(Schedule), typeof(BExIS.Rbm.Services.Booking.ScheduleStore)));



            Dictionary <string, Type> rbmEntities = new Dictionary <string, Type>();
            rbmEntities.Add("SingleResource", typeof(SingleResource));
            rbmEntities.Add("ResourceStructure", typeof(ResourceStructure));
            rbmEntities.Add("ResourceStructureAttribute", typeof(ResourceStructureAttribute));
            rbmEntities.Add("Activity", typeof(Activity));
            rbmEntities.Add("BookingEvent", typeof(BookingEvent));
            rbmEntities.Add("Notification", typeof(Notification));
            rbmEntities.Add("Schedule", typeof(Schedule));

            using (var entityManager = new EntityManager())
            {
                foreach (var et in entities)
                {
                    Entity entity = entityManager.Entities.Where(e => e.Name.ToUpperInvariant() == et.Name.ToUpperInvariant()).FirstOrDefault();

                    if (entity == null)
                    {
                        entity                 = new Entity();
                        entity.Name            = et.Name;
                        entity.EntityType      = et.Type;
                        entity.EntityStoreType = et.StoreType;
                        //entity.UseMetadata = true;
                        entity.Securable = true;
                        entityManager.Create(entity);
                    }
                }
            }

            try
            {
                ResourceStructureAttribute rsa = new ResourceStructureAttribute();
                using (var rsaManager = new ResourceStructureAttributeManager())
                    rsa = rsaManager.CreateResourceStructureAttribute("Exploratory", "Biodiversity Exploratories funded by DFG Priority Programme 1374. They serve as open research platform for all biodiversity and ecosystem research groups of Germany.");

                var dcManager = new DataContainerManager();

                string[]          keys        = { "Hainich-Dün", "Schorfheide-Chorin", "Schwäbische Alb" };
                List <DomainItem> domainItems = CreateDomainItems(keys);
                DomainConstraint  dc          = new DomainConstraint(ConstraintProviderSource.Internal, "", "en-US", "a simple domain validation constraint", false, null, null, null, domainItems);
                dcManager.AddConstraint(dc, rsa);


                ResourceStructureAttribute rsa2 = new ResourceStructureAttribute();
                using (var rsaManager2 = new ResourceStructureAttributeManager())
                    rsa2 = rsaManager2.CreateResourceStructureAttribute("Type", "Type of resource.");

                var dcManager2 = new DataContainerManager();

                string[]          keys2        = { "Area", "Equipment", "Sleeping place" };
                List <DomainItem> domainItems2 = CreateDomainItems(keys2);
                DomainConstraint  dc2          = new DomainConstraint(ConstraintProviderSource.Internal, "", "en-US", "a simple domain validation constraint", false, null, null, null, domainItems2);
                dcManager2.AddConstraint(dc2, rsa2);

                ResourceStructureAttribute rsa3 = new ResourceStructureAttribute();
                using (var rsaManager3 = new ResourceStructureAttributeManager())
                    rsa3 = rsaManager3.CreateResourceStructureAttribute("Information File", "Important information as file");

                ResourceStructureManager rsManager = new ResourceStructureManager();;
                ResourceStructure        rs        = rsManager.Create("Explo resources", "Resources related to exploratories.", null, null);

                using (var rsaManager = new ResourceStructureAttributeManager())
                    rsaManager.CreateResourceAttributeUsage(rsa, rs, true, false);
                using (var rsaManager = new ResourceStructureAttributeManager())
                    rsaManager.CreateResourceAttributeUsage(rsa2, rs, true, false);

                using (var rsaManager = new ResourceStructureAttributeManager())
                    rsaManager.CreateResourceAttributeUsage(rsa3, rs, true, true);

                ActivityManager aManager = new ActivityManager();
                aManager.CreateActivity("Adding of material (litter, dead wood, chemicals ....)", "", false);
                aManager.CreateActivity("Adding of organisms (seeds and others)", "", false);
                aManager.CreateActivity("Conference", "", false);
                aManager.CreateActivity("Contact stakeholder", "", false);
                aManager.CreateActivity("Dismantling of experiments", "", false);
                aManager.CreateActivity("Installation of equipment remaining for some time", "", false);
                aManager.CreateActivity("Measuring and marking of subplots/experiments/study organisms", "", false);
                aManager.CreateActivity("Observation/capture of organisms without removal", "", false);
                aManager.CreateActivity("Plot maintenance", "", false);
                aManager.CreateActivity("Removal of org. material without killing", "", false);
                aManager.CreateActivity("Removal of organisms", "", false);
                aManager.CreateActivity("Removal of soil samples", "", false);
                aManager.CreateActivity("Visit without activity", "", false);

                ResourceManager             rManager = new ResourceManager();;
                List <newResourceStructure> rs_new   = new List <newResourceStructure>();

                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all EPs (SCH)", color = "#ec5959", description = "Visit of all forest EPs in Schorfheide-Chorin", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all MIPs (SCH)", color = "#ec5959", description = "Visit of all forest MIPs in Schorfheide-Chorin", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all VIPs (SCH)", color = "#ec5959", description = "Visit of all forest VIPs in Schorfheide-Chorin", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Altenhof", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Arnimswalde", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Chorin", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Eichheide", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Glambeck", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Liepe", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Maienpfuhl", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Melzow", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Poratz", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Ringenwalde", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Senftenthal", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Theerofen", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Voigtswiese", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - Forstgut Altkuenkendorf", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - Fuerstliche Forstverwaltung Oettingen-Spielberg", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - Stiftung Schorfheide-Chorin", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - FOX (SCH)", color = "#ec5959", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - RP/UP (SCH)", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - ABP Landwirtschaft Neugrimnitz GmbH", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AEVG Stegelitz-Flieth", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Agrargemeinschaft Greiffenberg GmbH", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all EPs (SCH)", color = "#ff0000", description = "Visit of all grassland EPs in Schorfheide-Chorin", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all MIPs (SCH)", color = "#ff0000", description = "Visit of all grassland MIPs in Schorfheide-Chorin", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all VIPs (SCH)", color = "#ff0000", description = "Visit of all grassland VIPs in Schorfheide-Chorin", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Gut Biesenbrow", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Ingolf Limber", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Lehrschaeferei Friedrichsfelde", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - LW-Betrieb Haferkamp", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Naturrind GmbH Boeckenberg", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Reiner Wegner", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Weidewirtschaft Liepe", color = "#ff0000", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "no plot visit (SCH)", color = "#e28f8f", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schorfheide-Chorin"
                });


                rs_new.Add(new newResourceStructure()
                {
                    name = "Sleeping place (SCH)", color = "#9c3939", description = "Sleeping places in Schorfheide-Chorin", duration = 1, quantity = 8, withActivity = false, resourceStructure = rs, type = "Sleeping place", explo = "Schorfheide-Chorin"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Drying cabinet (SCH)", color = "#940b0b", description = "Drying cabinet in Schorfheide-Chorin", duration = 1, quantity = 5, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Fridge (SCH)", color = "#940b0b", description = "Fridge in Schorfheide-Chorin", duration = 1, quantity = 2, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Freezer (SCH)", color = "#940b0b", description = "Freezer in Schorfheide-Chorin", duration = 1, quantity = 2, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Metal detector (Magna Trak 100) (SCH)", color = "#940b0b", description = "Metal detector (Magna Trak 100) in Schorfheide-Chorin", duration = 1, quantity = 1, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Binocular (SCH)", color = "#940b0b", description = "", duration = 1, quantity = 1, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Chest freezer (SCH)", color = "#940b0b", description = "", duration = 1, quantity = 1, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schorfheide-Chorin"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Helmet (SCH)", color = "#940b0b", description = "", duration = 1, quantity = 8, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schorfheide-Chorin"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all EPs (HAI)", color = "#8cca0d", description = "Visit of all forest EPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all GPs (HAI)", color = "#8cca0d", description = "Visit of all forestGPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all MIPs (HAI)", color = "#8cca0d", description = "Visit of all forest MIPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all VIPs (HAI)", color = "#8cca0d", description = "Visit of all forest VIPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - FOX (HAI)", color = "8cca0d", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Anrode", color = "#8cca0d", description = "Forest - district Anrode", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - city of Mühlhausen", color = "#8cca0d", description = "Forest - city of Mühlhausen", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Behringen", color = "#8cca0d", description = "Forest - district Behringen", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Geney", color = "#8cca0d", description = "Forest - district Geney", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Keula", color = "#8cca0d", description = "Forest - district Keula", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Langula", color = "#8cca0d", description = "Forest - district Langula", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Sollstedt", color = "#8cca0d", description = "Forest - district Sollstedt", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Zehnsberg", color = "#8cca0d", description = "Forest - district Zehnsberg", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - national park", color = "#8cca0d", description = "Forest - national park", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - national park Weberstedterholz (core zone)", color = "#8cca0d", description = "Forest - national park Weberstedterholz (core zone)", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - district Westerwald", color = "#8cca0d", description = "Forest - district Westerwald", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all GPs (HAI)", color = "#9acd32", description = "Visit of all grassland GPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all EPs (HAI)", color = "#9acd32", description = "Visit of all grassland EPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all MIPs (HAI)", color = "#9acd32", description = "Visit of all grassland MIPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all VIPs (HAI)", color = "#9acd32", description = "Visit of all grassland VIPs in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - RP/UP (HAI)", color = "9acd32", description = "Visit of all new landuse experiment plots in HAI (HEG1,2,3,6,14,15)", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });


                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Diedorf", color = "#9acd32", description = "Grassland - AG Diedorf", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Großenlupnitz", color = "#9acd32", description = "Grassland - AG Großenlupnitz", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Kirchheiligen", color = "#9acd32", description = "Grassland - AG Kirchheiligen", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Bollstedt", color = "#9acd32", description = "Grassland - AG Bollstedt", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Lengefeld", color = "#9acd32", description = "Grassland - AG Lengefeld", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Mülverstedt", color = "#9acd32", description = "Grassland - AG Mülverstedt", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Wartburgblick", color = "#9acd32", description = "Grassland - AG Wartburgblick", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG Wenigenlupnitz", color = "#9acd32", description = "Grassland - AG Wenigenlupnitz", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - AG-Struth-Eigenrieden", color = "#9acd32", description = "Grassland - AG-Struth-Eigenrieden", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - BEAG/TOA", color = "#9acd32", description = "Grassland - BEAG/TOA", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Bundesforst Dörnaerplatz", color = "#9acd32", description = "Grassland - Bundesforst Dörnaerplatz", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Gut Sambach", color = "#9acd32", description = "Grassland - Gut Sambach", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Thüringen Wagyu Becker&Becker", color = "#9acd32", description = "Grassland - Thüringen Wagyu Becker&Becker", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Heller", color = "#9acd32", description = "Grassland - Heller", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Schaeferei Effenberger", color = "#9acd32", description = "Grassland - Schaeferei Effenberger", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Nationalpark", color = "#9acd32", description = "Grassland - Nationalpark", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Nordagrar (Naturrind Unstruttal)", color = "#9acd32", description = "Grassland - Nordagrar (Naturrind Unstruttal)", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Schaeferei Goepfert", color = "#9acd32", description = "Grassland - Schaeferei Goepfert", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Börner", color = "#9acd32", description = "Grassland - Börner", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - Strewe-Winterberg", color = "#9acd32", description = "Grassland - Strewe-Winterberg", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - TUPAG (Hainich Weiderind)", color = "#9acd32", description = "Grassland - TUPAG (Hainich Weiderind)", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "no plot visit", color = "#a9fb00", description = "No plot visit in Hainich-Dün", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Hainich-Dün"
                });


                rs_new.Add(new newResourceStructure()
                {
                    name = "Sleeping place (HAI)", color = "#78ab0f", description = "Sleeping place in Hainich-Dün", duration = 1, quantity = 8, withActivity = false, resourceStructure = rs, type = "Sleeping place", explo = "Hainich-Dün"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Drying cabinet (HAI)", color = "#6a8a27", description = "Drying cabinete in Hainich-Dün", duration = 1, quantity = 4, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Fridge (HAI)", color = "#6a8a27", description = "Fridge in Hainich-Dün", duration = 1, quantity = 2, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Freezer (HAI)", color = "#6a8a27", description = "Freezer in Hainich-Dün", duration = 1, quantity = 3, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Metal detector (Magna Trak 100) (HAI)", color = "#6a8a27", description = "Metal detector (Magna Trak 100) in Hainich-Dün", duration = 1, quantity = 1, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Hainich-Dün"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Metal detector (Garrett ACE  150) (HAI)", color = "#6a8a27", description = "Metal detector (Garrett ACE  150) in Hainich-Dün", duration = 1, quantity = 1, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Hainich-Dün"
                });


                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - all EPs (ALB)", color = "#3a75e0", description = "Visit of all forest EPs in Schwäbische Alb", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - VIP AEW1-8 (ALB)", color = "#3a75e0", description = "Visit of all VIP AEW1-8 in Schwäbische Alb", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - VIP AEW9 (Alb)", color = "#3a75e0", description = "Visit of all VIP AEW9 in Schwäbische Alb", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Forest - FOX (ALB)", color = "#3a75e0", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });


                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all EPs excluding former military training area", color = "#6495ed", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all EPs including former military training area", color = "#6495ed", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - all VIPs (ALB)", color = "#6495ed", description = "Visit of all grassland VIPs in Schwäbische Alb", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Grassland - RP/UP (ALB)", color = "#6495ed", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });


                rs_new.Add(new newResourceStructure()
                {
                    name = "no plot visit (ALB)", color = "#0057f5", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "total Exploratory outside EP", color = "#0057f6", description = "", duration = 1, quantity = 0, withActivity = true, resourceStructure = rs, type = "Area", explo = "Schwäbische Alb"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Sleeping place (ALB)", color = "#27509a", description = "Sleeping places in Schwäbische Alb", duration = 1, quantity = 8, withActivity = false, resourceStructure = rs, type = "Sleeping place", explo = "Schwäbische Alb"
                });

                rs_new.Add(new newResourceStructure()
                {
                    name = "Drying cabinet (ALB)", color = "#7e95bf", description = "Drying cabinet in Schwäbische Alb", duration = 1, quantity = 5, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Binocular (ALB)", color = "#7e95bf", description = "", duration = 1, quantity = 1, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schwäbische Alb"
                });
                rs_new.Add(new newResourceStructure()
                {
                    name = "Metal detector (Magna Trak 100) (ALB)", color = "#7e95bf", description = "Metal detector (Magna Trak 100) in Schwäbische Alb", duration = 1, quantity = 1, withActivity = false, resourceStructure = rs, type = "Equipment", explo = "Schwäbische Alb"
                });

                //get/create admin group for entity rights
                using (var groupManager = new GroupManager())
                    using (var permissionManager = new EntityPermissionManager())
                        using (var entityManager = new EntityManager())
                            using (var valueManager = new ResourceStructureAttributeManager())
                            {
                                var adminGroup = groupManager.Groups.Where(r => r.Name == "administrator").FirstOrDefault();
                                if (adminGroup == null)
                                {
                                    // create new group
                                    adminGroup = new Group
                                    {
                                        Name          = "administrator",
                                        Description   = "administrator",
                                        DisplayName   = "administrator",
                                        IsSystemGroup = false,
                                        IsValid       = true
                                    };

                                    groupManager.CreateAsync(adminGroup).Wait();
                                }

                                //create right type
                                int rights = (int)RightType.Read + (int)RightType.Write + (int)RightType.Delete + (int)RightType.Grant;

                                foreach (newResourceStructure rs_item in rs_new)
                                {
                                    var duration = new TimeDuration();
                                    duration.Value = rs_item.duration;
                                    var resource = rManager.CreateResource(rs_item.name, rs_item.description, rs_item.quantity, rs_item.color, rs_item.withActivity, rs_item.resourceStructure, duration);

                                    //add entity rights
                                    permissionManager.Create(adminGroup,
                                                             entityManager.FindByName("SingleResource"),
                                                             resource.Id,
                                                             rights
                                                             );

                                    ResourceAttributeUsage usage = valueManager.GetResourceAttributeUsageById(1);
                                    valueManager.CreateResourceAttributeValue(rs_item.explo, rManager.GetResourceById(resource.Id), usage);
                                    ResourceAttributeUsage usage2 = valueManager.GetResourceAttributeUsageById(2);
                                    valueManager.CreateResourceAttributeValue(rs_item.type, rManager.GetResourceById(resource.Id), usage2);
                                }
                            }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
            #endregion

            #region SECURITY

            OperationManager operationManager = new OperationManager();
            FeatureManager   featureManager   = new FeatureManager();

            try
            {
                List <Feature> features = featureManager.FeatureRepository.Get().ToList();

                Feature ResourceBooking = features.FirstOrDefault(f => f.Name.Equals("Resource Booking"));
                if (ResourceBooking == null)
                {
                    ResourceBooking = featureManager.Create("Resource Booking", "Resource Booking");
                }

                Feature NotificationBlackboard = features.FirstOrDefault(f => f.Name.Equals("Notification Blackboard"));
                if (NotificationBlackboard == null)
                {
                    NotificationBlackboard = featureManager.Create("Notification Blackboard", "Notification Blackboard", ResourceBooking);
                }


                Feature ResourceAdmin = features.FirstOrDefault(f => f.Name.Equals("Resource Administration"));
                if (ResourceAdmin == null)
                {
                    ResourceAdmin = featureManager.Create("Resource Administration", "Resource Administration");
                }

                Feature ResourceManagement = features.FirstOrDefault(f => f.Name.Equals("Resource Management"));
                if (ResourceManagement == null)
                {
                    ResourceManagement = featureManager.Create("Resource Management", "Resource Management", ResourceAdmin);
                }

                Feature ResourceStructureManagement = features.FirstOrDefault(f => f.Name.Equals("Resource Structure Management"));
                if (ResourceStructureManagement == null)
                {
                    ResourceStructureManagement = featureManager.Create("Resource Structure Management", "Resource Structure Management", ResourceAdmin);
                }

                Feature ResourceStructureAttributeManagement = features.FirstOrDefault(f => f.Name.Equals("Resource Structure Attribute Management"));
                if (ResourceStructureAttributeManagement == null)
                {
                    ResourceStructureAttributeManagement = featureManager.Create("Resource Structure Attribute Management", "Resource Structure Attribute Management", ResourceAdmin);
                }

                Feature NotificationManagement = features.FirstOrDefault(f => f.Name.Equals("Notification Management"));
                if (NotificationManagement == null)
                {
                    NotificationManagement = featureManager.Create("Notification Management", "Notification Management", ResourceAdmin);
                }

                Feature ActivityManagement = features.FirstOrDefault(f => f.Name.Equals("Activity Management"));
                if (ActivityManagement == null)
                {
                    ActivityManagement = featureManager.Create("Activity Management", "Activity Management", ResourceAdmin);
                }


                operationManager.Create("RBM", "Schedule", "*", ResourceBooking);
                operationManager.Create("RBM", "Calendar", "*", ResourceBooking);
                operationManager.Create("RBM", " NotificationBlackboard", "*", NotificationBlackboard);



                operationManager.Create("RBM", "Resource", "*", ResourceManagement);
                operationManager.Create("RBM", "ResourceStructure", "*", ResourceStructureManagement);
                operationManager.Create("RBM", "ResourceStructure", "*", ResourceStructureAttributeManagement);
                operationManager.Create("RBM", "Notification", "*", NotificationManagement);
                operationManager.Create("RBM", "Activity", "*", ActivityManagement);

                #region Help Workflow

                if (!operationManager.Exists("RBM", "help", "*"))
                {
                    operationManager.Create("RBM", "Help", "*");
                }

                #endregion Help Workflow
            }
            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                operationManager.Dispose();
                featureManager.Dispose();
            }

            #endregion
        }
        public ActionResult SaveResourceStructureAttribute(EditResourceStructureAttributeModel model, string[] keys)
        {
            using (var rsaManager = new ResourceStructureAttributeManager())
            {
                //check name
                if (model.AttributeName != null)
                {
                    ResourceStructureAttribute tempRS = rsaManager.GetResourceStructureAttributesByName(StringHelper.CutSpaces(model.AttributeName));
                    if (tempRS != null && tempRS.Id != model.Id)
                    {
                        ModelState.AddModelError("NameExist", "Name already exist.");
                    }
                }

                //check domain items
                if (keys != null)
                {
                    List <DomainItemModel> tempList = new List <DomainItemModel>();
                    foreach (string k in keys)
                    {
                        DomainItemModel d = new DomainItemModel();
                        d.Key   = k;
                        d.Value = k;
                        tempList.Add(d);
                        if (string.IsNullOrEmpty(k))
                        {
                            ModelState.AddModelError("DomainItem", "One domain item has no value.");
                        }
                    }
                    model.DomainItems = tempList;
                }

                if (ModelState.IsValid)
                {
                    ResourceStructureAttribute rsa = new ResourceStructureAttribute();
                    using (var rsManager = new ResourceStructureManager())
                    {
                        if (model.Id == 0)
                        {
                            rsa = rsaManager.CreateResourceStructureAttribute(model.AttributeName, model.AttributeDescription);
                        }
                        else
                        {
                            rsa             = rsaManager.GetResourceStructureAttributesById(model.Id);
                            rsa.Name        = model.AttributeName;
                            rsa.Description = model.AttributeDescription;
                            rsaManager.UpdateResourceStructureAttribute(rsa);
                        }

                        if (rsa != null && model.Id == 0)
                        {
                            //Start -> add security ----------------------------------------

                            using (EntityPermissionManager pManager = new EntityPermissionManager())
                                using (var entityTypeManager = new EntityManager())
                                    using (UserManager userManager = new UserManager())
                                    {
                                        var userTask = userManager.FindByNameAsync(HttpContext.User.Identity.Name);
                                        userTask.Wait();
                                        var user = userTask.Result;

                                        Entity entityType = entityTypeManager.FindByName("ResourceStructureAttribute");

                                        pManager.Create(user, entityType, rsa.Id, 31);
                                    }

                            //End -> add security ------------------------------------------
                        }


                        if (keys != null)
                        {
                            List <DomainItem> domainItems = CreateDomainItems(keys);
                            using (var dcManager = new DataContainerManager())
                            {
                                if (model.Id == 0 || rsa.Constraints.Count() == 0)
                                {
                                    DomainConstraint dc = new DomainConstraint(ConstraintProviderSource.Internal, "", "en-US", "a simple domain validation constraint", false, null, null, null, domainItems);
                                    dcManager.AddConstraint(dc, rsa);
                                }
                                else
                                {
                                    DomainConstraint temp = (DomainConstraint)rsa.Constraints.ElementAt(0);
                                    temp.Materialize();
                                    temp.Items = domainItems;
                                    dcManager.AddConstraint(temp, rsa);
                                }
                            }
                        }

                        //Creation with usage
                        if (model.rsID != 0)
                        {
                            ResourceStructure resourceStructure = rsManager.GetResourceStructureById(model.rsID);
                            rsaManager.CreateResourceAttributeUsage(rsa, resourceStructure, true, false);
                            //resourceStructure.ResourceStructureAttributes.Add(rsa);
                            //rsManager.Update(resourceStructure);
                            //return View("_editResourceStructure", new ResourceStructureModel(resourceStructure));
                            return(Json(new { success = true }));
                        }
                        else
                        {
                            return(Json(new { success = true }));
                        }
                    }
                }
                else
                {
                    return(PartialView("_createResourceStructureAttribute", model));
                }
            }
        }
예제 #11
0
        //[MeasurePerformance]
        //temporary solution: norman
        //For original solution, look into Aquadiva Code
        public List <Error> FinishUpload(EasyUploadTaskManager taskManager)
        {
            DataStructureManager dsm = new DataStructureManager();
            DatasetManager       dm  = new DatasetManager();
            DataContainerManager dam = new DataContainerManager();
            //SubjectManager sm = new SubjectManager();
            EntityPermissionManager entityPermissionManager = new EntityPermissionManager();

            List <Error> temp = new List <Error>();

            try
            {
                using (IUnitOfWork unitOfWork = this.GetUnitOfWork())
                {
                    // initialize all necessary manager

                    DataTuple[] rows = null;

                    //First, try to validate - if there are errors, return immediately
                    string       JsonArray        = TaskManager.Bus[EasyUploadTaskManager.SHEET_JSON_DATA].ToString();
                    List <Error> ValidationErrors = ValidateRows(JsonArray);
                    if (ValidationErrors.Count != 0)
                    {
                        temp.AddRange(ValidationErrors);
                        return(temp);
                    }

                    string timestamp = DateTime.UtcNow.ToString("r");
                    string title     = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.FILENAME]);

                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.DESCRIPTIONTITLE))
                    {
                        string tmp = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.DESCRIPTIONTITLE]);
                        if (!String.IsNullOrWhiteSpace(tmp))
                        {
                            title = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.DESCRIPTIONTITLE]);
                        }
                    }

                    StructuredDataStructure sds = dsm.CreateStructuredDataStructure(title, title + " " + timestamp, "", "", DataStructureCategory.Generic);

                    TaskManager.AddToBus(EasyUploadTaskManager.DATASTRUCTURE_ID, sds.Id);
                    TaskManager.AddToBus(EasyUploadTaskManager.DATASTRUCTURE_TITLE, title + " " + timestamp);

                    if (!TaskManager.Bus.ContainsKey(EasyUploadTaskManager.DATASET_TITLE))
                    {
                        TaskManager.AddToBus(EasyUploadTaskManager.DATASET_TITLE, title);
                        TaskManager.AddToBus(EasyUploadTaskManager.TITLE, title);
                    }

                    MetadataStructure metadataStructure = null;
                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.SCHEMA))
                    {
                        long metadataStructureId = Convert.ToInt64(TaskManager.Bus[EasyUploadTaskManager.SCHEMA]);
                        metadataStructure = unitOfWork.GetReadOnlyRepository <MetadataStructure>()
                                            .Get(m => m.Id == metadataStructureId).FirstOrDefault();
                    }
                    else
                    {
                        //Default option but shouldn't happen because previous steps can't be finished without selecting the metadata-structure
                        metadataStructure = unitOfWork.GetReadOnlyRepository <MetadataStructure>()
                                            .Get(m => m.Name.ToLower().Contains("eml")).FirstOrDefault();
                    }
                    ResearchPlan rp = unitOfWork.GetReadOnlyRepository <ResearchPlan>().Get().FirstOrDefault();
                    TaskManager.AddToBus(EasyUploadTaskManager.RESEARCHPLAN_ID, rp.Id);
                    TaskManager.AddToBus(EasyUploadTaskManager.RESEARCHPLAN_TITLE, rp.Title);

                    #region Progress Information

                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.CURRENTPACKAGESIZE))
                    {
                        TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGESIZE] = 0;
                    }
                    else
                    {
                        TaskManager.Bus.Add(EasyUploadTaskManager.CURRENTPACKAGESIZE, 0);
                    }

                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.CURRENTPACKAGE))
                    {
                        TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGE] = 0;
                    }
                    else
                    {
                        TaskManager.Bus.Add(EasyUploadTaskManager.CURRENTPACKAGE, 0);
                    }

                    #endregion

                    #region DataStructure
                    XmlDocument xmldoc       = new XmlDocument();
                    XmlElement  extraElement = xmldoc.CreateElement("extra");
                    XmlElement  orderElement = xmldoc.CreateElement("order");


                    List <Tuple <int, string, UnitInfo> > MappedHeaders = (List <Tuple <int, string, UnitInfo> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS];
                    //Sorting necessary to prevent problems when inserting the tuples
                    MappedHeaders.Sort((head1, head2) => head1.Item1.CompareTo(head2.Item1));
                    List <VariableIdentifier> identifiers = new List <VariableIdentifier>();

                    var dataTypeRepo      = unitOfWork.GetReadOnlyRepository <DataType>();
                    var unitRepo          = unitOfWork.GetReadOnlyRepository <Unit>();
                    var dataAttributeRepo = unitOfWork.GetReadOnlyRepository <DataAttribute>();

                    List <DataAttribute> allDataAttributes = dataAttributeRepo.Get().ToList();

                    foreach (Tuple <int, string, UnitInfo> Entry in MappedHeaders)
                    {
                        int i = MappedHeaders.IndexOf(Entry);

                        DataType dataType            = dataTypeRepo.Get(Entry.Item3.SelectedDataTypeId);
                        Unit     CurrentSelectedUnit = unitRepo.Get(Entry.Item3.UnitId);

                        DataAttribute CurrentDataAttribute = new DataAttribute();
                        //If possible, map the chosen variable name, unit and datatype to an existing DataAttribute (Exact match)
                        DataAttribute existingDataAttribute = allDataAttributes.Where(da => da.Name.ToLower().Equals(TrimAndLimitString(Entry.Item2).ToLower()) &&
                                                                                      da.DataType.Id == dataType.Id &&
                                                                                      da.Unit.Id == CurrentSelectedUnit.Id).FirstOrDefault();
                        if (existingDataAttribute != null)
                        {
                            CurrentDataAttribute = existingDataAttribute;
                        }
                        else
                        {
                            //No matching DataAttribute => Create a new one
                            CurrentDataAttribute = dam.CreateDataAttribute(TrimAndLimitString(Entry.Item2), Entry.Item2, "", false, false, "", MeasurementScale.Categorial, DataContainerType.ReferenceType, "", dataType, CurrentSelectedUnit, null, null, null, null, null, null);
                        }

                        Variable           newVariable = dsm.AddVariableUsage(sds, CurrentDataAttribute, true, Entry.Item2, "", "", "");
                        VariableIdentifier vi          = new VariableIdentifier
                        {
                            name = newVariable.Label,
                            id   = newVariable.Id
                        };
                        identifiers.Add(vi);

                        XmlElement newVariableXml = xmldoc.CreateElement("variable");
                        newVariableXml.InnerText = Convert.ToString(newVariable.Id);

                        orderElement.AppendChild(newVariableXml);
                    }
                    extraElement.AppendChild(orderElement);
                    xmldoc.AppendChild(extraElement);

                    sds.Extra       = xmldoc;
                    sds.Name        = "generated import structure " + timestamp;
                    sds.Description = "automatically generated structured data structure by user " + GetUsernameOrDefault() + " for file " + title + " on " + timestamp;

                    #endregion

                    Dataset ds = null;
                    ds = dm.CreateEmptyDataset(sds, rp, metadataStructure);

                    //TODO Should a template be created?

                    /*ExcelTemplateProvider etp = new ExcelTemplateProvider();
                     * etp.CreateTemplate(sds);*/

                    long datasetId = ds.Id;
                    long sdsId     = sds.Id;


                    if (dm.IsDatasetCheckedOutFor(datasetId, GetUsernameOrDefault()) || dm.CheckOutDataset(datasetId, GetUsernameOrDefault()))
                    {
                        DatasetVersion    dsv = dm.GetDatasetWorkingCopy(datasetId);
                        long              METADATASTRUCTURE_ID = metadataStructure.Id;
                        XmlMetadataWriter xmlMetadatWriter     = new XmlMetadataWriter(XmlNodeMode.xPath);
                        XDocument         metadataX            = xmlMetadatWriter.CreateMetadataXml(METADATASTRUCTURE_ID);
                        XmlDocument       metadataXml          = XmlMetadataWriter.ToXmlDocument(metadataX);
                        dsv.Metadata = metadataXml;
                        try
                        {
                            dsv.Metadata = xmlDatasetHelper.SetInformation(dsv, metadataXml, NameAttributeValues.title, title);
                        }
                        catch (NullReferenceException ex)
                        {
                            //Reference of the title node is missing
                            throw new NullReferenceException("The extra-field of this metadata-structure is missing the title-node-reference!");
                        }
                        dm.EditDatasetVersion(dsv, null, null, null);
                    }


                    #region security
                    // add security
                    if (GetUsernameOrDefault() != "DEFAULT")
                    {
                        //PermissionManager pm = new PermissionManager();

                        //User user = sm.GetUserByName(GetUsernameOrDefault());

                        //Rights-Management

                        /*
                         * TODO: Use the BExIS Party API for that
                         *
                         * */
                        /*
                         * UserPiManager upm = new UserPiManager();
                         * List<long> piList = (new UserSelectListModel(GetUsernameOrDefault())).UserList.Select(x => x.Id).ToList();
                         */


                        foreach (RightType rightType in Enum.GetValues(typeof(RightType)).Cast <RightType>())
                        {
                            //The user gets full permissions
                            // add security
                            if (GetUsernameOrDefault() != "DEFAULT")
                            {
                                entityPermissionManager.Create <User>(GetUsernameOrDefault(), "Dataset", typeof(Dataset), ds.Id, Enum.GetValues(typeof(RightType)).Cast <RightType>().ToList());
                            }

                            // adding the rights for the pis

                            /*foreach (long piId in piList)
                             * {
                             *  //Each pi gets full permissions
                             *  pm.CreateDataPermission(piId, 1, ds.Id, rightType);
                             *
                             *  // get all pi members
                             *  List<UserPi> currentMembers = upm.GetAllPiMember(piId).ToList();
                             *
                             *  foreach (UserPi currentMapping in currentMembers)
                             *  {
                             *      switch (rightType)
                             *      {
                             *          //Each member of each of the pis gets view-rights
                             *          case RightType.View:
                             *              pm.CreateDataPermission(currentMapping.UserId, 1, ds.Id, rightType);
                             *              break;
                             *          //Each member of each of the pis gets download-rights
                             *          case RightType.Download:
                             *              pm.CreateDataPermission(currentMapping.UserId, 1, ds.Id, rightType);
                             *              break;
                             *          default:
                             *              //No other permissions - is this call necessary?
                             *              pm.CreateDataPermission(currentMapping.UserId, 0, ds.Id, rightType);
                             *              break;
                             *      }
                             *  }
                             * }*/
                        }
                    }
                    #endregion security


                    #region excel reader

                    int packageSize = 10000;
                    //HACK ?
                    TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGESIZE] = packageSize;

                    int counter = 0;

                    dm.CheckOutDatasetIfNot(ds.Id, GetUsernameOrDefault()); // there are cases, the dataset does not get checked out!!
                    if (!dm.IsDatasetCheckedOutFor(ds.Id, GetUsernameOrDefault()))
                    {
                        throw new Exception(string.Format("Not able to checkout dataset '{0}' for  user '{1}'!", ds.Id, GetUsernameOrDefault()));
                    }

                    DatasetVersion workingCopy = dm.GetDatasetWorkingCopy(ds.Id);

                    counter++;
                    TaskManager.Bus[EasyUploadTaskManager.CURRENTPACKAGE] = counter;

                    //rows = reader.ReadFile(Stream, TaskManager.Bus[TaskManager.FILENAME].ToString(), oldSds, (int)id, packageSize).ToArray();

                    List <string> selectedDataAreaJsonArray   = (List <string>)TaskManager.Bus[EasyUploadTaskManager.SHEET_DATA_AREA];
                    string        selectedHeaderAreaJsonArray = TaskManager.Bus[EasyUploadTaskManager.SHEET_HEADER_AREA].ToString();
                    List <int[]>  areaDataValuesList          = new List <int[]>();
                    foreach (string area in selectedDataAreaJsonArray)
                    {
                        areaDataValuesList.Add(JsonConvert.DeserializeObject <int[]>(area));
                    }
                    int[] areaHeaderValues = JsonConvert.DeserializeObject <int[]>(selectedHeaderAreaJsonArray);

                    Orientation orientation = 0;

                    switch (TaskManager.Bus[EasyUploadTaskManager.SHEET_FORMAT].ToString())
                    {
                    case "LeftRight":
                        orientation = Orientation.rowwise;
                        break;

                    case "Matrix":
                        //orientation = Orientation.matrix;
                        break;

                    default:
                        orientation = Orientation.columnwise;
                        break;
                    }

                    String worksheetUri = null;
                    //Get the Uri to identify the correct worksheet
                    if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.ACTIVE_WOKSHEET_URI))
                    {
                        worksheetUri = TaskManager.Bus[EasyUploadTaskManager.ACTIVE_WOKSHEET_URI].ToString();
                    }

                    int batchSize = (new Object()).GetUnitOfWork().PersistenceManager.PreferredPushSize;
                    int batchnr   = 1;
                    foreach (int[] areaDataValues in areaDataValuesList)
                    {
                        //First batch starts at the start of the current data area
                        int currentBatchStartRow = areaDataValues[0] + 1;
                        while (currentBatchStartRow <= areaDataValues[2] + 1) //While the end of the current data area has not yet been reached
                        {
                            //Create a new reader each time because the reader saves ALL tuples it read and therefore the batch processing wouldn't work
                            EasyUploadExcelReader reader = new EasyUploadExcelReader();
                            // open file
                            Stream = reader.Open(TaskManager.Bus[EasyUploadTaskManager.FILEPATH].ToString());

                            //End row is start row plus batch size
                            int currentBatchEndRow = currentBatchStartRow + batchSize;

                            //Set the indices for the reader
                            EasyUploadFileReaderInfo fri = new EasyUploadFileReaderInfo
                            {
                                DataStartRow = currentBatchStartRow,
                                //End row is either at the end of the batch or the end of the marked area
                                //DataEndRow = (currentBatchEndRow > areaDataValues[2] + 1) ? areaDataValues[2] + 1 : currentBatchEndRow,
                                DataEndRow = Math.Min(currentBatchEndRow, areaDataValues[2] + 1),
                                //Column indices as marked in a previous step
                                DataStartColumn = areaDataValues[1] + 1,
                                DataEndColumn   = areaDataValues[3] + 1,

                                //Header area as marked in a previous step
                                VariablesStartRow    = areaHeaderValues[0] + 1,
                                VariablesStartColumn = areaHeaderValues[1] + 1,
                                VariablesEndRow      = areaHeaderValues[2] + 1,
                                VariablesEndColumn   = areaHeaderValues[3] + 1,

                                Offset      = areaDataValues[1],
                                Orientation = orientation
                            };

                            //Set variable identifiers because they might differ from the variable names in the file
                            reader.setSubmittedVariableIdentifiers(identifiers);

                            //Read the rows and convert them to DataTuples
                            rows = reader.ReadFile(Stream, TaskManager.Bus[EasyUploadTaskManager.FILENAME].ToString(), fri, sds, (int)datasetId, worksheetUri);

                            //After reading the rows, add them to the dataset
                            if (rows != null)
                            {
                                dm.EditDatasetVersion(workingCopy, rows.ToList(), null, null);
                            }

                            //Close the Stream so the next ExcelReader can open it again
                            Stream.Close();

                            //Debug information
                            int lines   = (areaDataValues[2] + 1) - (areaDataValues[0] + 1);
                            int batches = lines / batchSize;
                            batchnr++;

                            //Next batch starts after the current one
                            currentBatchStartRow = currentBatchEndRow + 1;
                        }
                    }

                    #endregion


                    dm.CheckInDataset(ds.Id, "upload data from upload wizard", GetUsernameOrDefault());

                    //Reindex search
                    if (this.IsAccessibale("DDM", "SearchIndex", "ReIndexSingle"))
                    {
                        this.Run("DDM", "SearchIndex", "ReIndexSingle", new RouteValueDictionary()
                        {
                            { "id", datasetId }
                        });
                    }

                    TaskManager.AddToBus(EasyUploadTaskManager.DATASET_ID, ds.Id);

                    return(temp);
                }
            }
            catch (Exception ex)
            {
                temp.Add(new Error(ErrorType.Other, "An error occured during the upload. " +
                                   "Please try again later. If this problem keeps occuring, please contact your administrator."));
                return(temp);
            }
            finally
            {
                dsm.Dispose();
                dm.Dispose();
                dam.Dispose();
                //sm.Dispose();
                entityPermissionManager.Dispose();
            }
        }
예제 #12
0
        public ActionResult Save(EditNotificationModel model)
        {
            using (NotificationManager nManager = new NotificationManager())
                using (EntityPermissionManager pManager = new EntityPermissionManager())
                    using (EntityManager entityTypeManager = new EntityManager())
                        using (UserManager userManager = new UserManager())
                        {
                            Dictionary <long, List <string> > dictionary = (Dictionary <long, List <string> >)Session["ResourceFilter"];
                            if (ModelState.IsValid && dictionary != null)
                            {
                                //if edit need comarison between stored dependensies and set in session
                                //get resource filter from the notification
                                //Dictionary<long, List<string>> dictionary = (Dictionary<long, List<string>>)Session["ResourceFilter"];
                                Session["ResourceFilter"] = null;

                                List <Schedule> affectedSchedules = GetAffectedSchedules(dictionary, model.StartDate, model.EndDate);

                                Notification notification = new Rbm.Entities.Booking.Notification();
                                if (model.Id == 0)
                                {
                                    notification = nManager.CreateNotification(model.Subject, model.StartDate, model.EndDate, model.Message);
                                }
                                else
                                {
                                    notification           = nManager.GetNotificationById(model.Id);
                                    notification.Subject   = model.Subject;
                                    notification.StartDate = model.StartDate;
                                    notification.EndDate   = model.EndDate;
                                    notification.Message   = model.Message;
                                    nManager.UpdateNotification(notification);
                                }

                                //save or update dependencies
                                if (model.Id == 0)
                                {
                                    foreach (KeyValuePair <long, List <string> > kp in dictionary)
                                    {
                                        foreach (string value in kp.Value)
                                        {
                                            nManager.CreateNotificationDependency(notification, Convert.ToInt64(kp.Key), value);
                                        }
                                    }
                                }
                                else
                                {
                                    //remove dep.
                                    for (int i = 0; i < notification.NotificationDependency.Count(); i++)
                                    //foreach (NotificationDependency d in notification.NotificationDependency)
                                    {
                                        if (dictionary.ContainsKey(notification.NotificationDependency.ToList()[i].AttributeId))
                                        {
                                            if (dictionary[notification.NotificationDependency.ToList()[i].AttributeId].Contains(notification.NotificationDependency.ToList()[i].DomainItem))
                                            {
                                                //:)
                                            }
                                            else
                                            {
                                                notification.NotificationDependency.Remove(notification.NotificationDependency.ToList()[i]);
                                                nManager.UpdateNotification(notification);
                                                //nManager.DeleteNotificationDependency(d);
                                            }
                                        }
                                        else
                                        {
                                            //delete all dependencies
                                            notification.NotificationDependency.Clear();
                                            nManager.UpdateNotification(notification);
                                        }
                                    }

                                    //add dep
                                    foreach (KeyValuePair <long, List <string> > kvp in dictionary)
                                    {
                                        long id = kvp.Key;
                                        foreach (string value in kvp.Value)
                                        {
                                            if (!notification.NotificationDependency.Any(a => a.AttributeId == id && a.DomainItem == value))
                                            {
                                                nManager.CreateNotificationDependency(notification, Convert.ToInt64(id), value);
                                            }
                                        }
                                    }
                                }

                                if (notification.Id != 0 && model.Id == 0)
                                {
                                    //Start -> add security ----------------------------------------

                                    //31 is the sum from all rights:  Read = 1,  Write = 4, Delete = 8, Grant = 16
                                    int    fullRights = (int)RightType.Read + (int)RightType.Write + (int)RightType.Delete + (int)RightType.Grant;
                                    Entity entityType = entityTypeManager.FindByName("Notification");

                                    //get admin groups: format= "groupname:resource structure attribute value"
                                    // give rights to group if fetch to notification
                                    string[] eventAdminGroups = Helper.Settings.get("EventAdminGroups").ToString().Split(',');
                                    Dictionary <string, string> adminGroupsDictionary = new Dictionary <string, string>();
                                    if (eventAdminGroups != null && eventAdminGroups.Length > 0)
                                    {
                                        foreach (string group in eventAdminGroups)
                                        {
                                            string[] groupPair = group.Split(':');
                                            adminGroupsDictionary.Add(groupPair[0], groupPair[1]);
                                        }
                                    }

                                    //get resource structrue attribute values to compare with admin group settings
                                    if (adminGroupsDictionary.Count > 0)
                                    {
                                        //get admin groups for notification
                                        var values      = dictionary.SelectMany(pair => pair.Value).ToList();
                                        var adminGroups = adminGroupsDictionary
                                                          .Where(pair => values.Contains(pair.Value))
                                                          .Select(pair => pair.Key)
                                                          .ToList();
                                        using (var groupManager = new GroupManager())
                                        {
                                            foreach (var g in adminGroups)
                                            {
                                                var group = groupManager.FindByNameAsync(g).Result;
                                                if (group != null)
                                                {
                                                    if (pManager.GetRights(group.Id, entityType.Id, notification.Id) == 0)
                                                    {
                                                        pManager.Create(group.Id, entityType.Id, notification.Id, fullRights);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //rights to bexcis admin group
                                    using (var groupManager = new GroupManager())
                                    {
                                        var adminGroup = groupManager.FindByNameAsync("administrator").Result;
                                        if (pManager.GetRights(adminGroup.Id, entityType.Id, notification.Id) == 0)
                                        {
                                            pManager.Create(adminGroup.Id, entityType.Id, notification.Id, fullRights);
                                        }
                                    }

                                    //rights to user that has create the notification
                                    var userTask = userManager.FindByNameAsync(HttpContext.User.Identity.Name);
                                    userTask.Wait();
                                    var user = userTask.Result;
                                    pManager.Create(user, entityType, notification.Id, fullRights);


                                    //End -> add security ------------------------------------------
                                }

                                //ToDo: Send email with notification to all in a affected schedule involved people
                                if (affectedSchedules.Count > 0)
                                {
                                    SendNotification(notification, affectedSchedules);
                                }

                                //return View("NotificationManager");
                                return(Json(new { success = true }));
                            }
                            else
                            {
                                List <AttributeDomainItemsModel> attributeDomainItems = (List <AttributeDomainItemsModel>)Session["FilterOptions"];
                                //Dictionary<long, List<string>> dictionary = (Dictionary<long, List<string>>)Session["ResourceFilter"];
                                if (dictionary != null)
                                {
                                    foreach (AttributeDomainItemsModel m in attributeDomainItems)
                                    {
                                        for (int i = 0; i < m.DomainItems.Count(); i++)
                                        {
                                            var list = dictionary.SelectMany(x => x.Value);
                                            if (list.Contains(m.DomainItems[i].Key))
                                            {
                                                m.DomainItems[i].Selected = true;
                                            }
                                        }
                                    }
                                }

                                model.AttributeDomainItems = attributeDomainItems;
                                return(PartialView("_editNotification", model));
                            }
                        }
        }
        public ActionResult Save(EditNotificationModel model)
        {
            using (NotificationManager nManager = new NotificationManager())
                using (EntityPermissionManager pManager = new EntityPermissionManager())
                    using (EntityManager entityTypeManager = new EntityManager())
                        using (UserManager userManager = new UserManager())
                        {
                            Dictionary <long, List <string> > dictionary = (Dictionary <long, List <string> >)Session["ResourceFilter"];
                            if (ModelState.IsValid && dictionary != null)
                            {
                                //if edit need comarison between stored dependensies and set in session
                                //get resource filter from the notification
                                //Dictionary<long, List<string>> dictionary = (Dictionary<long, List<string>>)Session["ResourceFilter"];
                                Session["ResourceFilter"] = null;

                                List <Schedule> affectedSchedules = GetAffectedSchedules(dictionary, model.StartDate, model.EndDate);

                                Notification notification = new Rbm.Entities.Booking.Notification();
                                if (model.Id == 0)
                                {
                                    notification = nManager.CreateNotification(model.Subject, model.StartDate, model.EndDate, model.Message);
                                }
                                else
                                {
                                    notification           = nManager.GetNotificationById(model.Id);
                                    notification.Subject   = model.Subject;
                                    notification.StartDate = model.StartDate;
                                    notification.EndDate   = model.EndDate;
                                    notification.Message   = model.Message;
                                    nManager.UpdateNotification(notification);
                                }

                                //save or update dependencies
                                if (model.Id == 0)
                                {
                                    foreach (KeyValuePair <long, List <string> > kp in dictionary)
                                    {
                                        foreach (string value in kp.Value)
                                        {
                                            nManager.CreateNotificationDependency(notification, Convert.ToInt64(kp.Key), value);
                                        }
                                    }
                                }
                                else
                                {
                                    //remove dep.
                                    for (int i = 0; i < notification.NotificationDependency.Count(); i++)
                                    //foreach (NotificationDependency d in notification.NotificationDependency)
                                    {
                                        if (dictionary.ContainsKey(notification.NotificationDependency.ToList()[i].AttributeId))
                                        {
                                            if (dictionary[notification.NotificationDependency.ToList()[i].AttributeId].Contains(notification.NotificationDependency.ToList()[i].DomainItem))
                                            {
                                                //:)
                                            }
                                            else
                                            {
                                                notification.NotificationDependency.Remove(notification.NotificationDependency.ToList()[i]);
                                                nManager.UpdateNotification(notification);
                                                //nManager.DeleteNotificationDependency(d);
                                            }
                                        }
                                        else
                                        {
                                            //delete all dependencies
                                            notification.NotificationDependency.Clear();
                                            nManager.UpdateNotification(notification);
                                        }
                                    }

                                    //add dep
                                    foreach (KeyValuePair <long, List <string> > kvp in dictionary)
                                    {
                                        long id = kvp.Key;
                                        foreach (string value in kvp.Value)
                                        {
                                            if (!notification.NotificationDependency.Any(a => a.AttributeId == id && a.DomainItem == value))
                                            {
                                                nManager.CreateNotificationDependency(notification, Convert.ToInt64(id), value);
                                            }
                                        }
                                    }
                                }


                                if (notification.Id != 0 && model.Id == 0)
                                {
                                    //Start -> add security ----------------------------------------


                                    {
                                        var userTask = userManager.FindByNameAsync(HttpContext.User.Identity.Name);
                                        userTask.Wait();
                                        var user = userTask.Result;

                                        Entity entityType = entityTypeManager.FindByName("Notification");

                                        //31 is the sum from all rights:  Read = 1,  Write = 4, Delete = 8, Grant = 16
                                        int rights = (int)RightType.Read + (int)RightType.Write + (int)RightType.Delete + (int)RightType.Grant;
                                        pManager.Create(user, entityType, notification.Id, rights);
                                    }

                                    //End -> add security ------------------------------------------
                                }

                                //ToDo: Send email with notification to all in a affected schedule involved people
                                if (affectedSchedules.Count > 0)
                                {
                                    SendNotification(notification, affectedSchedules);
                                }

                                //return View("NotificationManager");
                                return(Json(new { success = true }));
                            }
                            else
                            {
                                List <AttributeDomainItemsModel> attributeDomainItems = (List <AttributeDomainItemsModel>)Session["FilterOptions"];
                                //Dictionary<long, List<string>> dictionary = (Dictionary<long, List<string>>)Session["ResourceFilter"];
                                if (dictionary != null)
                                {
                                    foreach (AttributeDomainItemsModel m in attributeDomainItems)
                                    {
                                        for (int i = 0; i < m.DomainItems.Count(); i++)
                                        {
                                            var list = dictionary.SelectMany(x => x.Value);
                                            if (list.Contains(m.DomainItems[i].Key))
                                            {
                                                m.DomainItems[i].Selected = true;
                                            }
                                        }
                                    }
                                }

                                model.AttributeDomainItems = attributeDomainItems;
                                return(PartialView("_editNotification", model));
                            }
                        }
        }
예제 #14
0
        /// <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);
        }