/// <summary> /// Shows the edit. /// </summary> /// <param name="entityTypeId">The entity type id.</param> protected void ShowEdit(int entityTypeId) { pnlList.Visible = false; pnlDetails.Visible = true; EntityTypeService entityTypeService = new EntityTypeService(); EntityType entityType = entityTypeService.Get(entityTypeId); if (entityType != null) { lActionTitle.Text = ActionTitle.Edit(EntityType.FriendlyTypeName); hfEntityTypeId.Value = entityType.Id.ToString(); tbName.Text = entityType.Name; tbFriendlyName.Text = entityType.FriendlyName; cbCommon.Checked = entityType.IsCommon; } else { lActionTitle.Text = ActionTitle.Add(EntityType.FriendlyTypeName); hfEntityTypeId.Value = 0.ToString(); tbName.Text = string.Empty; tbFriendlyName.Text = string.Empty; cbCommon.Checked = false; } tbName.Enabled = !entityType.IsEntity; }
/// <summary> /// Handles the SaveClick event of the mdEdit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void mdEdit_SaveClick(object sender, EventArgs e) { var rockContext = new RockContext(); EntityTypeService entityTypeService = new EntityTypeService(rockContext); EntityType entityType = entityTypeService.Get(int.Parse(hfEntityTypeId.Value)); if (entityType == null) { entityType = new EntityType(); entityType.IsEntity = true; entityType.IsSecured = true; entityTypeService.Add(entityType); } entityType.Name = tbName.Text; entityType.FriendlyName = tbFriendlyName.Text; entityType.IsCommon = cbCommon.Checked; rockContext.SaveChanges(); hfEntityTypeId.Value = string.Empty; HideDialog(); BindGrid(); }
/// <summary> /// Reads the specified GUID. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public static EntityTypeCache Read(Guid guid) { ObjectCache cache = MemoryCache.Default; object cacheObj = cache[guid.ToString()]; if (cacheObj != null) { return(Read((int)cacheObj)); } else { var entityTypeService = new EntityTypeService(); var entityTypeModel = entityTypeService.Get(guid); if (entityTypeModel != null) { var entityType = new EntityTypeCache(entityTypeModel); var cachePolicy = new CacheItemPolicy(); cache.Set(EntityTypeCache.CacheKey(entityType.Id), entityType, cachePolicy); cache.Set(entityType.Guid.ToString(), entityType.Id, cachePolicy); return(entityType); } else { return(null); } } }
/// <summary> /// Handles the SaveClick event of the mdEdit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void mdEdit_SaveClick(object sender, EventArgs e) { var rockContext = new RockContext(); EntityTypeService entityTypeService = new EntityTypeService(rockContext); EntityType entityType = entityTypeService.Get(int.Parse(hfEntityTypeId.Value)); if (entityType == null) { entityType = new EntityType(); entityType.IsEntity = true; entityType.IsSecured = true; entityTypeService.Add(entityType); } entityType.Name = tbName.Text; entityType.FriendlyName = tbFriendlyName.Text; entityType.IsCommon = cbCommon.Checked; entityType.IndexResultTemplate = ceIndexResultsTemplate.Text; entityType.IndexDocumentUrl = ceIndexDocumentUrl.Text; entityType.LinkUrlLavaTemplate = ceLinkUrl.Text; rockContext.SaveChanges(); EntityTypeCache.Flush(entityType.Id); hfEntityTypeId.Value = string.Empty; HideDialog(); BindGrid(); }
/// <summary> /// Reads the specified name. /// </summary> /// <param name="name">The name.</param> /// <param name="createNew">if set to <c>true</c> [create new].</param> /// <returns></returns> public static EntityTypeCache Read(string name, bool createNew) { int?entityTypeId = null; lock ( obj ) { if (entityTypes.ContainsKey(name)) { entityTypeId = entityTypes[name]; } } if (entityTypeId.HasValue) { return(Read(entityTypeId.Value)); } var entityTypeService = new EntityTypeService(); var entityTypeModel = entityTypeService.Get(name, createNew, null); if (entityTypeModel != null) { return(Read(entityTypeModel)); } else { return(null); } }
/// <summary> /// Returns EntityType object from cache. If entityBlockType does not already exist in cache, it /// will be read and added to cache /// </summary> /// <param name="id"></param> /// <returns></returns> public static EntityTypeCache Read(int id) { string cacheKey = EntityTypeCache.CacheKey(id); ObjectCache cache = MemoryCache.Default; EntityTypeCache entityType = cache[cacheKey] as EntityTypeCache; if (entityType != null) { return(entityType); } else { var entityTypeService = new EntityTypeService(); var entityTypeModel = entityTypeService.Get(id); if (entityTypeModel != null) { entityType = new EntityTypeCache(entityTypeModel); var cachePolicy = new CacheItemPolicy(); cache.Set(cacheKey, entityType, cachePolicy); cache.Set(entityType.Guid.ToString(), entityType.Id, cachePolicy); return(entityType); } else { return(null); } } }
/// <summary> /// Shows the edit. /// </summary> /// <param name="entityTypeId">The entity type id.</param> protected void ShowEdit(int entityTypeId) { EntityTypeService entityTypeService = new EntityTypeService(new RockContext()); EntityType entityType = entityTypeService.Get(entityTypeId); if (entityType != null) { mdEdit.Title = ActionTitle.Edit(EntityType.FriendlyTypeName); hfEntityTypeId.Value = entityType.Id.ToString(); tbName.Text = entityType.Name; tbName.Enabled = false; // !entityType.IsEntity; tbFriendlyName.Text = entityType.FriendlyName; cbCommon.Checked = entityType.IsCommon; ceIndexResultsTemplate.Text = entityType.IndexResultTemplate; ceIndexDocumentUrl.Text = entityType.IndexDocumentUrl; ceLinkUrl.Text = entityType.LinkUrlLavaTemplate; } else { mdEdit.Title = ActionTitle.Add(EntityType.FriendlyTypeName); hfEntityTypeId.Value = 0.ToString(); tbName.Text = string.Empty; tbName.Enabled = true; tbFriendlyName.Text = string.Empty; cbCommon.Checked = false; ceIndexResultsTemplate.Text = string.Empty; ceIndexDocumentUrl.Text = string.Empty; ceLinkUrl.Text = string.Empty; } ShowDialog("Edit"); }
/// <summary> /// Handles the SaveClick event of the MdEditEntityType control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> private void MdEditEntityType_SaveClick(object sender, EventArgs e) { using (RockContext rockContext = new RockContext()) { EntityTypeService entityTypeService = new EntityTypeService(rockContext); var entityType = entityTypeService.Get(hfIdValue.ValueAsInt()); entityType.IsIndexingEnabled = cbEnabledIndexing.Checked; rockContext.SaveChanges(); if (cbEnabledIndexing.Checked) { IndexContainer.CreateIndex(entityType.IndexModelType); // call for bulk indexing BulkIndexEntityTypeTransaction bulkIndexTransaction = new BulkIndexEntityTypeTransaction(); bulkIndexTransaction.EntityTypeId = entityType.Id; RockQueue.TransactionQueue.Enqueue(bulkIndexTransaction); } else { IndexContainer.DeleteIndex(entityType.IndexModelType); } } mdEditEntityType.Hide(); LoadEntities(); }
/// <summary> /// Handles the SaveClick event of the MdEditEntityType control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> private void MdEditEntityType_SaveClick(object sender, EventArgs e) { using (RockContext rockContext = new RockContext()) { EntityTypeService entityTypeService = new EntityTypeService(rockContext); var entityType = entityTypeService.Get(hfIdValue.ValueAsInt()); entityType.IsIndexingEnabled = cbEnabledIndexing.Checked; rockContext.SaveChanges(); if (cbEnabledIndexing.Checked) { IndexContainer.CreateIndex(entityType.IndexModelType); // call for bulk indexing var processEntityTypeBulkIndexMsg = new ProcessEntityTypeBulkIndex.Message { EntityTypeId = entityType.Id }; processEntityTypeBulkIndexMsg.Send(); } else { IndexContainer.DeleteIndex(entityType.IndexModelType); } } mdEditEntityType.Hide(); LoadEntities(); }
private static EntityTypeCache LoadById2(int id, RockContext rockContext) { var entityTypeService = new EntityTypeService(rockContext); var entityTypeModel = entityTypeService.Get(id); if (entityTypeModel != null) { return(new EntityTypeCache(entityTypeModel)); } return(null); }
/// <summary> /// Re-indexes the selected entity types in Universal Search /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; string selectedEntitiesSetting = dataMap.GetString("EntityFilter"); bool allEntities = dataMap.GetBoolean("IndexAllEntities"); RockContext rockContext = new RockContext(); var selectedEntityTypes = EntityTypeCache.All().Where(e => e.IsIndexingSupported && e.IsIndexingEnabled && e.FriendlyName != "Site"); // if 'All' wasn't selected the filter out the ones that weren't selected if (!allEntities) { if (selectedEntitiesSetting.IsNotNullOrWhiteSpace()) { var selectedEntityIds = selectedEntitiesSetting.Split(',').Select(int.Parse).ToList(); selectedEntityTypes = selectedEntityTypes.Where(e => selectedEntityIds.Contains(e.Id)); } } string results = string.Empty; var timerTotal = System.Diagnostics.Stopwatch.StartNew(); foreach (var entityTypeCache in selectedEntityTypes) { EntityTypeService entityTypeService = new EntityTypeService(rockContext); var entityType = entityTypeService.Get(entityTypeCache.Id); IndexContainer.DeleteIndex(entityType.IndexModelType); IndexContainer.CreateIndex(entityType.IndexModelType); Type type = entityTypeCache.GetEntityType(); if (type != null) { object classInstance = Activator.CreateInstance(type, null); MethodInfo bulkItemsMethod = type.GetMethod("BulkIndexDocuments"); if (classInstance != null && bulkItemsMethod != null) { var timer = System.Diagnostics.Stopwatch.StartNew(); bulkItemsMethod.Invoke(classInstance, null); timer.Stop(); results += $"{entityType.FriendlyName}: {timer.ElapsedMilliseconds/1000}s,"; } } } results += $"Total Time: {timerTotal.ElapsedMilliseconds / 1000}s,"; context.Result = "Indexing results: " + results.Trim(','); }
/// <summary> /// Handles the Click event of the gRefresh control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gRefresh_Click(object sender, RowEventArgs e) { RockContext rockContext = new RockContext(); EntityTypeService entityTypeService = new EntityTypeService(rockContext); var entityType = entityTypeService.Get(e.RowKeyId); if (entityType != null) { IndexContainer.DeleteIndex(entityType.IndexModelType); IndexContainer.CreateIndex(entityType.IndexModelType); maMessages.Show(string.Format("The index for {0} has been re-created.", entityType.FriendlyName), ModalAlertType.Information); } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { EntityTypeService entityTypeService = new EntityTypeService(); EntityType entityType = entityTypeService.Get(int.Parse(hfEntityTypeId.Value)); entityType.FriendlyName = tbFriendlyName.Text; entityTypeService.Save(entityType, CurrentPersonId); BindGrid(); pnlDetails.Visible = false; pnlList.Visible = true; hfEntityTypeId.Value = string.Empty; }
public new object[] Get() { var logins = base.Get(); var apollosLogins = new Queue(); var context = new RockContext(); var entityTypeService = new EntityTypeService(context); var apollosAuth = entityTypeService.Get(ApollosAuthName); var apollosAuthId = apollosAuth.Id; foreach (var login in logins) { if (Validation.IsEmail(login.UserName) && login.EntityTypeId == apollosAuthId) { apollosLogins.Enqueue(new ApollosUserLogin(login)); } } return(apollosLogins.ToArray()); }
/// <summary> /// Reads the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static EntityTypeCache Read(Type type) { int?entityTypeId = null; lock ( obj ) { if (entityTypes.ContainsKey(type.FullName)) { entityTypeId = entityTypes[type.FullName]; } } if (entityTypeId.HasValue) { return(Read(entityTypeId.Value)); } var entityTypeService = new EntityTypeService(); var entityTypeModel = entityTypeService.Get(type, true, null); return(Read(entityTypeModel)); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { BinaryFileType binaryFileType; var rockContext = new RockContext(); BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); CategoryService categoryService = new CategoryService(rockContext); int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value); if (binaryFileTypeId == 0) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add(binaryFileType); } else { binaryFileType = binaryFileTypeService.Get(binaryFileTypeId); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.AllowCaching = cbAllowCaching.Checked; binaryFileType.RequiresSecurity = cbRequiresSecurity.Checked; if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue)) { var entityTypeService = new EntityTypeService(rockContext); var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue)); if (storageEntityType != null) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } binaryFileType.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType); if (!binaryFileType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { rockContext.SaveChanges(); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid); /* Take care of Binary File Attributes */ var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id; // delete BinaryFileAttributes that are no longer configured in the UI var attributes = attributeService.Get(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString()); var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr); } rockContext.SaveChanges(); // add/update the BinaryFileAttributes that are assigned in the UI foreach (var attributeState in BinaryFileAttributesState) { Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext); } // SaveAttributeValues for the BinaryFileType binaryFileType.SaveAttributeValues(rockContext); }); NavigateToParentPage(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { using (new UnitOfWorkScope()) { BinaryFileType binaryFileType; BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(); AttributeService attributeService = new AttributeService(); int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value); if (binaryFileTypeId == 0) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add(binaryFileType, CurrentPersonId); } else { binaryFileType = binaryFileTypeService.Get(binaryFileTypeId); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.IconSmallFileId = imgIconSmall.ImageId; binaryFileType.IconLargeFileId = imgIconLarge.ImageId; if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue)) { var entityTypeService = new EntityTypeService(); var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue)); if (storageEntityType != null) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } if (!binaryFileType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { binaryFileTypeService.Save(binaryFileType, CurrentPersonId); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid); /* Take care of Binary File Attributes */ // delete BinaryFileAttributes that are no longer configured in the UI string qualifierValue = binaryFileType.Id.ToString(); var BinaryFileAttributesQry = attributeService.GetByEntityTypeId(new BinaryFile().TypeId).AsQueryable() .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(qualifierValue)); var deletedBinaryFileAttributes = from attr in BinaryFileAttributesQry where !(from d in BinaryFileAttributesState select d.Guid).Contains(attr.Guid) select attr; deletedBinaryFileAttributes.ToList().ForEach(a => { var attr = attributeService.Get(a.Guid); Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr, CurrentPersonId); attributeService.Save(attr, CurrentPersonId); }); // add/update the BinaryFileAttributes that are assigned in the UI foreach (var attributeState in BinaryFileAttributesState) { // remove old qualifiers in case they changed var qualifierService = new AttributeQualifierService(); foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList()) { qualifierService.Delete(oldQualifier, CurrentPersonId); qualifierService.Save(oldQualifier, CurrentPersonId); } Attribute attribute = BinaryFileAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid)); if (attribute == null) { attribute = attributeState.Clone() as Rock.Model.Attribute; attributeService.Add(attribute, CurrentPersonId); } else { attributeState.Id = attribute.Id; attribute.FromDictionary(attributeState.ToDictionary()); foreach (var qualifier in attributeState.AttributeQualifiers) { attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier); } } attribute.EntityTypeQualifierColumn = "BinaryFileTypeId"; attribute.EntityTypeQualifierValue = binaryFileType.Id.ToString(); attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id; Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Save(attribute, CurrentPersonId); } }); } NavigateToParentPage(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { BinaryFileType binaryFileType; var rockContext = new RockContext(); BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); CategoryService categoryService = new CategoryService(rockContext); int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value); if (binaryFileTypeId == 0) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add(binaryFileType); } else { binaryFileType = binaryFileTypeService.Get(binaryFileTypeId); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.CacheToServerFileSystem = cbCacheToServerFileSystem.Checked; binaryFileType.CacheControlHeaderSettings = cpCacheSettings.CurrentCacheablity.ToJson(); binaryFileType.RequiresViewSecurity = cbRequiresViewSecurity.Checked; binaryFileType.MaxWidth = nbMaxWidth.Text.AsInteger(); binaryFileType.MaxHeight = nbMaxHeight.Text.AsInteger(); binaryFileType.PreferredFormat = ddlPreferredFormat.SelectedValueAsEnum <Format>(); binaryFileType.PreferredResolution = ddlPreferredResolution.SelectedValueAsEnum <Resolution>(); binaryFileType.PreferredColorDepth = ddlPreferredColorDepth.SelectedValueAsEnum <ColorDepth>(); binaryFileType.PreferredRequired = cbPreferredRequired.Checked; if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue)) { var entityTypeService = new EntityTypeService(rockContext); var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue)); if (storageEntityType != null) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } binaryFileType.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType); if (!binaryFileType.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid); /* Take care of Binary File Attributes */ var entityTypeId = EntityTypeCache.Get(typeof(BinaryFile)).Id; // delete BinaryFileAttributes that are no longer configured in the UI var attributes = attributeService.GetByEntityTypeQualifier(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), true); var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { attributeService.Delete(attr); } rockContext.SaveChanges(); // add/update the BinaryFileAttributes that are assigned in the UI foreach (var attributeState in BinaryFileAttributesState) { Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext); } // SaveAttributeValues for the BinaryFileType binaryFileType.SaveAttributeValues(rockContext); }); NavigateToParentPage(); }
public object Post([FromBody] Dictionary <string, string> data) { var response = new HttpResponseMessage(); if (!data.ContainsKey(UserNameKey)) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(string.Format("Data must contain {0} ", UserNameKey)); return(response); } if (!data.ContainsKey(HashKey)) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(string.Format("Data must contain {0} ", HashKey)); return(response); } var userName = data[UserNameKey]; var hash = data[HashKey]; if (!Validation.IsEmail(userName)) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(string.Format("{0} must be a valid email", UserNameKey)); return(response); } if (!Validation.IsBcryptHash(hash)) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(string.Format("{0} must be a valid Bcrypt hash", HashKey)); return(response); } var context = new RockContext(); var userLoginService = new UserLoginService(context); var existing = userLoginService.GetByUserName(userName); if (existing != null) { response.StatusCode = HttpStatusCode.Conflict; response.Content = new StringContent(string.Format("UserLogin with id={0} employs username {1}", existing.Id, existing.UserName)); return(response); } var entityTypeService = new EntityTypeService(context); var apollosAuth = entityTypeService.Get(ApollosAuthName); if (apollosAuth == null) { response.StatusCode = HttpStatusCode.InternalServerError; response.Content = new StringContent("Cannot find the Apollos Auth Entity"); return(response); } var userLogin = new UserLogin { EntityTypeId = apollosAuth.Id, Password = hash, UserName = userName }; userLogin.CreatedByPersonAliasId = GetPerson().PrimaryAliasId; userLoginService.Add(userLogin); context.SaveChanges(); return(new ApollosUserLogin(userLogin)); }
/// <summary> /// Searches the specified query. /// </summary> /// <param name="query">The query.</param> /// <param name="searchType">Type of the search.</param> /// <param name="entities">The entities.</param> /// <param name="fieldCriteria">The field criteria.</param> /// <param name="size">The size.</param> /// <param name="from">From.</param> /// <param name="totalResultsAvailable">The total results available.</param> /// <returns></returns> public override List <IndexModelBase> Search(string query, SearchType searchType, List <int> entities, SearchFieldCriteria fieldCriteria, int?size, int?from, out long totalResultsAvailable) { List <IndexModelBase> documents = new List <IndexModelBase>(); totalResultsAvailable = 0; bool allEntities = false; BooleanQuery queryContainer = new BooleanQuery(); List <string> combinedFields = new List <string>(); List <Type> indexModelTypes = new List <Type>(); Dictionary <string, Analyzer> combinedFieldAnalyzers = new Dictionary <string, Analyzer>(); using (RockContext rockContext = new RockContext()) { var entityTypeService = new EntityTypeService(rockContext); if (entities == null || entities.Count == 0) { //add all entities allEntities = true; var selectedEntityTypes = EntityTypeCache.All().Where(e => e.IsIndexingSupported && e.IsIndexingEnabled && e.FriendlyName != "Site"); foreach (var entityTypeCache in selectedEntityTypes) { entities.Add(entityTypeCache.Id); } } foreach (var entityId in entities) { // get entities search model name var entityType = entityTypeService.Get(entityId); indexModelTypes.Add(entityType.IndexModelType); // check if this is a person model, if so we need to add two model types one for person and the other for businesses // wish there was a cleaner way to do this if (entityType.Guid == SystemGuid.EntityType.PERSON.AsGuid()) { indexModelTypes.Add(typeof(BusinessIndex)); } } indexModelTypes = indexModelTypes.Distinct().ToList(); CombineIndexTypes(indexModelTypes, out combinedFields, out combinedFieldAnalyzers); if (entities != null && entities.Count != 0 && !allEntities) { var indexModelTypesQuery = new BooleanQuery(); indexModelTypes.ForEach(f => indexModelTypesQuery.Add(new TermQuery(new Term("type", f.Name.ToLower())), Occur.SHOULD)); queryContainer.Add(indexModelTypesQuery, Occur.MUST); } } TopDocs topDocs = null; // Use the analyzer in fieldAnalyzers if that field is in that dictionary, otherwise use StandardAnalyzer. PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(defaultAnalyzer: new StandardAnalyzer(_matchVersion), fieldAnalyzers: combinedFieldAnalyzers); if (fieldCriteria != null && fieldCriteria.FieldValues?.Count > 0) { Occur occur = fieldCriteria.SearchType == CriteriaSearchType.And ? Occur.MUST : Occur.SHOULD; foreach (var match in fieldCriteria.FieldValues) { BooleanClause booleanClause = new BooleanClause(new TermQuery(new Term(match.Field, match.Value)), occur); booleanClause.Query.Boost = match.Boost; queryContainer.Add(booleanClause); } } switch (searchType) { case SearchType.ExactMatch: { var wordQuery = new BooleanQuery(); if (!string.IsNullOrWhiteSpace(query)) { var words = query.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var word in words) { var innerQuery = new BooleanQuery(); combinedFields.ForEach(f => innerQuery.Add(new PrefixQuery(new Term(f, word.ToLower())), Occur.SHOULD)); wordQuery.Add(innerQuery, Occur.SHOULD); } } if (wordQuery.Count() != 0) { queryContainer.Add(wordQuery, Occur.MUST); } // special logic to support emails if (query.Contains("@")) { queryContainer.Add(new BooleanClause(new TermQuery(new Term("Email", query)), Occur.SHOULD)); } // special logic to support phone search if (query.IsDigitsOnly()) { queryContainer.Add(new BooleanClause(new WildcardQuery(new Term("PhoneNumbers", "*" + query + "*")), Occur.SHOULD)); } // add a search for all the words as one single search term foreach (var field in combinedFields) { var phraseQuery = new PhraseQuery(); phraseQuery.Add(new Term(field, query.ToLower())); queryContainer.Add(phraseQuery, Occur.SHOULD); } break; } case SearchType.Fuzzy: { foreach (var field in combinedFields) { queryContainer.Add(new FuzzyQuery(new Term(field, query.ToLower())), Occur.SHOULD); } break; } case SearchType.Wildcard: { bool enablePhraseSearch = true; if (!string.IsNullOrWhiteSpace(query)) { BooleanQuery wildcardQuery = new BooleanQuery(); // break each search term into a separate query and add the * to the end of each var queryTerms = query.Split(' ').Select(p => p.Trim()).ToList(); // special logic to support emails if (queryTerms.Count == 1 && query.Contains("@")) { wildcardQuery.Add(new WildcardQuery(new Term("Email", "*" + query.ToLower() + "*")), Occur.SHOULD); enablePhraseSearch = false; } else { foreach (var queryTerm in queryTerms) { if (!string.IsNullOrWhiteSpace(queryTerm)) { var innerQuery = new BooleanQuery(); combinedFields.ForEach(f => innerQuery.Add(new PrefixQuery(new Term(f, queryTerm.ToLower())), Occur.SHOULD)); wildcardQuery.Add(innerQuery, Occur.MUST); } } // add special logic to help boost last names if (queryTerms.Count() > 1 && (indexModelTypes.Contains(typeof(PersonIndex)) || indexModelTypes.Contains(typeof(BusinessIndex)))) { BooleanQuery nameQuery = new BooleanQuery { { new PrefixQuery(new Term("FirstName", queryTerms.First().ToLower())), Occur.MUST }, { new PrefixQuery(new Term("LastName", queryTerms.Last().ToLower())) { Boost = 30 }, Occur.MUST } }; wildcardQuery.Add(nameQuery, Occur.SHOULD); nameQuery = new BooleanQuery { { new PrefixQuery(new Term("NickName", queryTerms.First().ToLower())), Occur.MUST }, { new PrefixQuery(new Term("LastName", queryTerms.Last().ToLower())) { Boost = 30 }, Occur.MUST } }; wildcardQuery.Add(nameQuery, Occur.SHOULD); } // special logic to support phone search if (query.IsDigitsOnly()) { wildcardQuery.Add(new PrefixQuery(new Term("PhoneNumbers", queryTerms.First().ToLower())), Occur.SHOULD); } } queryContainer.Add(wildcardQuery, Occur.MUST); } // add a search for all the words as one single search term if (enablePhraseSearch) { // add a search for all the words as one single search term foreach (var field in combinedFields) { var phraseQuery = new PhraseQuery(); phraseQuery.Add(new Term(field, query.ToLower())); queryContainer.Add(phraseQuery, Occur.SHOULD); } } break; } } int returnSize = 10; if (size.HasValue) { returnSize = size.Value; } OpenReader(); if (from.HasValue) { TopScoreDocCollector collector = TopScoreDocCollector.Create(returnSize * 10, true); // Search for 10 pages with returnSize entries in each page _indexSearcher.Search(queryContainer, collector); topDocs = collector.GetTopDocs(from.Value, returnSize); } else { topDocs = _indexSearcher.Search(queryContainer, returnSize); } totalResultsAvailable = topDocs.TotalHits; if (topDocs != null) { foreach (var hit in topDocs.ScoreDocs) { var document = LuceneDocToIndexModel(queryContainer, hit); if (document != null) { documents.Add(document); } } } return(documents); }