public AbstractCriterion GetPermissionsCriteria(ICorePrincipal user, int operationCode, Type permissibleObjectType, String permissibleIdPropertyName, String permissibleOwnerPropertyName) { if (user != null) { if (user.IsInRole(SystemRole.Administrator.ToString())) { return(null); } var rolesSubQuery = DetachedCriteria.For <Role>() .CreateAlias("Users", "user") .Add(Restrictions.Eq("user.id", user.PrincipalId)) .SetProjection(Projections.Id()); var userUserGroupsSubQuery = DetachedCriteria.For <UserGroup>() .CreateAlias("Users", "userGroupUser", JoinType.LeftOuterJoin) .Add(Restrictions.Eq("userGroupUser.id", user.PrincipalId)) .SetProjection(Projections.Id()); var userGroupsRolesSubQuery = DetachedCriteria.For <Role>() .CreateAlias("UserGroups", "userGroup", JoinType.LeftOuterJoin) .Add(Subqueries.PropertyIn("userGroup.id", userUserGroupsSubQuery)) .SetProjection(Projections.Id()); var permissionsSubQuery = DetachedCriteria.For <Permission>() .Add(Restrictions.EqProperty("EntityId", permissibleIdPropertyName)).CreateAlias("EntityType", "et").Add(Restrictions.Eq("et.Name", PermissionsHelper.GetEntityType(permissibleObjectType))). Add(Restrictions.Or(Restrictions.Or( Restrictions.Or(Subqueries.PropertyIn("Role.Id", rolesSubQuery), Subqueries.PropertyIn("Role.Id", userGroupsRolesSubQuery)), Restrictions.Eq("Role.Id", (Int64)SystemRole.User)), !String.IsNullOrEmpty(permissibleOwnerPropertyName) ? Restrictions.And(Restrictions.IsNotNull(permissibleOwnerPropertyName), Restrictions.And(Restrictions.Eq(permissibleOwnerPropertyName, user.PrincipalId), Restrictions.Eq("Role.Id", (Int64)SystemRole.Owner))) : null )).Add( Restrictions.Eq(Projections.SqlProjection(String.Format("Permissions & {0} as result", operationCode), new[] { "result" }, new IType[] { NHibernateUtil.Int32 }), operationCode)) .SetProjection(Projections.Id()); return(Subqueries.Exists(permissionsSubQuery)); } else { var permissionsSubQuery = DetachedCriteria.For <Permission>() .Add(Restrictions.EqProperty("EntityId", permissibleIdPropertyName)).CreateAlias("EntityType", "et").Add(Restrictions.Eq("et.Name", PermissionsHelper.GetEntityType(permissibleObjectType))). Add(Restrictions.Eq("Role.Id", (Int64)SystemRole.Guest)).Add( Restrictions.Eq(Projections.SqlProjection(String.Format("Permissions & {0} as result", operationCode), new[] { "result" }, new IType[] { NHibernateUtil.Int32 }), operationCode)) .SetProjection(Projections.Id()); return(Subqueries.Exists(permissionsSubQuery)); } }
private static bool ProcessSettings(WebsiteImportTypeEnum importType, WebsiteExport websiteExport, Website existingWebsite, Website newWebsite, IDomainSessionFactoryProvider provider, ILogWriter logger) { try { var config = ServiceLocator.Current.GetInstance <IConfigurationService>(); var availableWebsiteThemes = config.MonahrqSettings.Themes.Cast <MonahrqThemeElement>(); var defaultTheme = availableWebsiteThemes.FirstOrDefault(x => x.Name.Contains("Default")); if (importType == WebsiteImportTypeEnum.File && websiteExport != null) { newWebsite.OutPutDirectory = websiteExport.OutPutDirectory; newWebsite.SelectedZipCodeRadii = websiteExport.SelectedZipCodeRadii.ToList(); newWebsite.GeographicDescription = websiteExport.GeographicDescription; newWebsite.AboutUsSectionSummary = websiteExport.AboutUsSectionSummary; newWebsite.AboutUsSectionText = websiteExport.AboutUsSectionText; newWebsite.CustomFeedbackFormUrl = websiteExport.CustomFeedbackFormUrl; newWebsite.FeedBackEmail = websiteExport.FeedBackEmail; newWebsite.FeedbackTopics = websiteExport.FeedbackTopics.ToList(); newWebsite.IncludeFeedbackFormInYourWebsite = websiteExport.IncludeFeedbackFormInYourWebsite; newWebsite.IncludeGuideToolInYourWebsite = websiteExport.IncludeGuideToolInYourWebsite; newWebsite.GoogleAnalyticsKey = websiteExport.GoogleAnalyticsKey; newWebsite.GoogleMapsApiKey = websiteExport.GoogleMapsApiKey; newWebsite.BrowserTitle = websiteExport.BrowserTitle; newWebsite.HeaderTitle = websiteExport.HeaderTitle; newWebsite.Keywords = websiteExport.Keywords; var theme = availableWebsiteThemes.FirstOrDefault(x => x.Name.ContainsCaseInsensitive(websiteExport.SelectedTheme)); var professionalWebsiteTheme = GetWebsiteTheme(Audience.Professionals, websiteExport.SelectedTheme, websiteExport.AccentColor, websiteExport.SelectedFont, websiteExport.BrandColor, theme); if (!string.IsNullOrEmpty(websiteExport.ConsumerBrandColor)) { var consumerWebsiteTheme = GetWebsiteTheme(Audience.Consumers, websiteExport.ConsumerSelectedTheme, websiteExport.AccentColor, websiteExport.ConsumerSelectedFont, websiteExport.ConsumerBrandColor, theme); newWebsite.Themes.Add(consumerWebsiteTheme); } newWebsite.Themes.Add(professionalWebsiteTheme); newWebsite.Menus = !string.IsNullOrEmpty(websiteExport.Menus.Value) ? JsonHelper.Deserialize <List <Menu> >(websiteExport.Menus.Value).Select(x => new WebsiteMenu { Menu = x }).ToList() : new List <WebsiteMenu>();; if (websiteExport.BannerImage != null) { // Encoding.UTF8.GetBytes(websiteExport.BannerImage.Image), newWebsite.BannerImage = new WebsiteImage { Image = websiteExport.BannerImage.Image, MemeType = websiteExport.BannerImage.MemeType, ImagePath = websiteExport.BannerImage.Path }; } if (websiteExport.LogoImage != null) { //Encoding.UTF8.GetBytes(websiteExport.LogoImage.Image), newWebsite.LogoImage = new WebsiteImage { Image = websiteExport.LogoImage.Image, MemeType = websiteExport.LogoImage.MemeType, ImagePath = websiteExport.LogoImage.Path }; } if (websiteExport.Hospitals != null && websiteExport.Hospitals.Any()) { var hospitals = new List <Hospital>(); var hositalIdList = websiteExport.Hospitals.Select(ds => ds.Id).ToList(); var hospitExportList = websiteExport.Hospitals .ToDictionary(wh => wh.ProviderId, wh => new Holder { Hospital = null, ProviderId = wh.ProviderId, Ccr = wh.Ccr }); using (var session = provider.SessionFactory.OpenSession()) { hospitals = session.CreateCriteria <Hospital>() .Add(Restrictions.In("State", newWebsite.StateContext.Cast <object>().ToArray())) .Add(Restrictions.And(Restrictions.Eq("IsArchived", false), Restrictions.Eq("IsDeleted", false))) .Future <Hospital>() .ToList(); } if (hospitals.Any()) { if (newWebsite.Hospitals == null) { newWebsite.Hospitals = new List <WebsiteHospital>(); } foreach (var hospital in hospitals) { if (hospitExportList.Values.All(x => x.ProviderId.ToUpper() != hospital.CmsProviderID.ToUpper())) { continue; } hospitExportList[hospital.CmsProviderID].Hospital = hospital; } foreach (var hospitalHolder in hospitExportList.Where(x => x.Value.Hospital != null).ToList()) { newWebsite.Hospitals.Add(new WebsiteHospital { Hospital = hospitalHolder.Value.Hospital, CCR = hospitalHolder.Value.Ccr }); } } else { newWebsite.Hospitals = new List <WebsiteHospital>(); } } if (websiteExport.NursingHomes != null && websiteExport.NursingHomes.Any()) { var nursingHomes = new List <NursingHome>(); // var nursingHomeList = websiteExport.NursingHomes.Select(ds => ds.Id).ToList(); var nursingHomeExportList = websiteExport.NursingHomes.ToDictionary(h => h.ProviderId, h => new Holder { NursingHome = null }); using (var session = provider.SessionFactory.OpenSession()) { nursingHomes = session.CreateCriteria <NursingHome>() .Add(Restrictions.In("State", newWebsite.StateContext.Cast <object>().ToArray())) //.Add(Restrictions.Eq("IsDeleted",false)) .Future <NursingHome>() .ToList(); } if (nursingHomes.Any()) { if (newWebsite.NursingHomes == null) { newWebsite.NursingHomes = new List <WebsiteNursingHome>(); } foreach (var nursingHome in nursingHomes) { if (!nursingHomeExportList.ContainsKey(nursingHome.ProviderId)) { continue; } nursingHomeExportList[nursingHome.ProviderId].NursingHome = nursingHome; } foreach (var hospitalHolder in nursingHomeExportList.Where(x => x.Value != null && x.Value.NursingHome != null).ToList()) { newWebsite.NursingHomes.Add(new WebsiteNursingHome { NursingHome = hospitalHolder.Value.NursingHome }); } } else { newWebsite.NursingHomes = new List <WebsiteNursingHome>(); } } } else if (importType == WebsiteImportTypeEnum.Existing && existingWebsite != null) { newWebsite.OutPutDirectory = existingWebsite.OutPutDirectory; newWebsite.SelectedZipCodeRadii = existingWebsite.SelectedZipCodeRadii.ToList(); newWebsite.GeographicDescription = existingWebsite.GeographicDescription; newWebsite.AboutUsSectionSummary = existingWebsite.AboutUsSectionSummary; newWebsite.AboutUsSectionText = existingWebsite.AboutUsSectionText; newWebsite.CustomFeedbackFormUrl = existingWebsite.CustomFeedbackFormUrl; newWebsite.FeedBackEmail = existingWebsite.FeedBackEmail; newWebsite.FeedbackTopics = existingWebsite.FeedbackTopics.ToList(); newWebsite.IncludeFeedbackFormInYourWebsite = existingWebsite.IncludeFeedbackFormInYourWebsite; newWebsite.IncludeGuideToolInYourWebsite = existingWebsite.IncludeGuideToolInYourWebsite; newWebsite.GoogleAnalyticsKey = existingWebsite.GoogleAnalyticsKey; newWebsite.GoogleMapsApiKey = existingWebsite.GoogleMapsApiKey; newWebsite.BrowserTitle = existingWebsite.BrowserTitle; newWebsite.HeaderTitle = existingWebsite.HeaderTitle; newWebsite.Keywords = existingWebsite.Keywords; if (existingWebsite.Themes != null && existingWebsite.Themes.Any()) { newWebsite.Themes = existingWebsite.Themes.Select(t => new WebsiteTheme { AudienceType = t.AudienceType, SelectedTheme = t.SelectedTheme ?? defaultTheme.Name, AccentColor = t.AccentColor ?? defaultTheme.AccentColor, BrandColor = t.BrandColor ?? defaultTheme.BrandColor, SelectedFont = t.SelectedFont ?? "'Droid Sans', Arial, sans-serif;", BackgroundColor = t.BackgroundColor ?? defaultTheme.BackgroundColor, BodyTextColor = t.BodyTextColor ?? defaultTheme.BodyTextColor, LinkTextColor = t.LinkTextColor ?? defaultTheme.LinkTextColor }).ToList(); } if (existingWebsite.Hospitals != null && existingWebsite.Hospitals.Any()) { newWebsite.Hospitals = existingWebsite.Hospitals.Select(wh => new WebsiteHospital { Hospital = wh.Hospital, CCR = wh.CCR, Index = wh.Index }) .ToList(); } if (existingWebsite.NursingHomes != null && existingWebsite.NursingHomes.Any()) { newWebsite.NursingHomes = existingWebsite.NursingHomes.Select(nh => new WebsiteNursingHome { NursingHome = nh.NursingHome, Index = nh.Index }) .ToList(); } if (existingWebsite.BannerImage != null) { newWebsite.BannerImage = existingWebsite.BannerImage; } if (existingWebsite.LogoImage != null) { newWebsite.LogoImage = existingWebsite.LogoImage; } } newWebsite.ActivityLog.Add(new ActivityLogEntry("Settings have be saved and/our updated.", DateTime.Now)); return(true); } catch (Exception exc) { logger.Write(exc); return(false); } }
public override void CreateFilter() { var filterParams = FilterParams as StockUnitFilterParams; if (filterParams == null) { return; } Criteria = DetachedCriteria.For <StockUnit>(); Criteria.CreateAlias("Owner", "owner") .CreateAlias("Card", "card") .CreateAlias("Status", "status"); var owners = filterParams.Owner.Cast <EntityBase>().ToList(); var statuses = filterParams.Status.Cast <EntityBase>().ToList(); var cards = filterParams.Card.Cast <EntityBase>().ToList(); var ownerCriterion = CreateCriterion(owners, "owner"); var statusesCriterion = CreateCriterion(statuses, "status"); var cardCriterion = CreateCriterion(cards, "card"); if (!string.IsNullOrEmpty(SearchString)) { SetSearchString(SearchString); } ICriterion result = ownerCriterion; if (result == null && statusesCriterion != null) { result = statusesCriterion; } if (result != null && statusesCriterion != null) { result = Restrictions.And(statusesCriterion, result); } if (result == null && cardCriterion != null) { result = cardCriterion; } if (result != null && cardCriterion != null) { result = Restrictions.And(cardCriterion, result); } if (result == null && SearchStringCriterion != null) { result = SearchStringCriterion; } if (result != null && SearchStringCriterion != null) { result = Restrictions.And(SearchStringCriterion, result); } if (result != null) { Criteria.Add(result); } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns>A <see cref="Agatha.Common.Response"/></returns> public override Response Handle(PatientListSearchRequest request) { var criteria = DetachedCriteria.For <Patient> () .SetFetchMode("PatientGender", FetchMode.Eager); SetRestrictions(criteria, request); var problemCriteria = DetachedCriteria.For <Problem> () .CreateAlias("ClinicalCase", "cc") .CreateAlias("cc.Patient", "p") .SetFetchMode("ProblemCodeCodedConcept", FetchMode.Join) .CreateAlias("ProblemStatus", "ps") .Add( Restrictions.And( Restrictions.Eq("ps.WellKnownName", ProblemStatus.Active), Subqueries.PropertyIn( "p.Key", SetRestrictions( DetachedCriteria.For <Patient> ().SetProjection(Projections.Property <Patient> (p => p.Key)), request)))); var medicationCriteria = DetachedCriteria.For <Medication> () .SetFetchMode("MedicationCodeCodedConcept", FetchMode.Join) .CreateAlias("MedicationStatus", "ms") .CreateAlias("Patient", "p") .Add( Restrictions.And( Restrictions.Eq("ms.WellKnownName", MedicationStatus.Active), Subqueries.PropertyIn( "p.Key", SetRestrictions( DetachedCriteria.For <Patient> ().SetProjection(Projections.Property <Patient> (p => p.Key)), request)))); var labCriteria = DetachedCriteria.For <LabResult> () .SetFetchMode("LabTestResultNameCodedConcept", FetchMode.Join) .CreateAlias("LabTest", "lt") .CreateAlias("lt.LabSpecimen", "ls") .CreateAlias("ls.Visit", "v") .CreateAlias("v.ClinicalCase", "cc") .CreateAlias("cc.Patient", "p") .Add( Subqueries.PropertyIn( "p.Key", SetRestrictions(DetachedCriteria.For <Patient> ().SetProjection(Projections.Property <Patient> (p => p.Key)), request))); var multiCriteria = Session.CreateMultiCriteria().Add(criteria) .Add(problemCriteria) .Add(medicationCriteria) .Add(labCriteria); multiCriteria.SetResultTransformer(new DistinctRootEntityResultTransformer()); var multiCriteriaList = multiCriteria.List(); var patients = ( IList )(multiCriteriaList)[0]; var problems = (( IList )(multiCriteriaList)[1]).OfType <Problem> (); var meds = (( IList )(multiCriteriaList)[2]).OfType <Medication> (); var labs = (( IList )(multiCriteriaList)[3]).OfType <LabResult> (); var results = new List <PatientListResultDto> (); foreach (Patient patient in patients) { results.Add( new PatientListResultDto { Key = patient.Key, PatientIdentifier = patient.UniqueIdentifier, PatientName = string.Format("{0}, {1}", patient.Name.Last, patient.Name.First), PatientAge = PatientListHelper.GetAge(patient.Profile.BirthDate), PatientGender = patient.Profile.PatientGender == null ? "-" : patient.Profile.PatientGender.Name, PatientActiveMedications = meds.Where(m => m.Patient.Key == patient.Key).Select(m => m.MedicationCodeCodedConcept.DisplayName).OrderBy( n => n).ToList(), PatientActiveProblems = problems.Where(p => p.ClinicalCase.Patient.Key == patient.Key).Select( p => p.ProblemCodeCodedConcept.DisplayName).OrderBy(n => n).ToList(), PatientLabTests = labs.Where( l => patient.Key == l.LabTest.LabSpecimen.ClinicalCase.Patient.Key) .Select( lr => new PatientLabTestSummaryDto { Key = lr.Key, LabTest = lr.LabTestResultNameCodedConcept.DisplayName, Results = new List <string> { string.Format( "{0} {1}", lr.Value, lr.UnitOfMeasureCode) } }).ToList() }); } if (results.Count > 0 && !string.IsNullOrEmpty(request.PatientListCriteriaDto.SortBy)) { if (request.PatientListCriteriaDto.SortBy == PropertyUtil.ExtractPropertyName(() => results[0].PatientActiveMedications) + "String" || request.PatientListCriteriaDto.SortBy == PropertyUtil.ExtractPropertyName(() => results[0].PatientActiveProblems) + "String" || request.PatientListCriteriaDto.SortBy == PropertyUtil.ExtractPropertyName(() => results[0].PatientLabTests) + "String") { results = results.OrderBy( request.PatientListCriteriaDto.SortBy.Replace("String", string.Empty), request.PatientListCriteriaDto.SortDirection == ListSortDirection.Ascending, new EnumerableToStringComparer()).ToList(); } else { results = results.OrderBy( request.PatientListCriteriaDto.SortBy, request.PatientListCriteriaDto.SortDirection == ListSortDirection.Ascending).ToList(); } } var response = CreateTypedResponse(); response.PatientList = new PatientListResultsDto(); if (request.PatientListCriteriaDto.PageSize > 0) { var pageIndex = request.PatientListCriteriaDto.PageIndex == 0 ? 1 : request.PatientListCriteriaDto.PageIndex; var pageSize = request.PatientListCriteriaDto.PageSize; response.PatientList.Results = results.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } else { response.PatientList.Results = results; } response.PatientList.PageIndex = request.PatientListCriteriaDto.PageIndex; response.PatientList.PageSize = Math.Max(request.PatientListCriteriaDto.PageSize, results.Count); response.PatientList.TotalCount = patients.Count; return(response); }
public static Bot FindBy(string login, string password) { //登录名不区分大小写 return(FindOne(Restrictions.And(Restrictions.Eq("Login", login.ToLowerInvariant()), Restrictions.Eq("Password", password)))); }
public static object ObterRelatorioAcessos(bool inAnonimos, int[] navegadores, string[] usuariosId, string dataInicial, string dataFinal, ModeloDeCorteEnum corte, int TopItens = 5) { DTOGrafico dtoGrafico = new DTOGrafico(); try { Acesso AcessoAlias = null; var query = Session.Current.QueryOver <Acesso>(() => AcessoAlias); if (!inAnonimos) { query.Where(Restrictions.IsNotNull(Projections.Property(() => AcessoAlias.Usuario))); } if (navegadores != null && navegadores.Count() > 0) { IList <string> NavegadoresList = new List <string>(); for (int i = 0; i < navegadores.Count(); i++) { NavegadoresList.Add(((NavegadorEnum)navegadores[i]).GetDescription()); } query = query.Where(Restrictions.On(() => AcessoAlias.Navegador).IsIn(NavegadoresList.ToArray())); } if (dataInicial != null && dataFinal != null) { DateTime DataInicial = DateTime.Parse(dataInicial).Date; DateTime DataFinal = DateTime.Parse(dataFinal).Date.AddHours(23).AddMinutes(59).AddSeconds(59); query.Where(Restrictions.And(Restrictions.Ge(Projections.Property(() => AcessoAlias.Data), DataInicial), Restrictions.Le(Projections.Property(() => AcessoAlias.Data), DataFinal))); } DTODado dto = new DTODado(); var PaginaGroup = Projections.GroupProperty(Projections.Property(() => AcessoAlias.Pagina)); var nomeAlias = PaginaGroup.WithAlias(() => dto.Label); var quantAlias = Projections.RowCount().WithAlias(() => dto.Quantidade); var corteAlias = new SQLCorteService().Executar(corte).WithAlias(() => dto.Corte); var projections = Projections.ProjectionList() .Add(nomeAlias) .Add(quantAlias) .Add(corteAlias) .Add(PaginaGroup) ; var Dados = query.OrderBy(() => AcessoAlias.Data).Asc() .ThenBy(() => AcessoAlias.Navegador).Asc() .Select(projections) .TransformUsing(Transformers.AliasToBean <DTODado>()) .List <DTODado>(); ObterGrafico(dtoGrafico, Dados, TopItens); } catch (Exception) { throw; } return(dtoGrafico); }
public static ICriteria And(this ICriteria criteria, ICriterion cri1, ICriterion cri2) { return(criteria.Add(Restrictions.And(cri1, cri2))); }
public virtual ContentItem Get(int id, VersionOptions options, QueryHints hints) { var session = _contentManagerSession(); ContentItem contentItem; ContentItemVersionRecord versionRecord = null; // obtain the root records based on version options if (options.VersionRecordId != 0) { // short-circuit if item held in session if (session.RecallVersionRecordId(options.VersionRecordId, out contentItem)) { return(contentItem); } versionRecord = _contentItemVersionRepository.Get(options.VersionRecordId); } else if (options.VersionNumber != 0) { // short-circuit if item held in session if (session.RecallVersionNumber(id, options.VersionNumber, out contentItem)) { return(contentItem); } versionRecord = _contentItemVersionRepository.Get(x => x.ContentItemRecord.Id == id && x.Number == options.VersionNumber); } else if (session.RecallContentRecordId(id, out contentItem)) { // try to reload a previously loaded published content item if (options.IsPublished) { return(contentItem); } versionRecord = contentItem.VersionRecord; } else { // do a query to load the records in case Get is called directly var contentItemVersionRecords = GetManyImplementation(hints, (contentItemCriteria, contentItemVersionCriteria) => { contentItemCriteria.Add(Restrictions.Eq("Id", id)); if (options.IsPublished) { contentItemVersionCriteria.Add(Restrictions.Eq("Published", true)); } else if (options.IsLatest) { contentItemVersionCriteria.Add(Restrictions.Eq("Latest", true)); } else if (options.IsDraft && !options.IsDraftRequired) { contentItemVersionCriteria.Add( Restrictions.And(Restrictions.Eq("Published", false), Restrictions.Eq("Latest", true))); } else if (options.IsDraft || options.IsDraftRequired) { contentItemVersionCriteria.Add(Restrictions.Eq("Latest", true)); } contentItemVersionCriteria.SetFetchMode("ContentItemRecord", FetchMode.Eager); contentItemVersionCriteria.SetFetchMode("ContentItemRecord.ContentType", FetchMode.Eager); //contentItemVersionCriteria.SetMaxResults(1); }); if (options.VersionNumber != 0) { versionRecord = contentItemVersionRecords.FirstOrDefault( x => x.Number == options.VersionNumber) ?? _contentItemVersionRepository.Get( x => x.ContentItemRecord.Id == id && x.Number == options.VersionNumber); } else { versionRecord = contentItemVersionRecords.LastOrDefault(); } } // no record means content item is not in db if (versionRecord == null) { // check in memory var record = _contentItemRepository.Get(id); if (record == null) { return(null); } versionRecord = GetVersionRecord(options, record); if (versionRecord == null) { return(null); } } // return item if obtained earlier in session if (session.RecallVersionRecordId(versionRecord.Id, out contentItem)) { if (options.IsDraftRequired && versionRecord.Published) { return(BuildNewVersion(contentItem)); } return(contentItem); } // allocate instance and set record property contentItem = New(versionRecord.ContentItemRecord.ContentType.Name); contentItem.VersionRecord = versionRecord; // store in session prior to loading to avoid some problems with simple circular dependencies session.Store(contentItem); // create a context with a new instance to load var context = new LoadContentContext(contentItem); // invoke handlers to acquire state, or at least establish lazy loading callbacks Handlers.Invoke(handler => handler.Loading(context), Logger); Handlers.Invoke(handler => handler.Loaded(context), Logger); // when draft is required and latest is published a new version is appended if (options.IsDraftRequired && versionRecord.Published) { contentItem = BuildNewVersion(context.ContentItem); } return(contentItem); }
public override ICriterion VisitFieldPredicate(FieldPredicateExpression node) { var fieldName = node.SelectorExpression.FieldName; var valueKey = node.SelectorExpression.ValueKey; var fieldValue = node.ValueExpression.Value; var fieldValueType = fieldValue != null?fieldValue.GetType() : typeof(string); switch (fieldName.ToLowerInvariant()) { case "id": Guid idValue = GetIdValue(node); switch (node.ValueExpression.ClauseType) { case ValuePredicateType.Equal: _discoveredRequiredNodeIds.Add(idValue); return(Restrictions.Eq(Projections.Property(() => version.Node.Id), idValue)); case ValuePredicateType.NotEqual: _negatingNodeIdsExist = true; return(!Restrictions.Eq(Projections.Property(() => version.Node.Id), idValue)); default: throw new InvalidOperationException( "Cannot query an item by id by any other operator than == or !="); } case "system-internal-selected-template": //TODO Pending property editors getting involved in query modification prior to being passed to hive provider, //manually check for queries against a template here if (valueKey == "TemplateId" && fieldValue != null) { var tryParseResult = HiveId.TryParse(fieldValue.ToString()); if (!tryParseResult.Success || tryParseResult.Result.ProviderGroupRoot == null || tryParseResult.Result.ProviderId == null || (tryParseResult.Result.ProviderGroupRoot.AbsoluteUri != "storage://" && tryParseResult.Result.ProviderId != "templates")) { var normalisedFieldValue = "/" + fieldValue.ToString().TrimStart("/").TrimEnd(".") + "."; // Need to convert the value into the serialized form that a HiveId would use var newValue = new HiveId("storage", "templates", new HiveIdValue(normalisedFieldValue)).ToString(HiveIdFormatStyle.UriSafe); fieldValue = newValue; } else { fieldValue = tryParseResult.Result.ToString(HiveIdFormatStyle.UriSafe); } } break; } // First look up the types of the main field AttributeDefinition defAlias = null; AttributeType typeAlias = null; var attributeType = _activeSession.NhSession.QueryOver <AttributeDefinition>(() => defAlias) .JoinAlias(() => defAlias.AttributeType, () => typeAlias) .Where(() => defAlias.Alias == fieldName) .Select(x => typeAlias.PersistenceTypeProvider) .List <string>(); foreach (var type in attributeType) { var typeName = type; if (_typesAlreadyEstablished.Contains(typeName)) { continue; } try { _typesAlreadyEstablished.Add(typeName); var persisterType = Type.GetType(typeName, false); if (persisterType != null) { var persisterInstance = Activator.CreateInstance(persisterType) as IAttributeSerializationDefinition; if (persisterInstance != null && !_typesToQuery.Contains(persisterInstance.DataSerializationType)) { _typesToQuery.Add(persisterInstance.DataSerializationType); } } } catch (Exception ex) { LogHelper.Error <NhCriteriaVisitor>("Error while trying to decide which value-tables to join & query", ex); throw; } } // U5-789 // Workaround pending a better check of what data is actually saved // An issue arose because previous data had been saved in long-string, // but the datatype changed to be just string, therefore only string was // being queried despite all the data residing still in long-string if (_typesToQuery.Contains(DataSerializationTypes.String) && !_typesToQuery.Contains(DataSerializationTypes.LongString)) { _typesToQuery.Add(DataSerializationTypes.LongString); } //NodeVersion aliasNodeVersion = null; //Attribute aliasAttribute = null; //AttributeDefinition aliasAttributeDefinition = null; //AttributeStringValue aliasStringValue = null; //AttributeLongStringValue aliasLongStringValue = null; //AttributeIntegerValue aliasIntegerValue = null; //AttributeDecimalValue aliasDecimalValue = null; //NodeRelation aliasNodeRelation = null; //AttributeDateValue aliasDateValue = null; //QueryOver<NodeVersion, AttributeDefinition> queryExtender = QueryOver.Of<NodeVersion>(() => aliasNodeVersion) // .JoinQueryOver<Attribute>(() => aliasNodeVersion.Attributes, () => aliasAttribute) // .JoinQueryOver<AttributeDefinition>(() => aliasAttribute.AttributeDefinition, () => aliasAttributeDefinition); int numberOfMatchesEvaluated = 0; AbstractCriterion restrictionBuilder = null; foreach (var dataSerializationTypese in _typesToQuery.Distinct()) { AbstractCriterion restriction = null; Expression <Func <object> > propertyExpression = null; Expression <Func <object> > subkeyExpression = null; List <ValuePredicateType> validClauseTypes = null; var useLikeMatchForStrings = false; switch (dataSerializationTypese) { case DataSerializationTypes.SmallInt: case DataSerializationTypes.LargeInt: case DataSerializationTypes.Boolean: propertyExpression = () => integerVal.Value; subkeyExpression = () => integerVal.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.GreaterThan, ValuePredicateType.GreaterThanOrEqual, ValuePredicateType.LessThan, ValuePredicateType.LessThanOrEqual, ValuePredicateType.NotEqual }; break; case DataSerializationTypes.Decimal: propertyExpression = () => decimalVal.Value; subkeyExpression = () => decimalVal.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.GreaterThan, ValuePredicateType.GreaterThanOrEqual, ValuePredicateType.LessThan, ValuePredicateType.LessThanOrEqual, ValuePredicateType.NotEqual }; break; case DataSerializationTypes.String: propertyExpression = () => stringVal.Value; subkeyExpression = () => stringVal.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.NotEqual, ValuePredicateType.Contains, ValuePredicateType.StartsWith, ValuePredicateType.EndsWith, ValuePredicateType.MatchesWildcard }; break; case DataSerializationTypes.LongString: propertyExpression = () => longStrVal.Value; subkeyExpression = () => longStrVal.ValueKey; useLikeMatchForStrings = true; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.NotEqual, ValuePredicateType.Contains, ValuePredicateType.StartsWith, ValuePredicateType.EndsWith, ValuePredicateType.MatchesWildcard }; break; case DataSerializationTypes.Date: propertyExpression = () => dateVal.Value; subkeyExpression = () => dateVal.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.GreaterThan, ValuePredicateType.GreaterThanOrEqual, ValuePredicateType.LessThan, ValuePredicateType.LessThanOrEqual, ValuePredicateType.NotEqual, ValuePredicateType.Empty }; break; } if (!validClauseTypes.Contains(node.ValueExpression.ClauseType)) { throw new InvalidOperationException("A field of type {0} cannot be queried with operator {1}".InvariantFormat(dataSerializationTypese.ToString(), node.ValueExpression.ClauseType.ToString())); } switch (node.ValueExpression.ClauseType) { case ValuePredicateType.Equal: restriction = GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression, subkeyExpression, valueKey); break; case ValuePredicateType.NotEqual: restriction = !GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression); break; case ValuePredicateType.LessThan: restriction = GetRestrictionLt(fieldValue, propertyExpression); break; case ValuePredicateType.LessThanOrEqual: restriction = GetRestrictionLtEq(fieldValue, propertyExpression); break; case ValuePredicateType.GreaterThan: restriction = GetRestrictionGt(fieldValue, propertyExpression); break; case ValuePredicateType.GreaterThanOrEqual: restriction = GetRestrictionGtEq(fieldValue, propertyExpression); break; case ValuePredicateType.Contains: restriction = GetRestrictionContains(fieldValue, propertyExpression); break; case ValuePredicateType.StartsWith: restriction = GetRestrictionStarts(fieldValue, propertyExpression); break; case ValuePredicateType.EndsWith: restriction = GetRestrictionEnds(fieldValue, propertyExpression); break; } if (restriction != null) { if (numberOfMatchesEvaluated == 0) { restrictionBuilder = restriction; numberOfMatchesEvaluated++; } else { restrictionBuilder = Restrictions.Or(restriction, restrictionBuilder); } } } var fieldNameRestriction = Restrictions.Eq(Projections.Property(() => def.Alias), fieldName); if (restrictionBuilder != null) { restrictionBuilder = Restrictions.And(restrictionBuilder, fieldNameRestriction); } else { restrictionBuilder = fieldNameRestriction; } return(restrictionBuilder); }
/// <summary> /// Gets the query. /// </summary> /// <param name="snapShotType">Type of the snap shot.</param> /// <param name="entity">The entity.</param> /// <returns></returns> public ICriterion GetQuery(SnapShotType snapShotType, TEntity entity) { return(snapShotType == SnapShotType.ById ? Restrictions.Eq("Id", entity.Id) : Restrictions.And(Restrictions.Eq("Id", entity.Id), Restrictions.Le("Version", entity.Version))); }
/// <summary> /// 添加 /// </summary> /// <param name="p"></param> /// <returns></returns> public Result Add(DeptEditParam p) { // 判断机构名称是否重复 var query1 = Restrictions.Eq("Name", p.Name); ICriterion query2 = null; if (p.PID == 0) // 顶级机构 { query2 = Restrictions.Eq("PDept", null); } else // 不是顶级机构 { query2 = Restrictions.Eq("PDept", new Dept { ID = p.PID }); } var query = Restrictions.And(query1, query2); var count = dal.Count(query); if (count > 0) { return(new Result(300, "该机构已经存在!")); } // 查找父节点的Code var PCode = ""; if (p.PID > 0) // 不是顶级机构 { var pdept = dal.Get(p.PID); if (pdept != null) { PCode = pdept.Code; } } // 为当前结点生成Code var Code = ""; if (p.PID == 0) // 顶级机构 { var query3 = Restrictions.Eq("PDept", null); var dept1 = dal.List(query3, "Code", Sort.Desc).FirstOrDefault(); if (dept1 == null) // 第一个 { Code = "001"; } else // 不是第一个 { Code = StringHelper.ZeroFill((int.Parse(dept1.Code.TrimStart('0')) + 1).ToString(), 3); } } else // 不是顶级机构 { var query3 = Restrictions.Eq("PDept", null); var dept1 = dal.List(query3, "Code", Sort.Desc).FirstOrDefault(); if (dept1 == null) // 第一个 { Code = "001"; } else // 不是第一个 { Code = PCode + StringHelper.ZeroFill((int.Parse(dept1.Code.Substring(PCode.Length, 3).TrimStart('0')) + 1).ToString(), 3); } } // 添加 var dept = new Dept { AddTime = DateTime.Now, AddUser = AdminHelper.Admin, Code = Code, Comment = p.Comment, ID = 0, Name = p.Name, PDept = p.PID == 0 ? null : new Dept { ID = p.PID }, Sort = p.Sort, Status = p.Status }; if (p.TypeID != null) { dept.Type = new DicItem { ID = p.TypeID.Value }; } var result = dal.Add(dept); if (result) { return(new Result(200, "添加成功!")); } else { return(new Result(300, "添加失败!")); } }
public List <Task> SearchTasks(TaskSearchCriteria searchCriteria, int userId) { var searchTasks = new List <Task>(); using (var session = NHibernateHelper.OpenSession()) { ICriterion crTaskName = null; ICriterion crDateBetween = null; ICriterion crTaskCategory = null; ICriterion crAllOr = null; if (!String.IsNullOrEmpty(searchCriteria.TaskName)) { crTaskName = Restrictions.Like("t.TaskName", "%" + searchCriteria.TaskName + "%"); } if (searchCriteria.TaskDateFrom.HasValue && searchCriteria.TaskDateTo.HasValue) { crDateBetween = Restrictions.Between("t.TaskDate", searchCriteria.TaskDateFrom.Value, searchCriteria.TaskDateTo.Value); } if (!String.IsNullOrEmpty(searchCriteria.TaskCategory)) { crTaskCategory = Restrictions.Eq("c.CategoryName", searchCriteria.TaskCategory); } if (crTaskName != null && crDateBetween != null && crTaskCategory != null) { crAllOr = Restrictions.Conjunction() .Add(crTaskName) .Add(crTaskCategory) .Add(crDateBetween); } if (crTaskName != null && crTaskCategory == null && crDateBetween == null) { crAllOr = crTaskName; } if (crTaskName != null & crTaskCategory != null && crDateBetween == null) { crAllOr = Restrictions.Disjunction() .Add(crTaskName) .Add(crTaskCategory); } if (crTaskName != null && crTaskCategory == null && crDateBetween != null) { crAllOr = Restrictions.Conjunction() .Add(crTaskName) .Add(crDateBetween); } if (crTaskName == null && crTaskCategory != null && crDateBetween != null) { crAllOr = Restrictions.Conjunction() .Add(crTaskCategory) .Add(crDateBetween); } if (crTaskName == null && crTaskCategory == null && crDateBetween != null) { crAllOr = Restrictions.Conjunction() .Add(crDateBetween); } if (crTaskName == null && crTaskCategory != null && crDateBetween == null) { crAllOr = Restrictions.Conjunction() .Add(crTaskCategory); } var query = session.CreateCriteria <Task>("t"); query.CreateCriteria("t.TaskCategory", "c"); query.CreateCriteria("t.User", "u"); ICriterion crUserId = Restrictions.Eq("u.Id", userId); ICriterion crEndAll = null; if (crAllOr != null) { crEndAll = Restrictions.And(crUserId, crAllOr); } else { crEndAll = crUserId; } query.Add(crEndAll); searchTasks = query.List <Task>().OrderByDescending(x => x.TaskDate).ToList <Task>(); } return(searchTasks); }
/// <summary> /// 添加 /// </summary> /// <param name="model"></param> /// <returns></returns> public override Result Add(Dept model) { // 判断机构名称是否重复 var query1 = Restrictions.Eq("Name", model.Name); ICriterion query2 = null; if (model.PDept == null) // 顶级机构 { query2 = Restrictions.Eq("PDept", null); } else // 不是顶级机构 { query2 = Restrictions.Eq("PDept", new Dept { ID = model.PDept.ID }); } var query = Restrictions.And(query1, query2); var count = dal.Count(query); if (count > 0) { return(new Result(300, "该机构已经存在!")); } // 查找父节点的Code var PCode = ""; if (model.PDept != null) // 不是顶级机构 { var pdept = dal.Get(model.PDept.ID); if (pdept != null) { PCode = pdept.Code; } } // 为当前结点生成Code var Code = ""; if (model.PDept == null) // 顶级机构 { var query3 = Restrictions.Eq("PDept", null); var dept1 = dal.List(query3, "Code", Sort.Desc).FirstOrDefault(); if (dept1 == null) // 第一个 { Code = "001"; } else // 不是第一个 { Code = StringHelper.ZeroFill((int.Parse(dept1.Code.TrimStart('0')) + 1).ToString(), 3); } } else // 不是顶级机构 { var query3 = Restrictions.Eq("PDept", model.PDept); var dept1 = dal.List(query3, "Code", Sort.Desc).FirstOrDefault(); if (dept1 == null) // 第一个 { Code = "001"; } else // 不是第一个 { Code = PCode + StringHelper.ZeroFill((int.Parse(dept1.Code.Substring(PCode.Length, 3).TrimStart('0')) + 1).ToString(), 3); } } // 添加 model.AddTime = DateTime.Now; model.AddUser = AdminHelper.Admin; model.Code = Code; model.ID = 0; return(base.Add(model)); }
private static ICriterion ProcessAndExpression(BinaryExpression expression) { return(Restrictions.And( ProcessExpression(expression.Left), ProcessExpression(expression.Right))); }
/// <summary> /// Creates a query for an array of date time ranges. /// </summary> /// <param name="propertyName"></param> /// <param name="searchValue"></param> /// <returns></returns> public static ICriterion DateTimeQuery(string propertyName, object searchValue) { List <Dictionary <string, DateTime?> > values; try { values = searchValue.CastJToken <List <Dictionary <string, DateTime?> > >(); } catch { throw new CommandCentralException("Your date/time criteria must be in an array of dictionaries with at least a from/to and a corresponding date.", ErrorTypes.Validation); } var disjunction = new Disjunction(); foreach (var value in values) { DateTime?from = null; DateTime?to = null; if (value.ContainsKey("From")) { from = value["From"]; } if (value.ContainsKey("To")) { to = value["To"]; } if (to == null && from == null) { throw new CommandCentralException("You must send at least a 'from' and a 'to' date.", ErrorTypes.Validation); } //Do the validation. if ((from.HasValue && to.HasValue) && from > to) { throw new CommandCentralException($"The dates, From:'{from}' and To:'{to}', were invalid. 'From' may not be after 'To'.", ErrorTypes.Validation); } if (from == to) { disjunction.Add(Restrictions.And( Restrictions.Ge(propertyName, from.Value.Date), Restrictions.Le(propertyName, from.Value.Date.AddHours(24)))); } else if (from == null) { disjunction.Add(Restrictions.Le(propertyName, to)); } else if (to == null) { disjunction.Add(Restrictions.Ge(propertyName, from)); } else { disjunction.Add(Restrictions.And( Restrictions.Ge(propertyName, from), Restrictions.Le(propertyName, to))); } } return(disjunction); }
/// <summary> /// 获取列表 /// </summary> /// <param name="p"></param> /// <param name="total"></param> /// <returns></returns> public IList <Log> List(LogListParam p, out int total) { ICriterion query = Restrictions.Eq("Status", 0); // 关键词 if (p.name != null) { var query1 = Restrictions.Like("Title", p.name, MatchMode.Anywhere); var query2 = Restrictions.Like("Content", p.name, MatchMode.Anywhere); var query3 = Restrictions.Or(query1, query2); query = Restrictions.And(query, query3); } // 类型 if (p.type == 0) // 系统事件 { var query1 = Restrictions.Eq("Type", LogType.System); query = Restrictions.And(query, query1); } else if (p.type == 1) // 用户事件 { var query1 = Restrictions.Eq("Type", LogType.User); query = Restrictions.And(query, query1); } // 来源 if (p.source == 0) // Web系统 { var query1 = Restrictions.Eq("Source", LogSource.WebApp); query = Restrictions.And(query, query1); } else if (p.source == 1) // 移动应用 { var query1 = Restrictions.Eq("Source", LogSource.MobileApp); query = Restrictions.And(query, query1); } else if (p.source == 2) // 桌面客户端 { var query1 = Restrictions.Eq("Source", LogSource.DesktopApp); query = Restrictions.And(query, query1); } // 等级 if (p.level == 0) // 崩溃 { var query1 = Restrictions.Eq("Level", LogLevel.Fatal); query = Restrictions.And(query, query1); } else if (p.level == 1) // 错误 { var query1 = Restrictions.Eq("Level", LogLevel.Error); query = Restrictions.And(query, query1); } else if (p.level == 2) // 警告 { var query1 = Restrictions.Eq("Level", LogLevel.Warn); query = Restrictions.And(query, query1); } else if (p.level == 3) // 消息 { var query1 = Restrictions.Eq("Level", LogLevel.Info); query = Restrictions.And(query, query1); } else if (p.level == 4) // 调试 { var query1 = Restrictions.Eq("Level", LogLevel.Debug); query = Restrictions.And(query, query1); } var list = dal.List(p.firstResult, p.maxResults, out total, query); return(list); }
public static object ObterRelatorioReceitasPorBuscas(bool inBuscas, string[] buscas, ModeloDeCorteEnum corte, string dataInicial, string dataFinal, int TopItens = 5) { DTOGrafico dtoGrafico = new DTOGrafico(); try { Busca BuscasAlias = null; Receita ReceitaAlias = null; var query = Session.Current.QueryOver <Busca>(() => BuscasAlias); query = query.JoinAlias(() => BuscasAlias.Receita, () => ReceitaAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin); query.Where(Restrictions.IsNull(Projections.Property(() => ReceitaAlias.Parente))); if (!inBuscas) { query.Where(Restrictions.IsNotNull(Projections.Property(() => BuscasAlias.Receita))); } if (buscas != null && buscas.Count() > 0) { query.Where(Restrictions.On(() => BuscasAlias.Termo).IsIn(buscas)); } if (dataInicial != null && dataFinal != null) { DateTime DataInicial = DateTime.Parse(dataInicial).Date; DateTime DataFinal = DateTime.Parse(dataFinal).Date.AddHours(23).AddMinutes(59).AddSeconds(59); query.Where(Restrictions.And(Restrictions.Ge(Projections.Property(() => BuscasAlias.Data), DataInicial), Restrictions.Le(Projections.Property(() => BuscasAlias.Data), DataFinal))); } DTODado dto = new DTODado(); var nomeReceitaProperty = Projections.Conditional(Restrictions.IsNotNull(Projections.Property(() => BuscasAlias.Receita)), Projections.Cast(NHibernateUtil.String, Projections.Property(() => ReceitaAlias.Titulo)), Projections.Constant("Busca sem receita", NHibernateUtil.String)); var nomeAlias = nomeReceitaProperty.WithAlias(() => dto.Label); var idReceitaGroup = Projections.GroupProperty(Projections.Property(() => BuscasAlias.Receita)); var quantAlias = Projections.RowCount().WithAlias(() => dto.Quantidade); var corteAlias = new SQLCorteService().Executar(corte).WithAlias(() => dto.Corte); var projections = Projections.ProjectionList() .Add(nomeAlias) .Add(quantAlias) .Add(corteAlias) .Add(idReceitaGroup) ; var Dados = query.OrderBy(() => BuscasAlias.Data).Asc() .ThenBy(() => ReceitaAlias.Titulo).Asc() .Select(projections) .TransformUsing(Transformers.AliasToBean <DTODado>()) .List <DTODado>(); ObterGrafico(dtoGrafico, Dados, TopItens); } catch (Exception) { throw; } return(dtoGrafico); }
public override ICriterion Visit(BinaryOperatorNode nodeIn) { var operatorKind = nodeIn.OperatorKind; var leftNode = nodeIn.Left; var rightNode = nodeIn.Right; if (this.IsNullNode(leftNode) && this.IsNullNode(rightNode)) { return(null); } // Invert if left is null if (this.IsNullNode(leftNode)) { rightNode = nodeIn.Left; leftNode = nodeIn.Right; } if (this.IsNullNode(rightNode)) { var leftProjection = this.projectionVisitor.Visit(leftNode); if (null == leftProjection) { return(null); } switch (operatorKind) { case BinaryOperatorKind.Equal: return(Restrictions.IsNull(leftProjection)); case BinaryOperatorKind.NotEqual: return(Restrictions.IsNotNull(leftProjection)); default: return(null); } } if (this.IsComparisonOperator(operatorKind)) { var leftProjection = this.projectionVisitor.Visit(leftNode); var rightProjection = this.projectionVisitor.Visit(rightNode); if (false == (null != leftProjection && null != rightProjection)) { return(null); } switch (operatorKind) { case BinaryOperatorKind.Equal: return(Restrictions.EqProperty(leftProjection, rightProjection)); case BinaryOperatorKind.GreaterThan: return(Restrictions.GtProperty(leftProjection, rightProjection)); case BinaryOperatorKind.GreaterThanOrEqual: return(Restrictions.GeProperty(leftProjection, rightProjection)); case BinaryOperatorKind.LessThan: return(Restrictions.LtProperty(leftProjection, rightProjection)); case BinaryOperatorKind.LessThanOrEqual: return(Restrictions.LeProperty(leftProjection, rightProjection)); default: return(null); } } if (this.IsLogicalOperator(operatorKind)) { var leftCriterion = leftNode.Accept <ICriterion>(this); var rightCriterion = rightNode.Accept <ICriterion>(this); if (false == (null != leftCriterion && null != rightCriterion)) { return(null); } switch (operatorKind) { case BinaryOperatorKind.And: return(Restrictions.And(leftCriterion, rightCriterion)); case BinaryOperatorKind.Or: return(Restrictions.Or(leftCriterion, rightCriterion)); } } return(null); }
protected override ICriterion WhereExpress(string keyword) { return(Restrictions.And(Restrictions.On <Role> (r => r.Name).IsLike(keyword), Restrictions.Where <Role> (r => r.RoleType != RoleType.Internal))); }