Esempio n. 1
0
        public async Task CreateAsync(Client client)
        {
            Ensure.That(client.Id == null, "Client Id is set internally when creating new clients");
            Ensure.NotNullOrEmpty(client.TenantKey);

            client.Id = KeyGen.NewGuid();

            // Initialize OIDC for this new client
            var tenant = await _tenantManager.CreateAsync(client.TenantKey, client.Name);

            var directory = await _directoryManager.CreateAsync(client.TenantKey, "Default User Directory");

            // create a new security pool mapped to the default directory
            var clientSecurityPool = await _poolManager.CreateTenantPoolAsync
                                     (
                client.TenantKey,
                client.Name + " Pool",
                new Identity.Models.Directory[] { directory }
                                     );

            // Create the Connect Client
            client.SecurityPoolId = clientSecurityPool.PoolId;

            if (client.AnniversaryDate == null)
            {
                client.AnniversaryDate = DateTime.UtcNow;
            }

            _db.Add(client);
            await _db.SaveChangesAsync();

            // Insert default roles
            await CreateDefaultClientLevelRoles(client);
        }
Esempio n. 2
0
        //agregar
        public async Task <Pais> Add(Pais pais)
        {
            var newPais = await _context.Paises.AddAsync(pais);

            await _context.SaveChangesAsync();

            return(newPais.Entity);
        }
        public async Task <Province> Add(Province province)
        {
            var newProvince = await _context.Provinces.AddAsync(province);

            await _context.SaveChangesAsync();

            return(newProvince.Entity);
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            var output = new System.Text.StringBuilder();

            // Fail if cannot connect to db
            if (_connectDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Check if internal product already exists
            var exists = await _connectDb.Products.AnyAsync(x => x.Id == DbKeys.ProductIds.Internal);

            if (exists)
            {
                // early terminate
                return(MigrationResult.Skipped("Product already exists"));
            }

            // Register the product
            var internalProduct = new Product
            {
                Id          = DbKeys.ProductIds.Internal,
                CategoryId  = DbKeys.ProductCategoryIds.Angelo,
                Name        = "Internal Corp Product",
                Description = "Internal product used for building PC|Mac demo sites.",
                SchemaFile  = "/schemas/products/Product-0-Internal.json",
                Active      = true
            };

            _connectDb.Products.Add(internalProduct);
            await _connectDb.SaveChangesAsync();


            // Update the PcMac Product Mapping
            var productMapping = await _connectDb.ClientProductApps
                                 .Include(x => x.AddOns)
                                 .FirstOrDefaultAsync(
                x => x.Id == DbKeys.ClientProductAppIds.PcMacApp1
                );

            productMapping.ProductId    = DbKeys.ProductIds.Internal;
            productMapping.Title        = internalProduct.Name;
            productMapping.MaxSiteCount = 500; // was previously 5

            // Remove any previously seeded add-ons (the new product doesn't support any)
            if (productMapping.AddOns != null)
            {
                (productMapping.AddOns as List <ClientProductAddOn>).RemoveAll(x => true);
            }

            // Done
            await _connectDb.SaveChangesAsync();

            return(MigrationResult.Success("Created product and mapped to PcMac client."));
        }
Esempio n. 5
0
        //========================================================    CREATE  ==============================================
        #region
        public async Task <T> CreateNTU(T entity)
        {
            try
            {
                await _db.Set <T>().AddAsync(entity);

                await _db.SaveChangesAsync();

                return(await Task.FromResult(entity));
            }
            catch (Exception e)
            {
                return(await Task.FromResult <T>(null));
            }
        }
Esempio n. 6
0
        public static async Task <T> updateModel(ConnectDbContext _context, T model)
        {
            _context.Entry(model).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(model);
        }
Esempio n. 7
0
        public async Task <SiteAlert> SaveAsync(SiteAlert siteAlert)
        {
            siteAlert.Posted = DateTime.Now;
            var model = _db.SiteAlerts.FirstOrDefault(x => x.Id == siteAlert.Id);

            if (model != null)
            {
                model.Title         = siteAlert.Title;
                model.Posted        = siteAlert.Posted;
                model.Status        = siteAlert.Status;
                model.StartDate     = siteAlert.StartDate;
                model.EndDate       = siteAlert.EndDate;
                model.VersionCode   = siteAlert.VersionCode;
                model.ContentTreeId = siteAlert.ContentTreeId;

                _db.SiteAlerts.Update(model);
            }
            else
            {
                //_db.Entry(siteAlert).State = EntityState.Added;
                _db.SiteAlerts.Add(siteAlert);
            }

            await _db.SaveChangesAsync();

            return(siteAlert);
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            var announcementContentType = AnnouncementManager.CONTENT_TYPE_ANNOUNCEMENTPOST;

            // Fail if cannot connect to db
            if (_announcementDbContext.Database.TryTestConnection() == false || _connectDbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // remove any versioning records that are in an invalid state
            await _connectDbContext.Database.ExecuteNonQueryAsync($@"
                DELETE FROM cms.ContentVersion WHERE ContentType = '{announcementContentType}' AND JsonData IS NULL
            ");

            // Ensure UserId is set for remaining versions
            // NOTE: Will only affect QA / Dev environments where UserIds weren't being saved during early test versions
            await _announcementDbContext.Database.ExecuteNonQueryAsync(@"
                UPDATE cms.ContentVersion SET UserId = bp.UserId
                FROM plugin.AnnouncementPost bp
                WHERE cms.ContentVersion.ContentId = bp.Id
                    AND cms.ContentVersion.UserId IS NULL
            ");

            // Identify announcements with valid version data to skip in next step
            // NOTE: These won't exist on production but might exist in dev / test environments
            var announcementIdsToSkip = await _connectDbContext.ContentVersions
                                        .Where(x =>
                                               x.ContentType == announcementContentType &&
                                               x.JsonData != null
                                               )
                                        .Select(x => x.ContentId).ToArrayAsync();


            // Identify announcement posts that have missing version data
            var announcementPostsToMigrate = await _announcementDbContext.AnnouncementPosts
                                             .Where(x => !announcementIdsToSkip.Contains(x.Id))
                                             .ToListAsync();


            // Insert the missing verision data
            foreach (var announcementPost in announcementPostsToMigrate)
            {
                var version = new ContentVersion(announcementContentType, announcementPost.Id);

                version.VersionCode = announcementPost.VersionCode;
                version.Created     = announcementPost.Posted;
                version.Status      = announcementPost.Published ? ContentStatus.Published : ContentStatus.Draft;
                version.UserId      = announcementPost.UserId;
                version.JsonData    = SerializeVersionData(announcementPost);

                _connectDbContext.ContentVersions.Add(version);
            }

            await _connectDbContext.SaveChangesAsync();


            return(MigrationResult.Success($"Inserted {announcementPostsToMigrate.Count} missing AnnouncementPost version records"));
        }
Esempio n. 9
0
        public async Task <bool> UpdateFolderAsync(Folder folder)
        {
            var folder1 = await _db.Folders.Where(x => x.Id == folder.Id).FirstOrDefaultAsync();

            if (folder1 == null)
            {
                return(false);
            }
            else
            {
                folder1.Title        = folder.Title;
                folder1.DocumentType = folder.DocumentType;
                await _db.SaveChangesAsync();

                return(true);
            }
        }
Esempio n. 10
0
        public async Task <string> CreateSiteCollectionAsync(SiteCollection siteCollection)
        {
            Ensure.That(siteCollection != null);

            try
            {
                siteCollection.Id = KeyGen.NewGuid();
                _db.SiteCollections.Add(siteCollection);

                await _db.SaveChangesAsync();

                return(siteCollection.Id);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 11
0
        public async Task UnscheduleNotificationAsync(string Id)
        {
            var note = await _connectDb.Notifications.Where(x => x.Id == Id).FirstOrDefaultAsync();

            if (note == null)
            {
                throw new Exception("Unable to unschedule notification (notification not found [" + Id + "])");
            }
            if ((note.Status == NotificationStatus.Scheduled))
            {
                note.Status = NotificationStatus.Draft;
                await _connectDb.SaveChangesAsync();
            }
            else if (note.Status != NotificationStatus.Draft)
            {
                throw new Exception("Unable to unschedule notification (Id:" + Id + ", Status:" + note.Status + ")");
            }
        }
Esempio n. 12
0
        public async Task <string> CreateCategoryAsync(Category category)
        {
            Ensure.That(category != null);

            try
            {
                category.Id = KeyGen.NewGuid();
                _db.Categories.Add(category);

                await _db.SaveChangesAsync();

                return(category.Id);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 13
0
        public async Task <ResourceClaim> AddResourceClaimAsync(string resourceId, string resourceType, string userId, string claimType)
        {
            if (_db.ResourceClaims.Any(x => x.ResourceId == resourceId && x.ResourceType == resourceType && x.UserId == userId && x.ClaimType == claimType))
            {
                return(null);
            }

            var resourceClaim = new ResourceClaim
            {
                ResourceId   = resourceId,
                ResourceType = resourceType,
                UserId       = userId,
                ClaimType    = claimType
            };

            _db.ResourceClaims.Add(resourceClaim);

            await _db.SaveChangesAsync();

            return(resourceClaim);
        }
Esempio n. 14
0
        public async Task <string> CreateAsync(PageMaster pageMaster)
        {
            Ensure.Argument.NotNull(pageMaster);

            try
            {
                if (string.IsNullOrEmpty(pageMaster.Id))
                {
                    pageMaster.Id = KeyGen.NewGuid();
                }

                _db.PageMasters.Add(pageMaster);

                await _db.SaveChangesAsync();

                return(pageMaster.Id);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 15
0
        //public async Task<List<UserGroupMembership>> GetUserGroupMembershipsAsync(string userGroupId)
        //{
        //    var query = _connectDb.UserGroupMemberships.AsNoTracking();
        //        //.Join(_db.NotificationUserGroups.Where(x => x.NotificationId == notificationId),
        //        //    ug => ug.Id,
        //        //    ng => ng.UserGroupId,
        //        //    (ug, ng) => ug);

        //    var results = await query.ToListAsync();

        //    return results;
        //}

        public async Task UpdateUserGroupAsync(UserGroup userGroup)
        {
            var oldGroup = await _connectDb.UserGroups.Where(x => x.Id == userGroup.Id).FirstOrDefaultAsync();

            if (oldGroup == null)
            {
                throw new Exception("Unable to find UserGroup (Id = " + userGroup.Id + ")");
            }
            oldGroup.Name = userGroup.Name;
            oldGroup.AllowPublicEnrollment = userGroup.AllowPublicEnrollment;
            await _connectDb.SaveChangesAsync();
        }
Esempio n. 16
0
        public virtual async Task DeleteAsync(string documentId)
        {
            var documentItems = _readDb
                                .FolderItems
                                .Where(x => x.DocumentId == documentId).ToList();

            if (documentItems != null)
            {
                _readDb.FolderItems.RemoveRange(documentItems);
                await _readDb.SaveChangesAsync();
            }

            var document = _readDb
                           .FileDocuments
                           .FirstOrDefault(x => x.DocumentId == documentId);

            if (document != null)
            {
                _readDb.FileDocuments.Remove(document);
                await _readDb.SaveChangesAsync();
            }

            //TODO Send request to Drive to remove physical file
        }
        private async Task <bool> UpdateFlagOnExistingSites()
        {
            var homePages = _connectDb.Pages.Where(x => x.Path == "/").ToList();

            if (homePages.Any())
            {
                foreach (var page in homePages)
                {
                    page.IsHomePage = true;
                    _connectDb.Pages.Update(page);
                }

                await _connectDb.SaveChangesAsync();
            }

            return(await Task.FromResult(true));
        }
Esempio n. 18
0
        public async Task <Tag> AddTag(string userId, string tagName)
        {
            var existingTag = await _db.Tags.FirstOrDefaultAsync(x => x.UserId == userId && x.TagName == tagName);

            if (existingTag != null)
            {
                return(existingTag);
            }

            var newTag = new Tag
            {
                Id       = Guid.NewGuid().ToString("N"),
                TagName  = tagName,
                UserId   = userId,
                IsActive = true,
            };

            _db.Tags.Add(newTag);

            await _db.SaveChangesAsync();

            return(newTag);
        }
Esempio n. 19
0
        public async Task <bool> UpdateAsync(Page page)
        {
            Ensure.Argument.NotNull(page);

            var tempPage = _db.Pages.FirstOrDefault(x => x.Id == page.Id);

            if (tempPage == null)
            {
                return(false);
            }


            tempPage.Title        = page.Title;
            tempPage.Keywords     = page.Keywords;
            tempPage.Summary      = page.Summary;
            tempPage.Path         = CleanRoute(page.Path);
            tempPage.PageMasterId = page.PageMasterId;
            tempPage.IsPrivate    = page.IsPrivate;
            tempPage.ParentPageId = page.ParentPageId;

            // Trimming strings
            if (!string.IsNullOrEmpty(tempPage.Title))
            {
                tempPage.Title = tempPage.Title.Trim();
            }

            if (!string.IsNullOrEmpty(tempPage.Keywords))
            {
                tempPage.Keywords = tempPage.Keywords.Trim();
            }

            if (!string.IsNullOrEmpty(tempPage.Summary))
            {
                tempPage.Summary = tempPage.Summary.Trim();
            }

            try
            {
                await _db.SaveChangesAsync();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 20
0
        public async Task AddFolderTagAsync(IFolder folder, string tag)
        {
            var exists = await HasTagAsync(folder, tag);

            // TODO: Consider throwing an error vs. not adding
            if (!exists)
            {
                var entity = BuildFolderTag(folder, tag);

                _db.FolderTags.Add(entity);
                await _db.SaveChangesAsync();
            }
        }
Esempio n. 21
0
        public async Task DeleteNavMenuAsync(string navMenuId)
        {
            Ensure.Argument.NotNull(navMenuId);

            var menu = await _db.NavigationMenu.FirstOrDefaultAsync(x => x.Id == navMenuId);

            if (menu != null)
            {
                var items = await _db.NavigationMenuItems.Where(x => x.NavMenuId == navMenuId).ToListAsync();

                foreach (var item in items)
                {
                    _db.NavigationMenuItems.Remove(item);
                }
                _db.NavigationMenu.Remove(menu);
                await _db.SaveChangesAsync();
            }
        }
Esempio n. 22
0
        /// =============================================== Create ======================================
        /// <summary>
        /// Create entity.
        /// Before creating a new entity that is required to check if an entity already exists (email, phone, code, ...).
        /// If Checkvalue is false will insert success
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="Checkvalue"></param>
        /// <returns>Entity</returns>
        #region
        public async Task <T> Create(T entity, bool CheckIsExist)
        {
            try
            {
                if (CheckIsExist)
                {
                    return(await Task.FromResult <T>(null));
                }
                await _db.Set <T>().AddAsync(entity);

                await _db.SaveChangesAsync();

                return(await Task.FromResult(entity));
            }
            catch (Exception e)
            {
                var error = e.Message;
                return(await Task.FromResult <T>(null));
            }
        }
 public async Task <int> SaveChangesAsync(CancellationToken cancellationToken)
 {
     return(await _context.SaveChangesAsync(cancellationToken));
 }
Esempio n. 24
0
        public async Task RemoveSiteCollectionsAsync(string siteId, IList <string> siteCollectionIds)
        {
            var siteCollections = await _db.SiteCollectionMaps
                                  .Where(x => x.SiteId == siteId)
                                  .Where(x => siteCollectionIds.Contains(x.SiteCollectionId))
                                  .ToListAsync();

            _db.SiteCollectionMaps.RemoveRange(siteCollections);
            await _db.SaveChangesAsync();
        }
Esempio n. 25
0
        public async Task UpdateVersionLabel(string contentType, string contentId, string versionCode, string versionLabel)
        {
            var version = await GetVersionInfo(contentType, contentId, versionCode);

            if (version == null)
            {
                throw new NullReferenceException("Cannot update version label. Version does not exist.");
            }

            if (string.IsNullOrEmpty(versionLabel))
            {
                versionLabel = "Unlabeled Version";
            }

            version.VersionLabel = versionLabel;

            await _connectDb.SaveChangesAsync();
        }