コード例 #1
0
ファイル: FileBiz.cs プロジェクト: mrgrayhat/Khodkar-Platform
        public async Task <bool> Delete(JObject data)
        {
            dynamic fileData = data;
            int     id;

            try
            {
                id = fileData.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "File Id"));
            }
            var file = await _contentManagementContext.Files.SingleOrDefaultAsync(fl => fl.Id == id);

            if (file == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FileNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(file, null, false);


            _contentManagementContext.Files.Remove(file);

            await _contentManagementContext.SaveChangesAsync();

            return(true);
        }
コード例 #2
0
        public async Task <ApplicationLocalGroup> SaveGroupTranslate(JObject data)
        {
            dynamic localGroupDto = data;
            int?    localGroupId  = localGroupDto.Id;
            var     localGroup    = new ApplicationLocalGroup()
            {
                Id = localGroupId ?? 0
            };

            var currentLocalGroup =
                await
                _securityContext.ApplicationLocalGroups.AsNoTracking().Include(md => md.Group)
                .SingleOrDefaultAsync(md => md.Id == localGroup.Id);

            if (localGroup.Id > 0)
            {
                if (currentLocalGroup == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.GroupNotFound));
                }

                localGroup            = currentLocalGroup;
                localGroup.RowVersion = localGroupDto.RowVersion;

                _securityContext.ApplicationLocalGroups.Attach(localGroup);
            }
            else
            {
                _securityContext.ApplicationLocalGroups.Add(localGroup);
            }

            localGroup.GroupId     = localGroupDto.ItemId;
            localGroup.Name        = localGroupDto.Name;
            localGroup.Description = localGroupDto.Description;
            localGroup.Language    = localGroupDto.Language;


            var currentGroup = await _securityContext.Groups
                               .AsNoTracking().SingleOrDefaultAsync(md => md.Id == localGroup.GroupId);

            if (currentGroup == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.GroupNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(currentGroup, localGroupDto, false);


            localGroup.Status = localGroupDto.Status;
            await _securityContext.SaveChangesAsync();

            return(localGroup);
        }
コード例 #3
0
        public async Task <bool> Delete(JObject data)
        {
            dynamic serviceData = data;
            int     id;

            try
            {
                id = serviceData.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "Service Id"));
            }
            var service = await _contentManagementContext
                          .MasterDataKeyValues.SingleOrDefaultAsync(sr => sr.Id == id && sr.TypeId == (int)EntityIdentity.Service);

            if (service == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.ServiceNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(service, null, false);


            if (service.EditMode)
            {
                _sourceControl.CheckCodeCheckOute(service);
            }

            var useCount = await _contentManagementContext.WebPages.Where(wp => wp.Services.Contains(service.PathOrUrl))
                           .CountAsync();

            if (useCount > 0)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.InUseItem, service.Name));
            }


            if (_fileSystemManager.FileExist(Path.Combine(Config.ServicesSourceCodePath, service.Guid + ".js")))
            {
                _sourceControl.RecycleBin(Config.ServicesSourceCodePath, service.Guid + ".js", codeNameIsFolder: false);

                DeleteFile(Config.ServicesSourceCodePath, service.Guid, ".js");
            }

            _contentManagementContext.MasterDataKeyValues.Remove(service);

            await _contentManagementContext.SaveChangesAsync();

            return(true);
        }
コード例 #4
0
ファイル: FileBiz.cs プロジェクト: mrgrayhat/Khodkar-Platform
        public async Task <LocalFile> SaveTranslate(JObject data)
        {
            dynamic localFileDto = data;
            int?    localFileId  = localFileDto.Id;
            var     localFile    = new LocalFile
            {
                Id = localFileId ?? 0
            };

            var currentLocalFile = await _contentManagementContext.LocalFiles.AsNoTracking().Include(md => md.File).SingleOrDefaultAsync(md => md.Id == localFile.Id);

            if (localFile.Id > 0)
            {
                if (currentLocalFile == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.TranslateNotFound));
                }

                localFile            = currentLocalFile;
                localFile.RowVersion = localFileDto.RowVersion;

                _contentManagementContext.LocalFiles.Attach(localFile);
            }
            else
            {
                _contentManagementContext.LocalFiles.Add(localFile);
            }

            localFile.FileId      = localFileDto.ItemId;
            localFile.Name        = localFileDto.Name;
            localFile.Description = localFileDto.Description;
            localFile.Language    = localFileDto.Language;

            var currentFile = await _contentManagementContext.Files
                              .AsNoTracking().SingleOrDefaultAsync(md => md.Id == localFile.FileId);

            if (currentFile == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.PathNotFound, "FileId"));
            }


            AuthorizeManager.SetAndCheckModifyAndAccessRole(currentFile, localFileDto, false);


            localFile.Status = localFileDto.Status;
            await _contentManagementContext.SaveChangesAsync();

            return(localFile);
        }
コード例 #5
0
        public async Task <MasterDataLocalKeyValue> SaveTranslate(JObject data)
        {
            dynamic masterDataLocalDto = data;
            int?    masterDataLocalId  = masterDataLocalDto.Id;
            var     masterDataLocal    = new MasterDataLocalKeyValue
            {
                Id = masterDataLocalId ?? 0
            };

            var currentMasterDataLocal = await ContentManagementContext.MasterDataLocalKeyValues.Include(md => md.MasterDataKeyValue)
                                         .SingleOrDefaultAsync(md => md.Id == masterDataLocal.Id);

            if (masterDataLocal.Id > 0)
            {
                if (currentMasterDataLocal == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.TranslateNotFound));
                }

                masterDataLocal            = currentMasterDataLocal;
                masterDataLocal.RowVersion = masterDataLocalDto.RowVersion;

                ContentManagementContext.MasterDataLocalKeyValues.Attach(masterDataLocal);
            }
            else
            {
                ContentManagementContext.MasterDataLocalKeyValues.Add(masterDataLocal);
            }

            masterDataLocal.MasterDataKeyValueId = masterDataLocalDto.ItemId;
            masterDataLocal.Name        = masterDataLocalDto.Name;
            masterDataLocal.Description = masterDataLocalDto.Description;
            masterDataLocal.Language    = masterDataLocalDto.Language;

            var currentMasterData = await ContentManagementContext.MasterDataKeyValues
                                    .AsNoTracking().SingleOrDefaultAsync(md => md.Id == masterDataLocal.MasterDataKeyValueId);

            if (currentMasterData == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.PathNotFound, "MasterDataKeyValueId"));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(currentMasterData, masterDataLocalDto, false);


            masterDataLocal.Status = masterDataLocalDto.Status;
            await ContentManagementContext.SaveChangesAsync();

            return(masterDataLocal);
        }
コード例 #6
0
        public async Task <string> GetCodeContentAsync(int codeId, string path)
        {
            path = path.Replace(Config.UrlDelimeter, Helper.RootUrl);
            var code = ContentManagementContext.MasterDataKeyValues.FirstOrDefault(sr => sr.Id == codeId);

            if (code == null || !path.ToLower().StartsWith(code.PathOrUrl.ToLower()))
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.CodeNotFound));
            }
            AuthorizeManager.SetAndCheckModifyAndAccessRole(code, null, false);
            if (await FileSystemManager.FileExistAsync(AuthorizeManager
                                                       .AuthorizeActionOnPath(path, ActionKey.ReadFromDisk)))
            {
                return(await FileSystemManager.ReadAsync(path));
            }
            throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.CodeNotFound));
        }
コード例 #7
0
        public async Task <bool> Delete(JObject data)
        {
            dynamic langData = data;
            int     id;

            try
            {
                id = langData.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "LanguageAndCulture Id"));
            }
            var languageAndCulture = await _contentManagementContext.LanguageAndCultures
                                     .SingleOrDefaultAsync(ln => ln.Id == id);

            if (languageAndCulture == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.LanguageAndCultureNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(languageAndCulture, null, false);

            var useCount = await _contentManagementContext.WebPages.Where(wp => wp.Language == languageAndCulture.Language)
                           .CountAsync();

            if (useCount > 0)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.InUseItem, languageAndCulture.Language));
            }


            DeleteFile(Config.ResourcesSourceCodePath, languageAndCulture.Language, ".js");
            DeleteFile(Config.ResourcesDistPath, languageAndCulture.Language, ".js");

            _contentManagementContext.LanguageAndCultures.Remove(languageAndCulture);

            await _contentManagementContext.SaveChangesAsync();

            UpdateWebConfigSetting(languageAndCulture, ActionKey.Delete);
            return(true);
        }
コード例 #8
0
        public async Task <bool> DeleteUser(JObject user)
        {
            dynamic userDto = user;
            int     id;

            try
            {
                id = userDto.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "User Id"));
            }
            var appUser = await _userManager.FindByIdAsync(id);

            if (appUser == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.UserNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(appUser, null, false);

            var userProfileId = appUser.Id;

            var result = await _userManager.DeleteAsync(appUser);

            if (result.Succeeded)
            {
                var userProfile = await _contentManagementContext.Users.FirstOrDefaultAsync(up => up.Id == userProfileId);

                if (userProfile != null)
                {
                    _contentManagementContext.Users.Remove(userProfile);

                    await _contentManagementContext.SaveChangesAsync();
                }

                return(true);
            }

            throw new KhodkarInvalidException(result.Errors.First());
        }
コード例 #9
0
        public async Task <bool> Delete(JObject data)
        {
            dynamic linkData = data;
            int     id;

            try
            {
                id = linkData.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "Link Id"));
            }
            var link = await _contentManagementContext.Links.SingleOrDefaultAsync(md => md.Id == id)
            ;

            if (link == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.LinkNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(link, null, false);


            var useCount = await _contentManagementContext.WebPages.Where(wp => wp.Url == link.Url)
                           .CountAsync();

            if (useCount > 0)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.InUseItem, link.Text));
            }


            _contentManagementContext.Links.Remove(link);

            await _contentManagementContext.SaveChangesAsync();

            return(true);
        }
コード例 #10
0
        public async Task <bool> DeleteGroup(JObject data)
        {
            dynamic groupData = data;
            int     id;

            try
            {
                id = groupData.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "Group Id"));
            }
            var group = await _securityContext.Groups.FindAsync(id);

            if (group == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.GroupNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(group, null, false);


            var useCount = await _securityContext.ApplicationUserGroups.Where(gr => gr.GroupId == group.Id)
                           .CountAsync();

            if (useCount > 0)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.InUseItem, group.Name));
            }


            _securityContext.Groups.Remove(group);
            await _securityContext.SaveChangesAsync();

            CacheManager.Remove(CacheManager.GetGroupKey(CacheKey.Aspect.ToString(), group.Id));
            return(true);
        }
コード例 #11
0
        public async Task <bool> DeleteRole(JObject data)
        {
            dynamic roleData = data;
            int     id;

            try
            {
                id = roleData.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "Role Id"));
            }
            var role = await _roleManager.FindByIdAsync(id);

            if (role == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RoleNotFound));
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(role, null, false);


            var useCount = await _securityContext.ApplicationGroupRoles.Where(gr => gr.RoleId == role.Id)
                           .CountAsync();

            if (useCount > 0)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.InUseItem, role.Name));
            }


            await _roleManager.DeleteAsync(role);

            return(true);
        }
コード例 #12
0
        public async Task <MasterDataKeyValue> Save(JObject data)
        {
            dynamic serviceDto = data;
            int?    serviceId  = serviceDto.Id;
            var     service    = new MasterDataKeyValue
            {
                Id     = serviceId ?? 0,
                TypeId = (int)EntityIdentity.Service
            };
            bool isNew = serviceDto.IsNew;


            bool   checkIn = serviceDto.CheckIn;
            string comment = serviceDto.Comment;

            var currentService = await _contentManagementContext
                                 .MasterDataKeyValues.AsNoTracking().SingleOrDefaultAsync(sv => sv.Id == service.Id && sv.TypeId == (int)EntityIdentity.Service);

            if (!isNew)
            {
                if (currentService == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.ServiceNotFound));
                }

                if (currentService.EditMode)
                {
                    _sourceControl.CheckCodeCheckOute(currentService);
                }

                service            = currentService;
                service.RowVersion = serviceDto.RowVersion;

                _contentManagementContext.MasterDataKeyValues.Attach(service);
            }
            else
            {
                _contentManagementContext.MasterDataKeyValues.Add(service);
            }



            string serviceCode = serviceDto.Code;

            if (serviceCode.IndexOf(_codeTemplate.ServicePrefix, StringComparison.Ordinal) != 0)
            {
                serviceCode = _codeTemplate.ServicePrefix + "." + serviceCode;
            }

            string serviceUrl = serviceDto.Url;

            if (serviceUrl.IndexOf(Helper.RootUrl, StringComparison.Ordinal) != 0)
            {
                serviceUrl = Helper.RootUrl + serviceUrl;
            }
            if (serviceUrl.LastIndexOf(Helper.RootUrl, StringComparison.Ordinal) == serviceUrl.Length - 1 && serviceUrl != "/")
            {
                serviceUrl = serviceUrl.Remove(serviceUrl.LastIndexOf(Helper.RootUrl, StringComparison.Ordinal));
            }
            var repeatedService = await _contentManagementContext
                                  .MasterDataKeyValues.Where(sr => sr.PathOrUrl == serviceUrl && sr.TypeId == (int)EntityIdentity.Service).CountAsync()
            ;

            if ((repeatedService > 0 && isNew) || (repeatedService > 1 && !isNew))
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RepeatedValue, serviceUrl));
            }


            int?parentId = serviceDto.ParentId;

            if (currentService?.ParentId != parentId || isNew)
            {
                var parentCode = await _contentManagementContext
                                 .MasterDataKeyValues.SingleOrDefaultAsync(sr => sr.Id == parentId && sr.TypeId == (int)EntityIdentity.Service);

                if (parentCode == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                }
                AuthorizeManager.CheckParentNodeModifyAccessForAddingChildNode(parentCode, parentCode.Id);
            }

            service.ParentId = parentId;

            service.Name = serviceDto.Name;
            service.Code = serviceCode;

            repeatedService = await _contentManagementContext
                              .MasterDataKeyValues.Where(sr => sr.Code == service.Code && sr.TypeId == (int)EntityIdentity.Service)
                              .CountAsync();

            if ((repeatedService > 0 && isNew) || (repeatedService > 1 && !isNew))
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RepeatedValue, service.Code));
            }


            service.Guid        = serviceDto.Guid;
            service.Description = serviceDto.Description;
            service.Version     = (currentService?.Version ?? 0) + 1;
            service.PathOrUrl   = serviceUrl;
            try
            {
                service.Order = serviceDto.Order;
            }
            catch (Exception)
            {
                service.Order = 1;
            }

            //LOG SERVICE EVENT?1:TRUE,2:FALSE
            try
            {
                service.Key = serviceDto.Key;
            }
            catch (Exception)
            {
                service.Key = 0;
            }

            service.IsLeaf   = serviceDto.IsLeaf;
            service.Language = Config.DefaultsLanguage;

            //if(service.IsLeaf)
            if (currentService != null)
            {
                service.ViewRoleId   = currentService.ViewRoleId;
                service.ModifyRoleId = currentService.ModifyRoleId;
                service.AccessRoleId = currentService.AccessRoleId;
            }
            AuthorizeManager.SetAndCheckModifyAndAccessRole(service, serviceDto);

            service.Status      = serviceDto.Status;
            service.EditMode    = serviceDto.EditMode;
            service.EnableCache = serviceDto.EnableCache;
            try
            {
                service.SlidingExpirationTimeInMinutes = serviceDto.SlidingExpirationTimeInMinutes;
            }
            catch (Exception)
            {
                service.SlidingExpirationTimeInMinutes = 0;
            }
            await _contentManagementContext.SaveChangesAsync();

            string jsCode = serviceDto.JsCode;

            if (!string.IsNullOrEmpty(jsCode))
            {
                await _sourceControl.AddChange(Config.ServicesSourceCodePath, service.Guid + ".js", jsCode, service.Version,
                                               comment);

                if (checkIn)
                {
                    await WriteFileAsync(Config.ServicesSourceCodePath, service.Guid, ".js", jsCode);
                }
            }


            CacheManager.ClearAllItemContainKey(service.PathOrUrl);
            UpdateServiceSettingOfWebConfig(service);
            return(service);
        }
コード例 #13
0
        public async Task <MasterDataKeyValue> Save(JObject data, bool isAuthroize = false)
        {
            dynamic masterDataDto = data;
            int?    masterDataId  = masterDataDto.Id;
            var     masterData    = new MasterDataKeyValue
            {
                Id = masterDataId ?? 0
            };
            bool isNew = masterDataDto.IsNew;

            //bool isPath;

            //try
            //{
            //    isPath = masterDataDto.IsPath;
            //}
            //catch (Exception)
            //{

            //    isPath = false;
            //}

            //bool isPathSecond;

            //try
            //{
            //    isPathSecond = masterDataDto.IsPathSecond;
            //}
            //catch (Exception)
            //{

            //    isPathSecond = false;
            //}

            int pathOrUrlProtocolId, secondPathOrUrlProtocolId;

            try
            {
                pathOrUrlProtocolId = masterDataDto.PathOrUrlProtocolId;
            }
            catch (Exception)
            {
                pathOrUrlProtocolId = (int)Protocol.LocalUrlPorotocol;
            }

            try
            {
                secondPathOrUrlProtocolId = masterDataDto.SecondPathOrUrlProtocolId;
            }
            catch (Exception)
            {
                secondPathOrUrlProtocolId = (int)Protocol.LocalUrlPorotocol;
            }

            var currentMasterData = await ContentManagementContext.MasterDataKeyValues.AsNoTracking().SingleOrDefaultAsync(md => md.Id == masterData.Id);

            if (!isNew)
            {
                if (currentMasterData == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.MasterDataKeyValuesNotFound));
                }

                if (currentMasterData.EditMode)
                {
                    SourceControl.CheckCodeCheckOute(masterData);
                }

                masterData            = currentMasterData;
                masterData.RowVersion = masterDataDto.RowVersion;

                ContentManagementContext.MasterDataKeyValues.Attach(masterData);
            }
            else
            {
                ContentManagementContext.MasterDataKeyValues.Add(masterData);
            }
            masterData.TypeId = masterDataDto.TypeId;

            //if (!isPath)
            //{
            //    if (masterDataUrl.IndexOf(Helper.RootUrl, StringComparison.Ordinal) != 0)
            //    {
            //        masterDataUrl = Helper.RootUrl + masterDataUrl;
            //    }

            //}
            //else
            //{

            //    if ( masterDataUrl.IndexOf("~", StringComparison.Ordinal) != 0)
            //    {
            //        if (masterDataUrl.IndexOf(Helper.RootUrl, StringComparison.Ordinal) != 0)
            //            masterDataUrl = "~" + Helper.RootUrl + masterDataUrl;
            //        else
            //            masterDataUrl = "~" + masterDataUrl;
            //    }
            //}
            string masterDataUrlOrPath = ProperPathOrUrl(Convert.ToString(masterDataDto.PathOrUrl), pathOrUrlProtocolId);

            if (masterDataUrlOrPath != Helper.RootUrl && masterData.TypeId != (int)EntityIdentity.BundleSource)
            {
                var repeatedMasterData =
                    await
                    ContentManagementContext.MasterDataKeyValues.Where(
                        md => md.PathOrUrl == masterDataUrlOrPath && md.TypeId == masterData.TypeId).CountAsync()
                ;

                if ((repeatedMasterData > 0 && isNew) || (repeatedMasterData > 1 && !isNew))
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RepeatedValue, masterDataUrlOrPath));
                }
            }
            masterData.PathOrUrl = masterDataUrlOrPath;
            try
            {
                int parentId = masterDataDto.ParentId;
                if (currentMasterData?.ParentId != parentId || isNew)
                {
                    var parentCode = await ContentManagementContext.MasterDataKeyValues.SingleOrDefaultAsync(md => md.Id == parentId);

                    if (parentCode == null)
                    {
                        throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                    }
                    AuthorizeManager.CheckParentNodeModifyAccessForAddingChildNode(parentCode, parentCode.Id);
                }
                masterData.ParentId = parentId;
            }
            catch (KhodkarInvalidException)
            {
                throw;
            }
            catch (Exception)
            {
                masterData.ParentId = null;
            }

            try
            {
                masterData.Key = masterDataDto.Key;
            }
            catch (Exception)
            {
                masterData.Key = null;
            }

            try
            {
                masterData.Value = masterDataDto.Value;
            }
            catch (Exception)
            {
                masterData.Value = null;
            }

            try
            {
                masterData.ForeignKey1 = masterDataDto.ForeignKey1;
            }
            catch (Exception)
            {
                masterData.ForeignKey1 = null;
            }

            try
            {
                masterData.ForeignKey2 = masterDataDto.ForeignKey2;
            }
            catch (Exception)
            {
                masterData.ForeignKey2 = null;
            }

            try
            {
                masterData.ForeignKey3 = masterDataDto.ForeignKey3;
            }
            catch (Exception)
            {
                masterData.ForeignKey3 = null;
            }

            masterData.SecondCode = masterDataDto.SecondCode;


            string secondMasterDataPathOrUrl = masterDataDto.SecondPathOrUrl;

            masterData.SecondPathOrUrl = ProperPathOrUrl(secondMasterDataPathOrUrl, secondPathOrUrlProtocolId);

            masterData.Name = masterDataDto.Name;
            masterData.Code = masterDataDto.Code;
            if (masterData.Code != null)
            {
                var repeatedMasterData =
                    await
                    ContentManagementContext.MasterDataKeyValues.Where(
                        md => md.Code == masterData.Code && md.TypeId == masterData.TypeId).CountAsync();

                if ((repeatedMasterData > 0 && isNew) || (repeatedMasterData > 1 && !isNew))
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RepeatedValue, masterData.Code));
                }
            }



            masterData.Guid        = masterDataDto.Guid;
            masterData.Description = masterDataDto.Description;
            masterData.Data        = masterDataDto.Data;
            masterData.Version     = (currentMasterData?.Version ?? 0) + 1;

            try
            {
                masterData.Order = masterDataDto.Order;
            }
            catch (Exception)
            {
                masterData.Order = 1;
            }
            masterData.IsLeaf = masterDataDto.IsLeaf;
            masterData.IsType = masterDataDto.IsType;

            if (masterData.IsType && masterData.IsLeaf)
            {
                throw new ConstraintException(LanguageManager.ToAsErrorMessage(ExceptionKey.MasterDataTypeIsLeaf));
            }

            try
            {
                masterData.TypeId = masterDataDto.TypeId;
            }
            catch (Exception)
            {
                throw new ValidationException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "TypeId"));
            }

            try
            {
                masterData.ParentTypeId = masterDataDto.ParentTypeId;
            }
            catch (Exception)
            {
                if (masterData.IsType)
                {
                    throw new ValidationException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "ParentTypeId"));
                }

                masterData.ParentTypeId = null;
            }

            masterData.Language = Config.DefaultsLanguage;
            //if(masterData.IsLeaf)
            if (masterData.TypeId == (int)EntityIdentity.Permission && !isAuthroize)
            {
                throw new UnauthorizedAccessException(LanguageManager.ToAsErrorMessage(ExceptionKey.InvalidGrant));
            }

            if (currentMasterData != null)
            {
                masterData.ViewRoleId   = currentMasterData.ViewRoleId;
                masterData.ModifyRoleId = currentMasterData.ModifyRoleId;
                masterData.AccessRoleId = currentMasterData.AccessRoleId;
            }


            AuthorizeManager.SetAndCheckModifyAndAccessRole(masterData, masterDataDto);


            masterData.Status      = masterDataDto.Status;
            masterData.EditMode    = masterDataDto.EditMode;
            masterData.EnableCache = masterDataDto.EnableCache;
            try
            {
                masterData.SlidingExpirationTimeInMinutes = masterDataDto.SlidingExpirationTimeInMinutes;
            }
            catch (Exception)
            {
                masterData.SlidingExpirationTimeInMinutes = 0;
            }
            await ContentManagementContext.SaveChangesAsync();

            if (masterData.TypeId == (int)EntityIdentity.SqlServerConnections)
            {
                WebConfigManager.AddOrUpdateConnection(masterData.Code, masterData.SecondCode,
                                                       ConnectionProvider.SqlServer);
            }
            else
            {
                UpdateMasterDatakeyVlaueSettingOfWebConfig(masterData);
            }
            return(masterData);
        }
コード例 #14
0
        public async Task <MasterDataKeyValue> Delete(JObject data, bool isAuthroize = false)
        {
            dynamic masterDataKeyValueData = data;
            int     id;

            try
            {
                id = masterDataKeyValueData.Id;
            }
            catch (Exception)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FieldMustBeNumeric, "MasterDataKeyValue Id"));
            }
            var masterDatakeyValue = await ContentManagementContext.MasterDataKeyValues.SingleOrDefaultAsync(md => md.Id == id);

            if (masterDatakeyValue == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.MasterDataKeyValuesNotFound));
            }

            if (masterDatakeyValue.TypeId == (int)EntityIdentity.Permission && !isAuthroize)
            {
                throw new UnauthorizedAccessException(LanguageManager.ToAsErrorMessage(ExceptionKey.InvalidGrant));
            }
            AuthorizeManager.SetAndCheckModifyAndAccessRole(masterDatakeyValue, null, false);


            if (masterDatakeyValue.EditMode)
            {
                SourceControl.CheckCodeCheckOute(masterDatakeyValue);
            }
            if (masterDatakeyValue.PathOrUrl != Helper.RootUrl)
            {
                var useCount = await ContentManagementContext.WebPages.Where(wp => wp.Services.Contains(masterDatakeyValue.PathOrUrl))
                               .CountAsync();

                if (useCount > 0)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.InUseItem, masterDatakeyValue.Name));
                }
            }
            var refrenceCount = await ContentManagementContext.MasterDataKeyValues.Where(md => md.ForeignKey1 == masterDatakeyValue.Id || md.ForeignKey2 == masterDatakeyValue.Id || md.ForeignKey3 == masterDatakeyValue.Id)
                                .CountAsync();

            if (refrenceCount > 0)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.InUseItem, masterDatakeyValue.Name));
            }


            ContentManagementContext.MasterDataKeyValues.Remove(masterDatakeyValue);


            await ContentManagementContext.SaveChangesAsync();

            if (masterDatakeyValue.TypeId == (int)EntityIdentity.SqlServerConnections)
            {
                WebConfigManager.RemoveConnection(masterDatakeyValue.Code);
            }
            return(masterDatakeyValue);
        }
コード例 #15
0
        public async Task <ApplicationRole> SaveRole(JObject role)
        {
            dynamic         roleDto = role;
            ApplicationRole applicationRole;
            bool            isNew = roleDto.IsNew;

            if (!isNew)
            {
                applicationRole = new ApplicationRole()
                {
                    Id = roleDto.Id
                };
                applicationRole = await _roleManager.FindByIdAsync(applicationRole.Id);

                if (applicationRole == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RoleNotFound));
                }
            }
            else
            {
                applicationRole = new ApplicationRole();
            }

            applicationRole.Name        = roleDto.Name;
            applicationRole.IsLeaf      = roleDto.IsLeaf;
            applicationRole.Description = roleDto.Description;
            try
            {
                applicationRole.Order = roleDto.Order;
            }
            catch (Exception)
            {
                applicationRole.Order = 0;
            }

            applicationRole.Status = roleDto.Status;

            try
            {
                int parentId = roleDto.ParentId;
                if (applicationRole.ParentId != parentId)
                {
                    var parentCode = await _roleManager.FindByIdAsync(parentId);

                    if (parentCode == null)
                    {
                        throw new KhodkarInvalidException(
                                  LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                    }
                    AuthorizeManager.CheckParentNodeModifyAccessForAddingChildNode(parentCode, parentCode.Id);
                }
                applicationRole.ParentId = parentId;
            }
            catch (KhodkarInvalidException)
            {
                throw;
            }
            catch (Exception)
            {
                applicationRole.ParentId = null;
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(applicationRole, roleDto);

            var roleresult = isNew
                ? await _roleManager.CreateAsync(applicationRole)
                : await _roleManager.UpdateAsync(applicationRole);

            if (!roleresult.Succeeded)
            {
                throw new KhodkarInvalidException(roleresult.Errors.First());
            }
            return(applicationRole);
        }
コード例 #16
0
        public async Task <LanguageAndCulture> Save(JObject data)
        {
            dynamic languageAndCultureDto = data;
            int?    languageAndCultureId  = languageAndCultureDto.Id;
            var     languageAndCulture    = new LanguageAndCulture()
            {
                Id = languageAndCultureId ?? 0
            };
            bool isNew   = languageAndCultureDto.isNew;
            bool publish = languageAndCultureDto.publish;
            var  currentLanguageAndCulture = await _contentManagementContext.LanguageAndCultures.AsNoTracking().SingleOrDefaultAsync(ln => ln.Id == languageAndCulture.Id);

            if (!isNew)
            {
                if (currentLanguageAndCulture == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.LanguageAndCultureNotFound));
                }


                languageAndCulture            = currentLanguageAndCulture;
                languageAndCulture.RowVersion = languageAndCultureDto.RowVersion;

                _contentManagementContext.LanguageAndCultures.Attach(languageAndCulture);
            }
            else
            {
                _contentManagementContext.LanguageAndCultures.Add(languageAndCulture);
            }

            languageAndCulture.Country       = languageAndCultureDto.Country;
            languageAndCulture.Culture       = languageAndCultureDto.Culture;
            languageAndCulture.Language      = languageAndCultureDto.Language;
            languageAndCulture.FlagId        = languageAndCultureDto.FlagId;
            languageAndCulture.IsDefaults    = languageAndCultureDto.IsDefaults;
            languageAndCulture.IsRightToLeft = languageAndCultureDto.IsRightToLeft;

            //for force update and change version for force client to get new versipn of language.js
            languageAndCulture.Version = (currentLanguageAndCulture?.Version ?? 0) + 1;

            languageAndCulture.Status = languageAndCultureDto.Status;

            if (currentLanguageAndCulture != null)
            {
                languageAndCulture.ViewRoleId   = currentLanguageAndCulture.ViewRoleId;
                languageAndCulture.ModifyRoleId = currentLanguageAndCulture.ModifyRoleId;
                languageAndCulture.AccessRoleId = currentLanguageAndCulture.AccessRoleId;
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(languageAndCulture, languageAndCultureDto);

            await _contentManagementContext.SaveChangesAsync();

            await _contentManagementContext.LanguageAndCultures.Where(lc => lc.Language == languageAndCulture.Language && lc.Id != languageAndCulture.Id)
            .UpdateAsync(t => new LanguageAndCulture()
            {
                Version = languageAndCulture.Version
            });

            string jsCode = languageAndCultureDto.JsCode;

            if (!string.IsNullOrEmpty(jsCode))
            {
                await WriteFileAsync(Config.ResourcesSourceCodePath, languageAndCulture.Language, ".js", jsCode);

                if (!publish)
                {
                    return(languageAndCulture);
                }

                await WriteFileAsync(Config.ResourcesDistPath, languageAndCulture.Language, ".js", _compressManager.CompressJavaScript(jsCode, languageAndCulture.Country));
            }
            UpdateWebConfigSetting(languageAndCulture, ActionKey.Add);



            CacheManager.Remove(CacheManager.GetBrowsersCodeInfoKey(CacheKey.BrowsersCodeInfo.ToString(),
                                                                    "~/" + languageAndCulture.Language));


            //var bundleInfo =
            //    SourceControl.BrowsersCodeInfos.FirstOrDefault(bc => bc.BundleUrl == languageAndCulture.Language);

            //if(bundleInfo != null)
            //bundleInfo.Version
            //    = Helper.UrlEncode(System.Text.Encoding.UTF8.GetString(languageAndCulture.RowVersion));

            //SourceControl.BrowsersCodeInfos.Remove(
            //    SourceControl.BrowsersCodeInfos.Find(bc => bc.BundleUrl == languageAndCulture.Language));

            return(languageAndCulture);
        }
コード例 #17
0
        protected void CheckAccess(MasterDataKeyValue code)
        {
            AuthorizeManager.SetAndCheckModifyAndAccessRole(code, null, false);

            SourceControl.CheckCodeCheckOute(code);
        }
コード例 #18
0
        private async Task <JObject> RegisterUserAsync(JObject user)
        {
            dynamic userDto  = user;
            string  userName = userDto.UserName;
            string  password = userDto.Password;

            if ((await _userManager.FindByNameAsync(userName)) != null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.DuplicateName));
            }

            var appUser = new ApplicationUser

            {
                UserName = userDto.UserName,
                //UserProfileId = 0,
                Email     = userDto.Email,
                FirstName = userDto.FirstName,
                LastName  = userDto.LastName,
                BirthDate = DateTime.UtcNow,
                Status    = userDto.Status
            };

            AuthorizeManager.SetAndCheckModifyAndAccessRole(appUser, userDto);

            IdentityResult createResult = await _userManager

                                          .CreateAsync(appUser, password);



            //Add User to the selected Groups

            if (createResult.Succeeded)
            {
                var profile = new UserProfile()
                {
                    Id           = appUser.Id,
                    AliasName    = userDto.AliasName,
                    Language     = Config.DefaultsLanguage,
                    ViewRoleId   = userDto.ViewRoleId,
                    ModifyRoleId = userDto.ModifyRoleId,
                    AccessRoleId = userDto.AccessRoleId
                };
                try
                {
                    _contentManagementContext.Users.Add(profile);
                    await _contentManagementContext.SaveChangesAsync();



                    userDto.Id = appUser.Id;
                    await UpdateUserGroups(userDto);

                    appUser = await _securityContext.Users.Include(us => us.Groups).FirstOrDefaultAsync(us => us.Id == appUser.Id);

                    if (appUser == null)
                    {
                        throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.UserNotFound));
                    }

                    return(JObject.Parse(JsonConvert.SerializeObject
                                             (new
                    {
                        appUser.Id,
                        appUser.UserName,
                        appUser.FirstName,
                        appUser.LastName,
                        appUser.Status,
                        appUser.ViewRoleId,
                        appUser.ModifyRoleId,
                        appUser.AccessRoleId,
                        UserProfileId = appUser.Id,
                        appUser.Email,
                        appUser.Groups,
                        profile.AliasName
                    }, Formatting.None,
                                             new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    })));
                }
                catch (Exception)
                {
                    try
                    {
                        await _userManager.DeleteAsync(appUser);

                        _contentManagementContext.Users.Remove(profile);
                        await _contentManagementContext.SaveChangesAsync();
                    }
                    catch (Exception)
                    {
                    }

                    throw;
                }
            }
            throw new KhodkarInvalidException(createResult.Errors.First());
        }
コード例 #19
0
        public async Task <bool> SaveFile(JObject data)
        {
            //var user = "******";
            //var version = "_asV_";
            dynamic codeDto     = data;
            int     id          = codeDto.Id;
            bool    checkIn     = codeDto.CheckIn;
            string  path        = codeDto.Path;
            string  codeContent = codeDto.Code;
            string  comment     = codeDto.Comment;

            path = path.Replace(Config.UrlDelimeter, Helper.RootUrl);
            var code = ContentManagementContext.MasterDataKeyValues.FirstOrDefault(sr => sr.Id == id);

            if (code == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.CodeNotFound));
            }

            if (code.EditMode)
            {
                SourceControl.CheckCodeCheckOute(code);
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(code, null, false);

            if (await FileSystemManager.FileExistAsync(AuthorizeManager
                                                       .AuthorizeActionOnPath(path, ActionKey.WriteToDisk)))
            {
                code.Version++;
                await ContentManagementContext.SaveChangesAsync();


                await SourceControl.AddChange(path.Remove(path.LastIndexOf("/", StringComparison.Ordinal) + 1),
                                              path.Substring(path.LastIndexOf("/", StringComparison.Ordinal) + 1),
                                              codeContent,
                                              code.Version,
                                              comment);


                //var userIndex = path.IndexOf(user, StringComparison.Ordinal);
                //var endSourceControlStringIndex = path.LastIndexOf(".", StringComparison.Ordinal);
                //if (userIndex > 0 &&
                //    path.IndexOf(version, StringComparison.Ordinal) > 0)
                //{
                //    path = path.Remove(userIndex, endSourceControlStringIndex - userIndex);


                //}
                //else
                //{
                if (checkIn)
                {
                    await FileSystemManager.WriteAsync(path, codeContent);
                }
                //}

                //return await FileSystemManager.WriteAsync(path.Insert(path.LastIndexOf(".", StringComparison.Ordinal),
                //     user+ CurrentUserManager.UserName.Replace("@", "[at]")+version+code.Version), codeContent);
                return(true);
            }

            throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.CodeNotFound));
        }
コード例 #20
0
ファイル: FileBiz.cs プロジェクト: mrgrayhat/Khodkar-Platform
        public async Task <File> Save(JObject data)
        {
            dynamic fileDto = data;

            string oldUrl = "";
            int?   fileId = fileDto.Id;
            var    file   = new File()
            {
                Id = fileId ?? 0
            };
            var currentFile = await _contentManagementContext.Files.AsNoTracking()
                              .SingleOrDefaultAsync(fl => fl.Id == file.Id);

            try
            {
                if (currentFile == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FileNotFound));
                }

                oldUrl          = currentFile.Url;
                file            = currentFile;
                file.RowVersion = fileDto.RowVersion;
                _contentManagementContext.Files.Attach(file);
            }
            catch (Exception)
            {
                _contentManagementContext.Files.Add(file);
            }

            try
            {
                file.Guid = fileDto.Guid;
            }
            catch (Exception)
            {
                file.Guid = SecureGuid.NewGuid();
            }

            string filePathUrl = fileDto.Url;

            if (filePathUrl.IndexOf(Helper.RootUrl, StringComparison.Ordinal) != 0)
            {
                filePathUrl = Helper.RootUrl + filePathUrl;
            }
            if (filePathUrl.LastIndexOf(Helper.RootUrl, StringComparison.Ordinal) == filePathUrl.Length - 1)
            {
                filePathUrl = filePathUrl.Substring(0, filePathUrl.Length - 1);
            }

            file.Name        = fileDto.Name;
            file.Description = fileDto.Description;
            file.TypeCode    = fileDto.TypeCode;


            var repeatedLink = await _contentManagementContext.FilePaths.Where(fp => fp.Url == filePathUrl).CountAsync();

            if ((repeatedLink > 0 && oldUrl == "") || (repeatedLink > 1 && oldUrl == ""))
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RepeatedValue, filePathUrl));
            }

            file.ContentType = _fileSystemManager.GetExtension(filePathUrl);
            file.Url         = filePathUrl;
            file.Size        = _fileSystemManager.GetFileSize(filePathUrl);
            file.Language    = Config.DefaultsLanguage;
            file.Content     = _fileSystemManager.FileToByte(filePathUrl);

            //if(service.IsLeaf)
            if (currentFile != null)
            {
                file.ViewRoleId   = currentFile.ViewRoleId;
                file.ModifyRoleId = currentFile.ModifyRoleId;
                file.AccessRoleId = currentFile.AccessRoleId;
            }
            AuthorizeManager.SetAndCheckModifyAndAccessRole(file, fileDto);

            file.Status = fileDto.Status;


            await _contentManagementContext.SaveChangesAsync();

            return(file);
        }
コード例 #21
0
        private async Task <JObject> UpdateUserAsync(JObject user)
        {
            dynamic userDto  = user;
            int     userId   = userDto.Id;
            string  password = userDto.Password;

            var appUser = await _userManager.FindByIdAsync(userId);

            if (appUser == null)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.UserNotFound));
            }


            var userProfile = await _contentManagementContext.Users.FirstOrDefaultAsync(up => up.Id == appUser.Id);

            if (userProfile == null)
            {
                userProfile = new UserProfile()
                {
                    Id = appUser.Id
                };

                _contentManagementContext.Users.Add(userProfile);
            }
            // throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.UserProfileNotFound));



            userProfile.AliasName = userDto.AliasName;


            AuthorizeManager.SetAndCheckModifyAndAccessRole(appUser, userDto);


            await _contentManagementContext.SaveChangesAsync();



            appUser.Email     = userDto.Email;
            appUser.FirstName = userDto.FirstName;
            appUser.LastName  = userDto.LastName;
            appUser.Status    = userDto.Status;



            IdentityResult updateResult = await _userManager

                                          .UpdateAsync(appUser);



            //Add User to the selected Groups

            if (updateResult.Succeeded)
            {
                //todo:check Authorize
                await UpdateUserGroups(user);

                bool isChangePass = userDto.IsChangePass;
                if (isChangePass)
                {
                    var token = await _userManager.GeneratePasswordResetTokenAsync(userId);

                    var changePassResult = await _userManager.ResetPasswordAsync(userId, token, password);

                    if (!changePassResult.Succeeded)
                    {
                        throw new KhodkarInvalidException(changePassResult.Errors.First());
                    }
                }

                appUser = await _securityContext.Users.Include(us => us.Groups).FirstOrDefaultAsync(us => us.Id == userId);

                if (appUser == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.UserNotFound));
                }
                return(JObject.Parse(JsonConvert.SerializeObject
                                         (new
                {
                    appUser.Id,
                    appUser.UserName,
                    appUser.FirstName,
                    appUser.LastName,
                    appUser.Status,
                    appUser.ViewRoleId,
                    appUser.ModifyRoleId,
                    appUser.AccessRoleId,
                    UserProfileId = appUser.Id,
                    appUser.Email,
                    appUser.Groups,
                    userProfile.AliasName
                }, Formatting.None,
                                         new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                })));
            }
            throw new KhodkarInvalidException(updateResult.Errors.First());
        }
コード例 #22
0
        //public async Task<IList<LinkObjective>> GetAllLinkAsync(IEnumerable<string> accessRoles = null, IEnumerable<string> denyRoles = null)
        //{
        //    //var ts = _securityContext.ApplicationTrees
        //    // .Include(x => x.Offspring.Select(y => y.Offspring))
        //    // .SingleOrDefault(x => x.Id == 72);
        //    //ts = ts;
        //    var lang = Setting.Language;
        //    var baseTree = await _contentManagementContext.Links.Where(ln => ln.Language == lang).AsNoTracking().ToListAsync();
        //    var newTree = new List<LinkObjective>();
        //    foreach (var node in baseTree)
        //    {
        //        if (node.IsLeaf)
        //        {
        //            if (accessRoles == null && denyRoles == null)
        //                BuildTree<LinkObjective, LinkObjective>(node, newTree, baseTree);
        //            else if (accessRoles != null && denyRoles != null)
        //            {
        //                if (accessRoles.Any(r => r == node.ViewRoleId.ToString()) && !denyRoles.Any(r => r == node.ViewRoleId.ToString()))
        //                {
        //                    BuildTree<LinkObjective, LinkObjective>(node, newTree, baseTree);
        //                }
        //            }
        //            else if (denyRoles == null)
        //            {
        //                if (accessRoles.Any(r => r == node.ViewRoleId.ToString()))
        //                {
        //                    BuildTree<LinkObjective, LinkObjective>(node, newTree, baseTree);
        //                }
        //            }
        //            else if (accessRoles == null)
        //            {
        //                if (!denyRoles.Any(r => r == node.ViewRoleId.ToString()))
        //                {
        //                    BuildTree<LinkObjective, LinkObjective>(node, newTree, baseTree);
        //                }
        //            }

        //        }


        //        if (node.ParentId == null)
        //        {
        //            if (node.IsLeaf)
        //            {

        //                if (accessRoles == null && denyRoles == null)
        //                {
        //                    if (!newTree.Exists(t => t.Id == node.Id))
        //                        newTree.Add(node);
        //                }
        //                else if (accessRoles != null && denyRoles != null)
        //                {
        //                    if (accessRoles.Any(r => r == node.ViewRoleId.ToString()) && !denyRoles.Any(r => r == node.ViewRoleId.ToString()))
        //                    {
        //                        if (!newTree.Exists(t => t.Id == node.Id))
        //                            newTree.Add(node);
        //                    }
        //                }
        //                else if (denyRoles == null)
        //                {
        //                    if (accessRoles.Any(r => r == node.ViewRoleId.ToString()))
        //                    {
        //                        if (!newTree.Exists(t => t.Id == node.Id))
        //                            newTree.Add(node);
        //                    }
        //                }
        //                else if (accessRoles == null)
        //                {
        //                    if (!denyRoles.Any(r => r == node.ViewRoleId.ToString()))
        //                    {
        //                        if (!newTree.Exists(t => t.Id == node.Id))
        //                            newTree.Add(node);
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                if (!newTree.Exists(t => t.Id == node.Id))
        //                    newTree.Add(node);
        //            }
        //        }
        //    }
        //    return RemoveEmptyParentNode<LinkObjective, LinkObjective>(newTree);
        //}

        #region [SaveLink..]
        public async Task <Link> Save(JObject data)
        {
            dynamic linkDto = data;

            string oldUrl = "";

            int?linkId = linkDto.Id;


            var link = new Link()
            {
                Id = linkId == null ? 0 : linkDto.Id
            };
            var currentLink = await _contentManagementContext.Links.AsNoTracking().SingleOrDefaultAsync(ln => ln.Id == link.Id);

            try
            {
                if (currentLink == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.LinkNotFound));
                }
                oldUrl          = currentLink.Url;
                link            = currentLink;
                link.RowVersion = linkDto.RowVersion;
                _contentManagementContext.Links.Attach(link);
            }
            catch (Exception)
            {
                link = new Link();
                _contentManagementContext.Links.Add(link);
            }


            string linkUrl = linkDto.Url;

            if (linkUrl.IndexOf(Helper.RootUrl, StringComparison.Ordinal) != 0)
            {
                linkUrl = Helper.RootUrl + linkUrl;
            }
            if (linkUrl.LastIndexOf(Helper.RootUrl, StringComparison.Ordinal) == linkUrl.Length - 1)
            {
                linkUrl = linkUrl.Substring(0, linkUrl.Length - 1);
            }
            try
            {
                int parentId = linkDto.ParentId;
                if (currentLink?.ParentId != parentId)
                {
                    var parentCode = await _contentManagementContext.Links.SingleOrDefaultAsync(md => md.Id == parentId);

                    if (parentCode == null)
                    {
                        throw new KhodkarInvalidException(
                                  LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                    }
                    AuthorizeManager.CheckParentNodeModifyAccessForAddingChildNode(parentCode, parentCode.Id);
                }
                link.ParentId = parentId;
            }
            catch (KhodkarInvalidException)
            {
                throw;
            }
            catch (Exception)
            {
                link.ParentId = null;
            }
            link.Text               = linkDto.Text;
            link.TransactionCode    = linkDto.TransactionCode;
            link.Html               = linkDto.Html;
            link.Action             = linkDto.Action;
            link.Url                = linkUrl;
            link.ShowToSearchEngine = linkDto.ShowToSearchEngine;

            var repeatedLink = await _contentManagementContext.Links.Where(sr => sr.Url == link.Url).CountAsync();

            if ((repeatedLink > 0 && oldUrl == "") || (repeatedLink > 1 && oldUrl == ""))
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RepeatedValue, link.Url));
            }


            try
            {
                link.Order = linkDto.Order;
            }
            catch (Exception)
            {
                link.Order = 1;
            }
            link.IsLeaf   = linkDto.IsLeaf;
            link.Language = linkDto.Language;

            //if(service.IsLeaf)

            if (currentLink != null)
            {
                link.ViewRoleId   = currentLink.ViewRoleId;
                link.ModifyRoleId = currentLink.ModifyRoleId;
                link.AccessRoleId = currentLink.AccessRoleId;
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(link, linkDto);

            link.Status   = linkDto.Status;
            link.IsMobile = linkDto.IsMobile;
            link.TypeId   = linkDto.TypeId;

            await _contentManagementContext.SaveChangesAsync();

            if (oldUrl != "")
            {
                _contentManagementContext.WebPages.Where(wp => wp.Url == oldUrl).Update(wp => new WebPage()
                {
                    Url = linkUrl
                });
            }
            return(link);
        }
コード例 #23
0
        public async Task <ApplicationGroup> SaveGroup(JObject group)
        {
            dynamic          groupDto = group;
            ApplicationGroup applicationGroup;
            bool             isNew             = groupDto.IsNew;
            JArray           sremovedListArray = groupDto.RemovedList;
            var    removedList    = sremovedListArray.ToObject <List <int> >();
            JArray addedListArray = groupDto.AddedList;
            var    addedList      = addedListArray.ToObject <List <int> >();

            if (!isNew)
            {
                applicationGroup = new ApplicationGroup()
                {
                    Id = groupDto.Id
                };
                applicationGroup = await _securityContext.Groups.FindAsync(applicationGroup.Id);

                if (applicationGroup == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.GroupNotFound));
                }
            }
            else
            {
                applicationGroup = new ApplicationGroup();
                _securityContext.Groups.Add(applicationGroup);
            }



            applicationGroup.Name        = groupDto.Name;
            applicationGroup.IsLeaf      = groupDto.IsLeaf;
            applicationGroup.Description = groupDto.Description;
            try
            {
                applicationGroup.Order = groupDto.Order;
            }
            catch (Exception)
            {
                applicationGroup.Order = 0;
            }

            applicationGroup.Status = groupDto.Status;

            try
            {
                int parentId = groupDto.ParentId;
                if (applicationGroup.ParentId != parentId)
                {
                    var parentCode = await _securityContext.Groups.FindAsync(parentId);

                    if (parentCode == null)
                    {
                        throw new KhodkarInvalidException(
                                  LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                    }
                    AuthorizeManager.CheckParentNodeModifyAccessForAddingChildNode(parentCode, parentCode.Id);
                }
                applicationGroup.ParentId = parentId;
            }
            catch (KhodkarInvalidException)
            {
                throw;
            }
            catch (Exception)
            {
                applicationGroup.ParentId = null;
            }

            AuthorizeManager.SetAndCheckModifyAndAccessRole(applicationGroup, groupDto);

            foreach (var item in addedList)
            {
                var role = new ApplicationGroupRole()
                {
                    GroupId = applicationGroup.Id,
                    RoleId  = item
                };
                _securityContext.ApplicationGroupRoles.Add(role);
            }

            if (removedList.Count > 0)
            {
                _securityContext.ApplicationGroupRoles.Where(
                    eg => removedList.Contains(eg.RoleId) && eg.GroupId == applicationGroup.Id).Delete();
            }

            await _securityContext.SaveChangesAsync();


            CacheManager.Remove(CacheManager.GetGroupKey(CacheKey.Aspect.ToString(), applicationGroup.Id));

            return(applicationGroup);
        }