Ejemplo n.º 1
0
        public async Task <bool> HasPermissions(Guid permissionID, Guid userID)
        {
            if (await DataContext.Users.AnyAsync(u => u.ID == userID && u.UserType == DTO.Enums.UserTypes.CNDSNetworkProxy))
            {
                return(false);
            }

            var  cndsUserID = Guid.Empty;
            Guid networkID  = await CNDSEntityUpdater.GetNetworkID(DataContext);

            try
            {
                using (var cnds = new CNDSEntityUpdater(networkID))
                {
                    var response = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(new[] { userID });

                    cndsUserID = response.Select(user => user.EntityID).FirstOrDefault();

                    if (cndsUserID == default(Guid))
                    {
                        throw new System.Net.Http.HttpRequestException("User not found in CNDS.");
                    }

                    return(await CNDSEntityUpdater.CNDS.Permissions.HasPermission(permissionID, cndsUserID));
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                throw;
            }
        }
Ejemplo n.º 2
0
        public override async System.Threading.Tasks.Task <DataMartDTO> Get(Guid id)
        {
            var datamart = await DataContext.DataMarts.Where(o => o.ID == id && o.DataMartTypeID != CNDSImportedDataMartTypeID).AsNoTracking().Map <DataMart, DataMartDTO>().FirstOrDefaultAsync();

            if (datamart == null)
            {
                if (await DataContext.DataMarts.AnyAsync(o => o.ID == id && o.DataMartTypeID == CNDSImportedDataMartTypeID))
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "You do not have permission to view the selected DataMart."));
                }
                else
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The specified DataMart was not found."));
                }
            }

            //TODO: create helper to cache
            var  cndsDMID  = Guid.Empty;
            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            try
            {
                using (var cnds = new CNDSEntityUpdater(networkID))
                {
                    var response = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(new[] { id });

                    cndsDMID = response.Select(org => org.EntityID).FirstOrDefault();

                    if (cndsDMID == default(Guid))
                    {
                        throw new System.Net.Http.HttpRequestException("DataMart not found in CNDS.");
                    }

                    var availDMMetadata   = (await CNDSEntityUpdater.CNDS.Domain.List("$filter=EntityType eq Lpp.CNDS.DTO.Enums.EntityType'2'")).ToArray();
                    var currentDmMetadata = (await CNDSEntityUpdater.CNDS.DataSources.ListDataSourceDomains(cndsDMID)).ToArray();
                    var visibility        = await CNDSEntityUpdater.CNDS.DataSources.GetDomainVisibility(cndsDMID);

                    List <MetadataDTO> meta = new List <MetadataDTO>();
                    foreach (var metadata in availDMMetadata.Where(x => x.ParentDomainID == null))
                    {
                        meta.Add(cnds.GetMetadataChildren(metadata.ID, availDMMetadata, currentDmMetadata, visibility, cndsDMID));
                    }
                    datamart.Metadata = meta;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                throw;
            }
            return(datamart);
        }
Ejemplo n.º 3
0
        public override async System.Threading.Tasks.Task <OrganizationDTO> Get(Guid id)
        {
            var organization = await DataContext.Organizations.Where(o => o.ID == id && o.OrganizationType == DTO.Enums.OrganizationType.Local).AsNoTracking().Map <Organization, OrganizationDTO>().FirstOrDefaultAsync();

            if (organization == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The specified Organization was not found."));
            }

            //TODO: create helper to cache
            var  cndsOrgID = Guid.Empty;
            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            try
            {
                using (var cnds = new CNDSEntityUpdater(networkID))
                {
                    var response = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(new[] { id });

                    cndsOrgID = response.Select(org => org.EntityID).FirstOrDefault();

                    if (cndsOrgID == default(Guid))
                    {
                        throw new System.Net.Http.HttpRequestException("Organization not found in CNDS.");
                    }

                    var availOrgMetdata = await CNDSEntityUpdater.CNDS.Domain.List("$filter=EntityType eq Lpp.CNDS.DTO.Enums.EntityType'0'");

                    var currentOrgMetadata = await CNDSEntityUpdater.CNDS.Organizations.ListOrganizationDomains(cndsOrgID);

                    var visibility = await CNDSEntityUpdater.CNDS.Organizations.GetDomainVisibility(cndsOrgID);

                    List <MetadataDTO> meta = new List <MetadataDTO>();
                    foreach (var metadata in availOrgMetdata.Where(x => x.ParentDomainID == null))
                    {
                        meta.Add(cnds.GetMetadataChildren(metadata.ID, availOrgMetdata, currentOrgMetadata, visibility, cndsOrgID));
                    }
                    organization.Metadata = meta;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                throw;
            }
            return(organization);
        }
Ejemplo n.º 4
0
        public async Task <IEnumerable <CNDSAssignedPermissionDTO> > GetCurrentUserPermissions()
        {
            if (await DataContext.Users.AnyAsync(u => u.ID == Identity.ID && u.UserType == DTO.Enums.UserTypes.CNDSNetworkProxy))
            {
                return(Enumerable.Empty <CNDSAssignedPermissionDTO>());
            }

            var  cndsUserID = Guid.Empty;
            Guid networkID  = await CNDSEntityUpdater.GetNetworkID(DataContext);

            try
            {
                using (var cnds = new CNDSEntityUpdater(networkID))
                {
                    var response = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(new[] { Identity.ID });

                    cndsUserID = response.Select(user => user.EntityID).FirstOrDefault();

                    if (cndsUserID == default(Guid))
                    {
                        throw new System.Net.Http.HttpRequestException("User not found in CNDS.");
                    }

                    var returnPermissions = await CNDSEntityUpdater.CNDS.Permissions.GetUserPermissions(cndsUserID);

                    var convertedPermissions = (from p in returnPermissions
                                                select new CNDSAssignedPermissionDTO
                    {
                        SecurityGroupID = p.SecurityGroupID,
                        PermissionID = p.PermissionID,
                        Allowed = p.Allowed
                    }).ToArray();
                    return(convertedPermissions);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                throw;
            }
        }
Ejemplo n.º 5
0
        public async Task <CNDSSecurityGroupUserDTO> GetUserSecurityGroups(Guid userID)
        {
            if (await DataContext.Users.AnyAsync(u => u.ID == userID && u.UserType == DTO.Enums.UserTypes.CNDSNetworkProxy))
            {
                return(new CNDSSecurityGroupUserDTO());
            }

            var  cndsUserID = Guid.Empty;
            Guid networkID  = await CNDSEntityUpdater.GetNetworkID(DataContext);

            try
            {
                using (var cnds = new CNDSEntityUpdater(networkID))
                {
                    var response = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(new[] { userID });

                    cndsUserID = response.Select(user => user.EntityID).FirstOrDefault();

                    if (cndsUserID == default(Guid))
                    {
                        throw new System.Net.Http.HttpRequestException("User not found in CNDS.");
                    }

                    var sgus = await CNDSEntityUpdater.CNDS.SecurityGroupUsers.Get(cndsUserID);

                    return(new CNDSSecurityGroupUserDTO {
                        UserID = sgus.UserID, SecurityGroups = sgus.SecurityGroups.Select(x => new CNDSSecurityGroupDTO {
                            ID = x.ID, Name = x.Name
                        })
                    });
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                throw;
            }
        }
Ejemplo n.º 6
0
        public override async Task Delete([FromUri] IEnumerable <Guid> ID)
        {
            if (!await DataContext.CanDelete <DataMart>(Identity, ID.ToArray()))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to delete this project."));
            }

            var datamarts = await(from dm in DataContext.DataMarts where ID.Contains(dm.ID) && dm.DataMartTypeID != CNDSImportedDataMartTypeID select dm).ToArrayAsync();

            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            if (CNDSEntityUpdater.CanUpdateCNDS)
            {
                try
                {
                    using (var cnds = new CNDSEntityUpdater(networkID))
                    {
                        var networkEntities = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(datamarts.Select(x => x.ID).ToArray());

                        foreach (var datamart in datamarts)
                        {
                            await CNDSEntityUpdater.CNDS.DataSources.Delete(networkEntities.Where(x => x.NetworkEntityID == datamart.ID).Select(x => x.EntityID).FirstOrDefault());

                            datamart.Deleted = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                    throw;
                }
            }


            await DataContext.SaveChangesAsync();
        }
Ejemplo n.º 7
0
        public override async Task Delete([FromUri] IEnumerable <Guid> ID)
        {
            if (!await DataContext.CanDelete <Organization>(Identity, ID.ToArray()))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to delete this Organization."));
            }

            var orgs      = await(from o in DataContext.Organizations where ID.Contains(o.ID) && o.OrganizationType == DTO.Enums.OrganizationType.Local select o).ToArrayAsync();
            var childOrgs = await(from o in DataContext.Organizations where o.ParentOrganizationID.HasValue && ID.Contains(o.ParentOrganizationID.Value) && o.OrganizationType == DTO.Enums.OrganizationType.Local select o).ToArrayAsync();

            foreach (var child in childOrgs)
            {
                child.ParentOrganizationID = null;
            }

            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            if (CNDSEntityUpdater.CanUpdateCNDS)
            {
                try
                {
                    using (var cnds = new CNDSEntityUpdater(networkID))
                    {
                        var networkEntities = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(orgs.Select(x => x.ID).ToArray());

                        foreach (var org in orgs)
                        {
                            await CNDSEntityUpdater.CNDS.Organizations.Delete(networkEntities.Where(x => x.NetworkEntityID == org.ID).Select(x => x.EntityID).FirstOrDefault());

                            org.Deleted = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                    throw;
                }
            }

            var users = await(from u in DataContext.Users where ID.Contains(u.OrganizationID.Value) select u).ToArrayAsync();

            foreach (var user in users)
            {
                user.Deleted = true;
            }

            var dms = await(from d in DataContext.DataMarts where ID.Contains(d.OrganizationID) select d).ToArrayAsync();

            foreach (var dm in dms)
            {
                dm.Deleted = true;
            }

            await DataContext.SaveChangesAsync();


            var securityGroups = await(from sg in DataContext.SecurityGroups where ID.Contains(sg.OwnerID) select sg.ID).ToArrayAsync();

            if (securityGroups.Any())
            {
                var securityGroupIDs = String.Join(",", securityGroups.Select(x => String.Format("'{0}'", x)));
                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclGlobal where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclDataMarts where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclDataMartRequestTypes where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclOrganizations where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclOrganizationDataMarts where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclOrganizationUsers where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclProjects where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclProjectOrganizations where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclProjectDataMarts where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclProjectDataMartRequestTypes where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclRegistries where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclRequests where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclRequestSharedFolders where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclRequestTypes where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclUsers where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from AclRequestTypes where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from GlobalEvents where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from DataMartEvents where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from GroupEvents where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from OrganizationEvents where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from ProjectEvents where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from ProjectOrganizationEvents where SecurityGroupID IN ({0})", securityGroupIDs));

                await DataContext.Database.ExecuteSqlCommandAsync(string.Format("delete from ProjectDataMartEvents where SecurityGroupID IN ({0})", securityGroupIDs));
            }
        }
Ejemplo n.º 8
0
        public async Task <Guid> Copy(Guid organizationID)
        {
            var existing = await(from o in DataContext.Organizations where o.ID == organizationID && o.OrganizationType == DTO.Enums.OrganizationType.Local select o).FirstOrDefaultAsync();

            if (existing == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The Organization could not be found."));
            }

            if (!await DataContext.HasPermissions <Organization>(Identity, existing.ID, PermissionIdentifiers.Organization.Copy))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to copy the specified organization."));
            }

            string newAcronym = "New " + existing.Acronym;
            string newName    = "New " + existing.Name;

            while (await(from p in DataContext.Organizations where !p.Deleted && (p.Name == newName && p.Acronym == newAcronym) select p).AnyAsync())
            {
                newAcronym = "New " + newAcronym;
                newName    = "New " + newName;
            }

            var organization = new Organization
            {
                Acronym = newAcronym,
                Name    = newName,
                ParentOrganizationID          = existing.ParentOrganizationID,
                ApprovalRequired              = existing.ApprovalRequired,
                ContactEmail                  = existing.ContactEmail,
                ContactFirstName              = existing.ContactFirstName,
                ContactLastName               = existing.ContactLastName,
                ContactPhone                  = existing.ContactPhone,
                SpecialRequirements           = existing.SpecialRequirements,
                UsageRestrictions             = existing.UsageRestrictions,
                HealthPlanDescription         = existing.HealthPlanDescription,
                EnableClaimsAndBilling        = existing.EnableClaimsAndBilling,
                EnableEHRA                    = existing.EnableEHRA,
                EnableRegistries              = existing.EnableRegistries,
                DataModelESP                  = existing.DataModelESP,
                DataModelHMORNVDW             = existing.DataModelHMORNVDW,
                DataModelI2B2                 = existing.DataModelI2B2,
                DataModelMSCDM                = existing.DataModelMSCDM,
                DataModelOMOP                 = existing.DataModelOMOP,
                DataModelOther                = existing.DataModelOther,
                DataModelOtherText            = existing.DataModelOtherText,
                PragmaticClinicalTrials       = existing.PragmaticClinicalTrials,
                Biorepositories               = existing.Biorepositories,
                PatientReportedBehaviors      = existing.PatientReportedBehaviors,
                PatientReportedOutcomes       = existing.PatientReportedOutcomes,
                PrescriptionOrders            = existing.PrescriptionOrders,
                InpatientEHRApplication       = existing.InpatientEHRApplication,
                OutpatientEHRApplication      = existing.OutpatientEHRApplication,
                OtherInpatientEHRApplication  = existing.OtherInpatientEHRApplication,
                OtherOutpatientEHRApplication = existing.OtherOutpatientEHRApplication,
                InpatientClaims               = existing.InpatientClaims,
                OutpatientClaims              = existing.OutpatientClaims,
                ObservationalParticipation    = existing.ObservationalParticipation,
                ProspectiveTrials             = existing.ProspectiveTrials,
                EnrollmentClaims              = existing.EnrollmentClaims,
                DemographicsClaims            = existing.DemographicsClaims,
                LaboratoryResultsClaims       = existing.LaboratoryResultsClaims,
                VitalSignsClaims              = existing.LaboratoryResultsClaims,
                OtherClaims                   = existing.OtherClaims,
                OtherClaimsText               = existing.OtherClaimsText,
                ObservationClinicalExperience = existing.ObservationClinicalExperience,
                OrganizationType              = existing.OrganizationType
            };

            DataContext.Organizations.Add(organization);

            var orgDTO = new OrganizationDTO()
            {
                ID      = organization.ID,
                Name    = organization.Name,
                Acronym = organization.Acronym,
                ParentOrganizationID = organization.ParentOrganizationID,
                ContactEmail         = organization.ContactEmail,
                ContactFirstName     = organization.ContactFirstName,
                ContactLastName      = organization.ContactLastName,
                ContactPhone         = organization.ContactPhone
            };

            #region CNDS
            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            if (CNDSEntityUpdater.CanUpdateCNDS)
            {
                try
                {
                    using (var cnds = new CNDSEntityUpdater(networkID))
                    {
                        var response = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(new[] { organizationID });

                        var cndsOrgID = response.Select(org => org.EntityID).FirstOrDefault();

                        if (cndsOrgID == default(Guid))
                        {
                            throw new System.Net.Http.HttpRequestException("Organization not found in CNDS.");
                        }

                        var availOrgMetdata = await CNDSEntityUpdater.CNDS.Domain.List("$filter=EntityType eq Lpp.CNDS.DTO.Enums.EntityType'0'");

                        var currentOrgMetadata = await CNDSEntityUpdater.CNDS.Organizations.ListOrganizationDomains(cndsOrgID);

                        List <MetadataDTO> meta = new List <MetadataDTO>();
                        foreach (var metadata in availOrgMetdata.Where(x => x.ParentDomainID == null))
                        {
                            meta.Add(cnds.GetMetadataChildren(metadata.ID, availOrgMetdata, currentOrgMetadata, null, null));
                        }
                        orgDTO.Metadata = meta;
                        await CNDSEntityUpdater.RegisterOrUpdateOrganizations(orgDTO);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                }
            }

            #endregion CNDS

            //Registries
            var existingRegistries = await(from reg in DataContext.OrganizationRegistries where reg.OrganizationID == existing.ID select reg).ToArrayAsync();
            foreach (var existingRegistry in existingRegistries)
            {
                var reg = new OrganizationRegistry
                {
                    RegistryID     = existingRegistry.RegistryID,
                    OrganizationID = organization.ID,
                    Description    = existingRegistry.Description
                };
                DataContext.OrganizationRegistries.Add(reg);
            }

            //Security Groups
            var existingSecurityGroups = await(from sg in DataContext.SecurityGroups.Include(x => x.Users) where sg.OwnerID == existing.ID orderby sg.ParentSecurityGroupID select sg).ToArrayAsync();
            var SecurityGroupMap       = new Dictionary <Guid, Guid>();

            CopySecurityGroups(existingSecurityGroups, ref SecurityGroupMap, null, organization);

            await DataContext.SaveChangesAsync();

            //All of these are done this way with a conditional if because the triggers cause inserts that entity framework is not aware of. Note that they are parameterized to ensure no sql injections.

            foreach (var user in existingSecurityGroups.SelectMany(u => u.Users).DistinctBy(u => new { u.SecurityGroupID, u.UserID }))
            {
                await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM SecurityGroupUsers WHERE UserID = @UserID AND SecurityGroupID = @SecurityGroupID)
	INSERT INTO SecurityGroupUsers (UserID, SecurityGroupID, Overridden) VALUES (@UserID, @SecurityGroupID, 0)"    , new SqlParameter("UserID", user.UserID), new SqlParameter("SecurityGroupID", SecurityGroupMap[user.SecurityGroupID]));
            }



            //Org Acls
            var existingSecurityGroupIDs = SecurityGroupMap.Select(gm => gm.Key).ToArray();
            var existingOrganizationAcls = await(from a in DataContext.OrganizationAcls where a.OrganizationID == existing.ID && existingSecurityGroupIDs.Contains(a.SecurityGroupID) select a).Distinct().ToArrayAsync();

            foreach (var existingOrganizationAcl in existingOrganizationAcls)
            {
                if (!SecurityGroupMap.ContainsKey(existingOrganizationAcl.SecurityGroupID))
                {
                    SecurityGroupMap.Add(existingOrganizationAcl.SecurityGroupID, existingOrganizationAcl.SecurityGroupID);
                }

                var count = await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM AclOrganizations WHERE OrganizationID = @OrganizationID AND SecurityGroupID = @SecurityGroupID AND PermissionID = @PermissionID)
	INSERT INTO AclOrganizations (OrganizationID, SecurityGroupID, PermissionID, Allowed, Overridden) VALUES (@OrganizationID, @SecurityGroupID, @PermissionID, @Allowed, 1)"    , new SqlParameter("OrganizationID", organization.ID), new SqlParameter("SecurityGroupID", SecurityGroupMap[existingOrganizationAcl.SecurityGroupID]), new SqlParameter("PermissionID", existingOrganizationAcl.PermissionID), new SqlParameter("Allowed", existingOrganizationAcl.Allowed));
            }

            //Org Event Acls
            var existingOrganizationEventAcls = await(from a in DataContext.OrganizationEvents where a.OrganizationID == existing.ID select a).ToArrayAsync();
            foreach (var existingOrganizationEventAcl in existingOrganizationEventAcls)
            {
                if (!SecurityGroupMap.ContainsKey(existingOrganizationEventAcl.SecurityGroupID))
                {
                    SecurityGroupMap.Add(existingOrganizationEventAcl.SecurityGroupID, existingOrganizationEventAcl.SecurityGroupID);
                }

                await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM OrganizationEvents WHERE OrganizationID = @OrganizationID AND SecurityGroupID = @SecurityGroupID AND EventID = @EventID)
	INSERT INTO OrganizationEvents (OrganizationID, SecurityGroupID, EventID, Allowed, Overridden) VALUES (@OrganizationID, @SecurityGroupID, @EventID, @Allowed, 0)"    , new SqlParameter("OrganizationID", organization.ID), new SqlParameter("SecurityGroupID", SecurityGroupMap[existingOrganizationEventAcl.SecurityGroupID]), new SqlParameter("EventID", existingOrganizationEventAcl.EventID), new SqlParameter("Allowed", existingOrganizationEventAcl.Allowed));
            }

            return(organization.ID);
        }
Ejemplo n.º 9
0
        public async Task <Guid> Copy(Guid datamartID)
        {
            var existing = await(from dm in DataContext.DataMarts where dm.ID == datamartID && dm.DataMartTypeID != CNDSImportedDataMartTypeID select dm).SingleOrDefaultAsync();

            if (existing == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The DataMart could not be found."));
            }

            if (!await DataContext.HasPermissions <DataMart>(Identity, existing, PermissionIdentifiers.DataMart.Copy))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to copy the specified DataMart."));
            }

            string newAcronym = "New " + existing.Acronym;
            string newName    = "New " + existing.Name;

            while (await(from p in DataContext.DataMarts where !p.Deleted && (p.Name == newName && p.Acronym == newAcronym) select p).AnyAsync())
            {
                newAcronym = "New " + newAcronym;
                newName    = "New " + newName;
            }

            var datamart = new DataMart
            {
                Acronym                                    = newAcronym,
                StartDate                                  = DateTime.Today,
                Name                                       = newName,
                DataMartType                               = existing.DataMartType,
                DataMartTypeID                             = existing.DataMartTypeID,
                AvailablePeriod                            = existing.AvailablePeriod,
                ContactEmail                               = existing.ContactEmail,
                ContactFirstName                           = existing.ContactFirstName,
                ContactLastName                            = existing.ContactLastName,
                ContactPhone                               = existing.ContactPhone,
                SpecialRequirements                        = existing.SpecialRequirements,
                UsageRestrictions                          = existing.UsageRestrictions,
                Deleted                                    = existing.Deleted,
                HealthPlanDescription                      = existing.HealthPlanDescription,
                OrganizationID                             = existing.OrganizationID,
                Organization                               = existing.Organization,
                IsGroupDataMart                            = existing.IsGroupDataMart,
                UnattendedMode                             = existing.UnattendedMode,
                Description                                = existing.Description,
                EndDate                                    = existing.EndDate,
                DataUpdateFrequency                        = existing.DataUpdateFrequency,
                InpatientEHRApplication                    = existing.InpatientEHRApplication,
                OutpatientEHRApplication                   = existing.OutpatientEHRApplication,
                LaboratoryResultsAny                       = existing.LaboratoryResultsAny,
                LaboratoryResultsClaims                    = existing.LaboratoryResultsClaims,
                LaboratoryResultsTestName                  = existing.LaboratoryResultsTestName,
                LaboratoryResultsDates                     = existing.LaboratoryResultsDates,
                LaboratoryResultsTestLOINC                 = existing.LaboratoryResultsTestLOINC,
                LaboratoryResultsTestSNOMED                = existing.LaboratoryResultsTestSNOMED,
                LaboratoryResultsSpecimenSource            = existing.LaboratoryResultsSpecimenSource,
                LaboratoryResultsTestDescriptions          = existing.LaboratoryResultsTestDescriptions,
                LaboratoryResultsOrderDates                = existing.LaboratoryResultsOrderDates,
                LaboratoryResultsTestResultsInterpretation = existing.LaboratoryResultsTestResultsInterpretation,
                LaboratoryResultsTestOther                 = existing.LaboratoryResultsTestOther,
                LaboratoryResultsTestOtherText             = existing.LaboratoryResultsTestOtherText,
                InpatientEncountersAny                     = existing.InpatientEncountersAny,
                InpatientEncountersEncounterID             = existing.InpatientEncountersEncounterID,
                InpatientEncountersProviderIdentifier      = existing.InpatientEncountersProviderIdentifier,
                InpatientDatesOfService                    = existing.InpatientDatesOfService,
                InpatientICD9Procedures                    = existing.InpatientICD9Procedures,
                InpatientICD10Procedures                   = existing.InpatientICD10Procedures,
                InpatientICD9Diagnosis                     = existing.InpatientICD9Diagnosis,
                InpatientICD10Diagnosis                    = existing.InpatientICD10Diagnosis,
                InpatientSNOMED                            = existing.InpatientSNOMED,
                InpatientHPHCS                             = existing.InpatientHPHCS,
                InpatientDisposition                       = existing.InpatientDisposition,
                InpatientDischargeStatus                   = existing.InpatientDischargeStatus,
                InpatientOther                             = existing.InpatientOther,
                InpatientOtherText                         = existing.InpatientOtherText,
                OutpatientEncountersAny                    = existing.OutpatientEncountersAny,
                OutpatientEncountersEncounterID            = existing.OutpatientEncountersEncounterID,
                OutpatientEncountersProviderIdentifier     = existing.OutpatientEncountersProviderIdentifier,
                OutpatientClinicalSetting                  = existing.OutpatientClinicalSetting,
                OutpatientDatesOfService                   = existing.OutpatientDatesOfService,
                OutpatientICD9Procedures                   = existing.OutpatientICD9Procedures,
                OutpatientICD10Procedures                  = existing.OutpatientICD10Procedures,
                OutpatientICD9Diagnosis                    = existing.OutpatientICD9Diagnosis,
                OutpatientICD10Diagnosis                   = existing.OutpatientICD10Diagnosis,
                OutpatientSNOMED                           = existing.OutpatientSNOMED,
                OutpatientHPHCS                            = existing.OutpatientHPHCS,
                OutpatientOther                            = existing.OutpatientOther,
                OutpatientOtherText                        = existing.OutpatientOtherText,
                ERPatientID                                = existing.ERPatientID,
                EREncounterID                              = existing.EREncounterID,
                EREnrollmentDates                          = existing.EREnrollmentDates,
                EREncounterDates                           = existing.EREncounterDates,
                ERClinicalSetting                          = existing.ERClinicalSetting,
                ERICD9Diagnosis                            = existing.ERICD9Diagnosis,
                ERICD10Diagnosis                           = existing.ERICD10Diagnosis,
                ERHPHCS                                    = existing.ERHPHCS,
                ERNDC                                      = existing.ERNDC,
                ERSNOMED                                   = existing.ERSNOMED,
                ERProviderIdentifier                       = existing.ERProviderIdentifier,
                ERProviderFacility                         = existing.ERProviderFacility,
                EREncounterType                            = existing.EREncounterType,
                ERDRG                                      = existing.ERDRG,
                ERDRGType                                  = existing.ERDRGType,
                EROther                                    = existing.EROther,
                EROtherText                                = existing.EROtherText,
                DemographicsAny                            = existing.DemographicsAny,
                PatientBehaviorInstruments                 = existing.PatientBehaviorInstruments,
                PharmacyDispensingAny                      = existing.PharmacyDispensingAny,
                OtherClaims                                = existing.OtherClaims,
                Registeries                                = existing.Registeries,
                OtherInpatientEHRApplication               = existing.OtherInpatientEHRApplication,
                OtherOutpatientEHRApplication              = existing.OtherOutpatientEHRApplication,
                DataModel                                  = existing.DataModel,
                OtherDataModel                             = existing.OtherDataModel,
                IsLocal                                    = existing.IsLocal,
                Url = existing.Url ?? ""
            };

            DataContext.DataMarts.Add(datamart);

            var dmDTO = new DataMartDTO {
                ID             = datamart.ID,
                Name           = datamart.Name,
                Acronym        = datamart.Acronym,
                OrganizationID = datamart.OrganizationID,
                AdapterID      = datamart.AdapterID
            };


            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            if (CNDSEntityUpdater.CanUpdateCNDS)
            {
                try
                {
                    using (var cnds = new CNDSEntityUpdater(networkID))
                    {
                        IList <Guid> ids = new List <Guid>();
                        ids.Add(datamartID);
                        ids.Add(datamart.OrganizationID);
                        var networkEntity = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(ids);

                        Guid?cndsOrganizationID = networkEntity.Where(x => x.NetworkEntityID == datamart.OrganizationID).Select(x => x.EntityID).FirstOrDefault();
                        var  cndsDataSourceID   = networkEntity.Where(x => x.NetworkEntityID == datamartID).Select(o => o.EntityID).FirstOrDefault();

                        var availDMMetadata = await CNDSEntityUpdater.CNDS.Domain.List("$filter=EntityType eq Lpp.CNDS.DTO.Enums.EntityType'2'");

                        var oldMetadata = await CNDSEntityUpdater.CNDS.DataSources.ListDataSourceDomains(cndsDataSourceID);

                        List <MetadataDTO> meta = new List <MetadataDTO>();
                        foreach (var metadata in availDMMetadata.Where(x => x.ParentDomainID == null))
                        {
                            meta.Add(cnds.GetMetadataChildren(metadata.ID, availDMMetadata, oldMetadata, null, null));
                        }
                        dmDTO.Metadata = meta;

                        await CNDSEntityUpdater.RegisterOrUpdateDataSources(dmDTO);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                    throw;
                }
            }

            await DataContext.SaveChangesAsync();

            //DataMart Acls
            var existingDataMartAcls = await(from a in DataContext.DataMartAcls where a.DataMartID == existing.ID select a).ToArrayAsync();

            foreach (var existingDataMartAcl in existingDataMartAcls)
            {
                var count = await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM AclDataMarts WHERE DataMartID = @DataMartID AND SecurityGroupID = @SecurityGroupID AND PermissionID = @PermissionID)
	INSERT INTO AclDataMarts (DataMartID, SecurityGroupID, PermissionID, Allowed, Overridden) VALUES (@DataMartID, @SecurityGroupID, @PermissionID, @Allowed, 1)"    , new SqlParameter("DataMartID", datamart.ID), new SqlParameter("SecurityGroupID", existingDataMartAcl.SecurityGroupID), new SqlParameter("PermissionID", existingDataMartAcl.PermissionID), new SqlParameter("Allowed", existingDataMartAcl.Allowed));
            }

            return(datamart.ID);
        }