How to get all PageTemplate that contains a specific component? - c#

I have a pagetemplate called ArticlePageTemplate. This ArticlePageTemplate contains a component called Articles. The Article component has data field called Header, SubHeader, Date, and Content.
Presentation details of ArticlesPageTemplate
Using Lucene in sitecore 8. How do I get all ArticlePageTemplate that contains an Article component with the value of "News" in subheader of Article component.
Sitecore structure:
Here is my code
public class LuceneSearchService : ILuceneSearchService, IDisposable
{
bool disposed = false;
// Instantiate a SafeHandle instance.
SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
private IProviderSearchContext _SearchContext;
private ISearchIndex _Index;
private string _IndexName = "sitecore_web_index";
public string IndexName
{
get { return _IndexName; }
set { _IndexName = value; }
}
public LuceneSearchService()
{
_Index = ContentSearchManager.GetIndex(this.IndexName);
_SearchContext = _Index.CreateSearchContext();
}
public IQueryable<SearchResultItem> PerformSearch(string searchPath)
{
var searchQuery = _SearchContext.GetQueryable<SearchResultItem>()
.Where(i => i.Path.StartsWith(searchPath));
return searchQuery;
}
public IQueryable<SearchResultItem> PerformSearch(string searchPath, string templateName)
{
var searchQuery = PerformSearch(searchPath).Where(x => x.TemplateName == templateName);
return searchQuery;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
_SearchContext.Dispose();
_Index.Dispose();
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
Code implementation
public void SearchArticles()
{
var articles = SearchService.PerformSearch("/sitecore/content", "ArticlePageTemplate").ToList();
foreach (var article in articles){
var articleName = article;
}
}
I can get all the ArticlesPageTemplate using the code above but I can't filter it to get only those ArticlePageTemplate that contains an Article component in which Article component's subheader is "news".
I do not know how to get the articles component of ArticlePageTemplate so I could add them to my search query in lucene.
Any advice is appreciated.
Note:
The datasource of ArticlesComponent may change so it is not always a child of ArticlesPageTemplate.
UPDATE (09/11/2015)
I tried what Richard suggested but it does not work.
var articles = SearchService
.PerformSearch<ArticleResultItem>("/sitecore/content", "ArticlePageTemplate")
.Where(item => item.SubHeader == "News").ToList();
Using the above query does not yield any result but using the below query returns a result but it retrieves ArticleComponent instead of ArticlePageTemplate.
var articles = SearchService
.PerformSearch<ArticleResultItem>("/sitecore/content"
.Where(item => item.SubHeader == "News").ToList();
SOLUTION:
Computed fields works. See VisualizationField.cs from the link below:
https://gist.github.com/techphoria414/7604814

I can see two approaches that you can go with here:
Build a 'computed field' for the Article component subheader field. You would set this up so that the index is configured to look for this component on an item with the ArticlePageTemplate template and compute the subheader value into the index. This essentially makes the index think that the subheader field is actually a field on ArticlePageTemplate item. Then you can do a regular search on the index.
Find the reference pages for a component. In this scenario, you search the index for the components (not ArticlePageTemplate), and if you can depend on your folder structure and you do not have re-use across pages, you can then just grab the parent page of any search result. (item.Parent.Parent, in your example structure)
UPDATE: Some links for computed fields:
http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2013/03/sitecore-7-computed-index-fields.aspx
https://gist.github.com/techphoria414/7604814

You would need to create a custom class that allows you to filter on your field, you can base it off the SearchResultItem class.
So something like:
public class ArticleResultItem : SearchResultItem
{
[IndexField("SubHeader")]
public string SubHeader { get;set; }
}
Then if you change your PerformSearch method to take a generic based of SearchResultItem, you can filter using that field in your calling method.
public IQueryable<T> PerformSearch<T>(string searchPath)
where T: SearchResultItem
{
var searchQuery = _SearchContext.GetQueryable<T>()
.Where(i => i.Path.StartsWith(searchPath));
return searchQuery;
}
public IQueryable<T> PerformSearch<T>(string searchPath, string templateName)
where T: SearchResultItem
{
var searchQuery = PerformSearch<T>(searchPath).Where(x => x.TemplateName == templateName);
return searchQuery;
}
And then you would call it like this:
public void SearchArticles()
{
var articles = SearchService
.PerformSearch<ArticleResultItem>("/sitecore/content", "ArticlePageTemplate")
.Where(item => item.SubHeader == "News").ToList();
foreach (var article in articles){
var articleName = article;
// Do something with the list here....
}
}

Related

How to Provide Fluent Validation on Multi-Select Component using MudBlazor

I have a Blazor app that manages a lot of form input. Every form is tied to an instance of type IncidentLog, and every UI element of the form is tied to a property of that IncidentLog instance.
In the form, we have a MudSelect component where T="Department". The MudSelect has MultiSelection="true", and the results are stored in a IEnumerable(Department) Departments property of the IncidentLog instance.
This component works totally fine, but I've tried implementing FluentValidation in the form and I'm not sure how to define the expression of the For parameter of this MudSelect component. It looks like it's expecting me to pass an object that matches T="Department", but the validation I need to run against the validator is based off of IEnumerable(Department)... I just want to check that the user has selected at least one department from the multiselect component.
Error message when trying to pass IEnumerable object to the For validator:
IncidentLogPropertiesComponent razor page - relevant blurb
<MudForm Model="#Log" #ref="#form" Validation="#(incidentLogValidator.ValidateValue)" ValidationDelay="100">
<MudCardContent Class="pt-0">
...
<MudSelect T="Department" ToStringFunc="#ConverterDepartment" Dense="true" Margin="Margin.Dense" Label="Affected Departments:" MultiSelection="true" #bind-SelectedValues="Log.Departments" Clearable>
#foreach (var department in Departments.OrderBy(o=>o.DepartmentName).ToList())
{
<MudSelectItem Value="#department"/>
}
</MudSelect>
...
</MudCardContent>
</MudForm>
IncidentLog.cs:
public class IncidentLog : Log
{
[Key]
public int IncidentID { get; set; }
....
[Write(false)]
public IEnumerable<Department> Departments { get; set; } = new HashSet<Department>();//3
....
}
IncidentLogPropertiesComponentBase
public class IncidentLogPropertiesComponentBase : OwningComponentBase<iIncidentLogRepository>, IDisposable
{
protected IncidentLogValidator incidentLogValidator = new IncidentLogValidator();
...
[Parameter]
public IncidentLog? Log
{
get
{
return (AppState.SelectedLog != null && AppState.SelectedLog.LogType.LogTypeID == 2) ? (IncidentLog)AppState.SelectedLog : null;
}
set
{
AppState.SetLog(value);
}
}
}
IncidentLogValidator:
public class IncidentLogValidator: AbstractValidator<IncidentLog>
{
public IncidentLogValidator()
{
...
RuleFor(t => t.Departments).NotEmpty().WithMessage("Must enter at least one department affected.");
}
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(ValidationContext<IncidentLog>.CreateWithOptions((IncidentLog)model, x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}
*I didn't link my AppState state management file even though it's referenced in code above - I don't think it's relevant to the issue I'm having.
How do I provide Fluent Validation to Multi-Select Dropdowns using MudBlazor?

Missing a cast in a linq query for a controller

I am new with c# controllers and I am trying to join two entities with a LINQ query. But I am getting a 'missing a cast' error message as shown below that I don't understand and it does not help me to correct the error.
The controller looks like:
public class SoonDueReportsController_simple : BaseODataController
{
public SoonDueReportsController_simple(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
public SoonDueReportsController_simple Get()
{
var falligkeiten = UnitOfWork.GetAll<Fälligkeiten>();
var betriebe = UnitOfWork.GetAll<Betriebe>();
var query = (from betrieb in betriebe.AsQueryable()
join fallig in falligkeiten.AsQueryable()
on betrieb.ID equals
fallig.Betrieb_ID
where fallig.Fälligkeit_Erledigt_Datum == null
&& betrieb.Aktiv == true
select new
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
return query;
}
}
This type of controller I have used with success for single entities (tables from an sql db) to display static data in a kendo grid. But I fail when I try to join two tables as shown above. If someone could help me with this problem I'd appreciate it very much.
Regards, Manu
You select a collection of anonymous objects
select new
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
And want the method to return a instance of certain type. C# is the strongly typed language without type inference, which means you have to specifically create objects of a certain type or interface if you want to return them.
Also, you are have the controller type itself to be returned from the Get method. This makes no sense. I actually do not know what you want to do but may be this would work:
public class SoonDueReportsController_simple : BaseODataController
{
public SoonDueReportsController_simple(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<SomeModel> Get()
{
var falligkeiten = UnitOfWork.GetAll<Fälligkeiten>();
var betriebe = UnitOfWork.GetAll<Betriebe>();
var query = (from betrieb in betriebe.AsQueryable()
join fallig in falligkeiten.AsQueryable()
on betrieb.ID equals
fallig.Betrieb_ID
where fallig.Fälligkeit_Erledigt_Datum == null
&& betrieb.Aktiv == true
select new SomeModel
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
return query;
}
}
public class SomeModel
{
public int BetriebId { get; set; }
public string FalligkeitObject { get; set; }
}
Please bear in mind that there are no such things as "C# controllers". You are working with OData, so I would recommend you to look at some OData resources, there are plenty of examples out there.
And one last thing, don't get me wrong, but it does not help giving properties, types and other identifiers German names. People would have hard time trying to understand your code.
The exception explains to you the problem exactly. You're wanting to return a type of 'SoonDueReportsController_simple' and yet you are returning a Queryable where a' is your new { ..., ... } object.
I like the suggestion given to make a strong typed object and fill it but you can also return a dynamic type.
This code works to explain:
private dynamic Get() => new { Name = "SomeName", Age = 31 };
private void TestGet()
{
var obj = Get();
var name = obj.Name;
var age = obj.Age;
}

Trying to create an Add extension method for an IDbSet

I'm trying to create an Extension method for my DBContext (db) and one of the IDbSets. I would like to be able to call the extension like this:
db.UploadedFile.AddFile
(
SessionUser.ProfileId,
model.UploadingFile.FileName,
serverPath,
model.ProjectSubmissionId
);
This seems to work, but I would like to later, after a db.SaveChanges(), get the Primary Key ID of the added value.
This is what I have so far:
public static class UploadedFileExtensions
{
public static bool AddFile
(
this IDbSet<UploadedFile> files,
Guid uploadedByProfileId,
string fileName,
string filePath,
Guid? associatedWithId
)
{
var newFile = new UploadedFile
{
UploadedByProfileId = uploadedByProfileId,
FileName = fileName,
FilePath = filePath,
FileExtension = Path.GetExtension(fileName),
Submitted = DateTime.Now,
Modified = DateTime.Now,
IsActive = true
};
if (associatedWithId != null) newFile.AssociatedWithId = associatedWithId;
return files.AddFile(newFile);
//return true;
}
public static bool AddFile(this IDbSet<UploadedFile> files, UploadedFile file)
{
files.Add(file);
return true;
}
}
Depending on your how your db context code is setup, you may be able to do something like this:
private int GetMaxPrimaryKeyID()
{
return MyRepository.Items.Select(o => o.ID).DefaultIfEmpty().Max();
}
Where Items is:
IEnumerable<T> Items { get; }
Assuming this is an identity ID, I don't think you can get it before it is committed to the database.
I would wrap or inherit from the context (unit of work pattern is good for this) and override the SaveChanges method with your own.
As soon as the data is committed you can see what ID value has been assigned.
Something like:
public override void SaveChanges()
{
UploadedFile[] newFiles = base.ChangeTracker.Entries<UploadedFile>()
.Where(x => x.State == EntityState.Added)
.Select(x => x.Entity)
.ToArray()
base.SaveChanges();
//id values should be available to you here in the newFiles array
}
EDIT:
On reflection, there isn't actually any need for you to override anything here. You could just use something like the above code example with your context object directly. All you really need to do is use the ChangeTracker property to inspect your entities after the commit (but before you dispose the context).

Find a generic DbSet in a DbContext dynamically

I know this question has already been asked but I couldn't find an answer that satisfied me. What I am trying to do is to retrieve a particular DbSet<T> based on its type's name.
I have the following :
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyDllAssemblyName")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyCallingAssemblyName")]
class MyDbContext : DbContext {
public DbSet<ModelA> A { get; set; }
public DbSet<ModelB> B { get; set; }
public dynamic GetByName_SwitchTest(string name) {
switch (name) {
case "A": return A;
case "B": return B;
}
}
public dynamic GetByName_ReflectionTest(string fullname)
{
Type targetType = Type.GetType(fullname);
var model = GetType()
.GetRuntimeProperties()
.Where(o =>
o.PropertyType.IsGenericType &&
o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
o.PropertyType.GenericTypeArguments.Contains(targetType))
.FirstOrDefault();
if (null != model)
return model.GetValue(this);
return null;
}
}
I have no trouble getting the type itself whether it is via a simple switch or reflection. I need however to return the type as a dynamic since I do not know what DbSet type it will be.
Then somewhere else in the same assembly, I use it this way :
// MyDbContext MyDbContextInstance..
var model = MyDbContextInstance.GetByName_SwitchTest("A");
var record1 = model.FirstOrDefault(); // It crashes here with RunTimeBinderException
At this point model contains an instance of a InternalDbSet<ModelA> type. From there, any use I do with the model object I get a RunTimeBinderException :
'Microsoft.Data.Entity.Internal.InternalDbSet' does not contain a definition for 'FirstOrDefault'
Investigating on the web, I found a blog post explaining that (dixit his blog) :
the reason the call to FirstOrDefault() fails is that the type
information of model is not available at runtime. The reason it's not
available is because anonymous types are not public. When the method
is returning an instance of that anonymous type, it's returning a
System.Object which references an instance of an anonymous type - a
type whose info isn't available to the main program.
And then he points that a solution :
The solution is actually quite simple. All we have to do is open up
AssemplyInfo.cs of the ClassLibrary1 project and add the following
line to it: [assembly:InternalsVisibleTo("assembly-name")]
I did try this solution on my code but it doesn't work. For info I have an asp.net 5 solution with two assemblies running on dnx dotnet46. An app and a dll containing all my models and DbContext. All the concerned calls I do are located on the dll though.
Does this solution have any chance to work ?
Am I missing something ?
Any pointers would be greatly appreciated ?
Thanks in advance
[EDIT]
I have tried to return IQueryable<dynamic> rather than dynamic and I could do the basic query model.FirstOrDefault(); but above all I'd like to be able to filter on a field too :
var record = model.FirstOrDefault(item => item.MyProperty == true);
So how did I do it when I am not aware of <T> during compile time.
First need to get the type as DbContext.Set method returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store.
public virtual DbSet Set(Type entityType)
Note here argument is the type of entity for which a set should be returned.And set for the given entity type is the return value.
var type = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(t => t.Name == <Pass your table name>);
now once I have this type
if(type != null)
{
DbSet context = context.Set(type);
}
Or a one liner would be
DbSet mySet = context.Set(Type.GetType("<Your Entity Name>"));
*Disclaimer: This response doesn't give a stricto sensu answer to my question. It is rather a different approach to resolve my own problem. I am aware this is a specific example for a given situation that will not work for everyone. I am posting this approach in the hope it helps someone but will not mark it as the answer as I am still hoping for a real solution.
To start with, let's accept the fact that the only useful information we can get out of the current code is whether a record exists or not.. Any attempt of a dynamic queries after that would give the RuntimeBinderException.
Then let's continue with another fact; DbContext.Add(object) and DbContext.Update(object) are not template based so we can use them to save our models ( Instead of db.A.Add() or db.A.Update() )
In my own situation, no more is required to work out a procedure
Define models a little differently
To start with, I need a field that is retrievable across all my models which should obviously be a way to identify a unique record.
// IModel give me a reliable common field to all my models ( Fits my DB design maybe not yours though )
interface IModel { Guid Id { get; set; } }
// ModelA inherit IModel so that I always have access to an 'Id'
class ModelA : IModel {
public Guid Id { get; set; }
public int OtherField { get; set; }
}
// ModelB inherit IModel so that I always have access to an 'Id'
class ModelB : IModel {
public Guid Id { get; set; }
public string WhateverOtherField { get; set; }
}
Re-purpose the dynamic queries a bit to do something we know works
I haven't found a way to do smart query dynamically, so instead I know I can reliably identify a record and know if it exists or not.
class MyDbContext : DbContext {
public DbSet<ModelA> A { get; set; }
public DbSet<ModelB> B { get; set; }
// In my case, this method help me to know the next action I need to do
// The switch/case option is not pretty but might have better performance
// than Reflection. Anyhow, this is one's choice.
public bool HasRecord_SwitchTest(string name) {
switch (name) {
case "A": return A.AsNoTracking().Any(o => o.Id == id);
case "B": return B.AsNoTracking().Any(o => o.Id == id);
}
return false;
}
// In my case, this method help me to know the next action I need to do
public bool HasRecord_ReflectionTest(string fullname)
{
Type targetType = Type.GetType(fullname);
var model = GetType()
.GetRuntimeProperties()
.Where(o =>
o.PropertyType.IsGenericType &&
o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
o.PropertyType.GenericTypeArguments.Contains(targetType))
.FirstOrDefault();
if (null != model)
return (bool)model.GetValue(this).AsNoTracking().Any(o => o.Id == id);
return false;
}
// Update and save immediately - simplified for example
public async Task<bool> UpdateDynamic(object content)
{
EntityEntry entry = Update(content, GraphBehavior.SingleObject);
return 1 == await SaveChangesAsync(true);
}
// Insert and save immediately - simplified for example
public async Task<bool> InsertDynamic(object content)
{
EntityEntry entry = Add(content, GraphBehavior.SingleObject);
return 1 == await SaveChangesAsync(true);
}
}
A little bit of plumbing to give a sense to my situation
Next, what I needed to do with that dynamic queries was a way to replicate data from a server down to my client. ( I have omitted a big chunk of the architecture to simplify this example )
class ReplicationItem
{
public ReplicationAction Action { get; set; } // = Create, Update, Delete
public string ModelName { get; set; } // Model name
public Guid Id { get; set; } // Unique identified across whole platform
}
Connecting the bits.
Now, here's the routine that connects the bits
public async void ProcessReplicationItem(ReplicationItem replicationItem)
{
using (var db = new MyDbContext())
{
// Custom method that attempts to get remote value by Model Name and Id
// This is where I get the strongly typed object
var remoteRecord = await TryGetAsync(replicationItem.ModelName, replicationItem.Id);
bool hasRemoteRecord = remoteRecord.Content != null;
// Get to know if a local copy of this record exists.
bool hasLocalRecord = db.HasRecord_ReflectionTest(replicationItem.ModelName, replicationItem.Id);
// Ensure response is valid whether it is a successful get or error is meaningful ( ie. NotFound )
if (remoteRecord.Success || remoteRecord.ResponseCode == System.Net.HttpStatusCode.NotFound)
{
switch (replicationItem.Action)
{
case ReplicationAction.Create:
{
if (hasRemoteRecord)
{
if (hasLocalRecord)
await db.UpdateDynamic(remoteRecord.Content);
else
await db.InsertDynamic(remoteRecord.Content);
}
// else - Do nothing
break;
}
case ReplicationAction.Update:
[etc...]
}
}
}
}
// Get record from server and with 'response.Content.ReadAsAsync' type it
// already to the appropriately
public static async Task<Response> TryGetAsync(ReplicationItem item)
{
if (string.IsNullOrWhiteSpace(item.ModelName))
{
throw new ArgumentException("Missing a model name", nameof(item));
}
if (item.Id == Guid.Empty)
{
throw new ArgumentException("Missing a primary key", nameof(item));
}
// This black box, just extrapolate a uri based on model name and id
// typically "api/ModelA/{the-guid}"
string uri = GetPathFromMessage(item);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:12345");
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
return new Response()
{
Content = await response.Content.ReadAsAsync(Type.GetType(item.ModelName)),
Success = true,
ResponseCode = response.StatusCode
};
}
else
{
return new Response()
{
Success = false,
ResponseCode = response.StatusCode
};
}
}
}
public class Response
{
public object Content { get; set; }
public bool Success { get; set; }
public HttpStatusCode ResponseCode { get; set; }
}
ps: I am still interested in a real answer, so please keep posting for other answer if you have a real one to share.
You could use this to get the DBSet for a specific type:
public object GetByType(DbContextcontext, Type type) {
var methode = _context.GetType().GetMethod("Set", types: Type.EmptyTypes);
if (methode == null) {
return null;
}
return methode.MakeGenericMethod(type).Invoke(_context, null);
}

Query LINQ - Could not find an implementation of the query pattern

I created a table in my designer view with 4 columns. I'd like to add others columns manually (because it'll be add according the data stored in DB).
I would like to create the link between the data from DB and the table so I did this :
private void LoadSiteDataSource()
{
CVaultDataSource.Rows.Clear();
if (this.Site != null)
{
var sitesDB = from sites in this.Site
select sites.KEY;
foreach (var item in sitesDB)
{
CVaultDataSource.Rows.Add(item);
}
}
}
But I have this error :
Could not find an implementation of the query pattern for source type System.ComponentModel.ISite. 'Select not found'.
I've look the differents topics about this error but I could not find something to fix it.
I'm already using this function which works :
private void LoadDataSource()
{
CVaultDataSource.Rows.Clear();
if (this.BaseFilters != null)
{
var filters = from filterBase in this.BaseFilters
orderby filterBase.EVPTCODE
select new object[] { filterBase.CVAULTCODE, filterBase.EVPTCODE, filterBase.EVPTDESIGNATION, filterBase.DURATION, filterBase.ETDTIME };
foreach (var item in filters)
{
CVaultDataSource.Rows.Add(item);
}
}
}
Does someone know why it does not work ?
I just forget to declare this :
public List<SITE> Sites { get; private set; }
That's why it did not work.

Categories