Retrieving a list of Tridion 2009 components with a specific value and schema without using search - tridion

I would like to create a .NET page residing on the CMS server that shows all components that are based on a specific Schema(tcm:3-3-8) and from a specific Publication(tcm:0-3-1) including BluePrinted and Localized items, but only if they have the value "http://www.google.com" for the field "URL" in that Schema.
Is this possible, without using the search service as this is rather slow and unreliable?

Your search might be slow because of not indexing the search collection.
You should do indexing the search collection on regular intervals for better and fast results.

That's an expensive operation to do because of the cost of opening each individual component to check the value of a field, but certainly do-able.
Get the schema object
Get a list of components that use this schema (WhereUsed on the schema with filter on ItemType = component)
Open each component and check the value for the field(s), add to a List<Component> if it matches
Display list (possibly using a ASP.NET GridView)

I have not had any chance to test it, but something like this
Common common = new Common();
TDSE tdse = new TDSE();
ListRowFilter ComponentFilter = tdse.CreateListRowFilter();
Schema schema = (Schema)common.getObject("tcm:126-238630-8", ItemType.ItemTypeSchema);
ComponentFilter.SetCondition("ItemType", ItemType.ItemTypeComponent);
ComponentFilter.SetCondition("Recursive", true);
XDocument doc = common.ReadXML(schema.Info.GetListUsingItems(ListColumnFilter.XMLListID, ComponentFilter));
List<Component> MatchedComponents = new List<Component>();
XmlNamespaceManager NS = new XmlNamespaceManager(new NameTable());
NS.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
NS.AddNamespace("Content", "uuid:4432F3C3-9F3E-45E4-AE31-408C5C46E2BF");
foreach (XElement component in doc.XPathSelectElements("/tcm:ListUsingItems/tcm:Item", NS))
{
Component comp = common.getComponent(component.Attribute("ID").Value);
XDocument compDoc = common.ReadXML(comp.GetXML(XMLReadFilter.XMLReadData));
foreach (XElement compNode in compDoc.XPathSelectElements("/tcm:Component/tcm:Data/tcm:Content/Content:Content/Content:feederUrl", NS))
{
MatchedComponents.Add(comp);
}
}

Related

Handling reads of Cosmos DB container with multiple types?

I'd like to store several different object types in a single Cosmos DB container, as they are all logically grouped and make sense to read together by timestamp to avoid extra HTTP calls.
However, the Cosmos DB client API doesn't seem to provide an easy way of doing the reads with multiple types. The best solution I've found so far is to write your own CosmosSerializer and JsonConverter, but that feels clunky: https://thomaslevesque.com/2019/10/15/handling-type-hierarchies-in-cosmos-db-part-2/
Is there a more graceful way to read items of different types to a shared base class so I can cast them later, or do I have to take the hit?
Thanks!
The way I do this is to create the ItemQueryIterator and FeedResponse objects as dynamic and initially read them untyped so I can inspect a "type" property that tells me what type of object to deserialize into.
In this example I have a single container that contains both my customer data as well as all their sales orders. The code looks like this.
string sql = "SELECT * from c WHERE c.customerId = #customerId";
FeedIterator<dynamic> resultSet = container.GetItemQueryIterator<dynamic>(
new QueryDefinition(sql)
.WithParameter("#customerId", customerId),
requestOptions: new QueryRequestOptions
{
PartitionKey = new PartitionKey(customerId)
});
CustomerV4 customer = new CustomerV4();
List<SalesOrder> orders = new List<SalesOrder>();
while (resultSet.HasMoreResults)
{
//dynamic response. Deserialize into POCO's based upon "type" property
FeedResponse<dynamic> response = await resultSet.ReadNextAsync();
foreach (var item in response)
{
if (item.type == "customer")
{
customer = JsonConvert.DeserializeObject<CustomerV4>(item.ToString());
}
else if (item.type == "salesOrder")
{
orders.Add(JsonConvert.DeserializeObject<SalesOrder>(item.ToString()));
}
}
}
Update:
You do not have to use dynamic types if want to create a "base document" class and then derive from that. Deserialize into the documentBase class, then check the type property check which class to deserialize the payload into.
You can also extend this pattern when you evolve your data models over time with a docVersion property.

SQL Lite Xamarin : Query

I'm newbie in SQLite.
I would like to query my SQLite database to get multiple rows.
When I add a new item in my local database I call this method Add:
public bool Add<T>(string key, T value)
{
return this.Insert(new SQliteCacheTable(key, this.GetBytes(value))) == 1;
}
_simpleCache.Add("favorite_1", data1);
_simpleCache.Add("favorite_2", data2);
_simpleCache.Add("favorite_3", data2);
Then,
I would like to retrieve from local database all entries where key starts with "favorite_"
to returns all objects in the database which are "favorite" objects.
I'm experienced in Linq, and I would like to do something like this:
IEnumerable<Element> = repository.Find((element) => element.Key.StartWith("favorite_"))
In the SQLiteConnection class there is a method like this:
SQLite.Net.SQLiteConnection.Find<T>(System.Linq.Expressions.Expression<System.Func<T,bool>>)
But I would like the same with in returns a collection IEnumerable<T>.
Can you help me please?
Thank you.
Jool
You have to build your query on the table itself, not the connection:
Assuming:
SQLiteConnection repository;
Then the code would look like:
var favorites = repository.Table<SQliteCacheTable>().Where(item => item.StartsWith("favorite_"));
The favorites variable is of type TableQuery<SQliteCacheTable> though, so it does not yet contain your data. The execution of the actual SQL query will be deferred until you try to access the results (by enumerating with foreach or converting to a list with ToList, for example).
To actually observe what's going on on the database, you can turn on tracing in sqlite-net, by setting repository.Trace = true on your SQLiteConnection object.
Finally, it's worth mentioning that you can also use the C# query syntax on TableQuery<T> objects, if your comfortable with it. So your query could become:
var favorites = from item in repository.Table<SQliteCacheTable>()
where item.StartsWith("favorite_")
select item;

NHibernate: adding calculated field to query results

I have inherited an ASP.NET website built on NHibernate, with which I have no experience. I need to add a calculated field based on a column in a related table to an existing query. In SQL, this would be done easily enough using a correlated subquery:
select
field1,
field2,
(select count(field3) from table2 where table2.table1ID = table1.ID) calc_field
from
table1
where
[criteria...]
Unfortunately, of course, I can't use SQL for this. So in reality, I have three related questions:
What is the best way to trace through the web of interfaces, base classes, etc used by NHibernate in order to pinpoint the object where I need to add the field?
Having located that object, what, if anything, has to be done besides adding a public property to the object corresponding to the new field?
Are there any NHibernate-specific considerations with regard to referencing a related object in a query?
Here is the existing code that performs the search:
public INHibernateQueryable<C> Search(ISearchQuery query, string sortField)
{
_session = GetSession();
var c = _session.Linq<C>();
c.Expand("IP");
c.Expand("LL");
c.Expand("LL.Address");
c.Expand("LL.Address.City");
c.Expand("LL.Address.City.State");
c.Expand("LL.Address.City.County");
c.Expand("CE");
c.Expand("IC");
c.Expand("AR");
c.Expand("ER");
c.Expand("Status");
var res = _SearchFilters
.Where(x => x.ShouldApply(query))
.Aggregate(c, (candidates, filter) => (INHibernateQueryable<C>) filter.Filter(candidates, query));
res = SortSearch(res, sortField);
return res;
}
I appreciate any advice from experienced Hibernators.
Thanks,
Mike
If you are only interested in returning a query containing a computed value, you can still call a stored procedure in NHibernate and map the results to a POCO in the same way as you map a table for CRUD operations; obviously read-only instead of updatable.
Have a look at the ISession.CreateSQLQuery method; I can post an example from one of my projects if you need one.

How to use SQL Server 2008 stored procedure in asp.net mvc

I have created a simple stored procedure in SQL Server 2008 as:
CREATE PROCEDURE viewPosts
AS
SELECT * FROM dbo.Post
Now, I have no idea how to use it in controller's action, I have a database object which is:
entities db = new entities();
Kindly tell me how to use stored procedure with this database object in Entity Framework.
For Details check this link:
http://www.entityframeworktutorial.net/data-read-using-stored-procedure.aspx
Hope this will help you.
See article about 30% in:
In the designer, right click on the entity and select Stored Procedure mapping.
Click and then click the drop down arrow that appears. This exposes the list of all Functions found in the DB metadata.
Select Procedure from the list. The designer will do its best job of matching the stored procedure’s parameters with the entity properties using the names. In this case, since all of the property names match the parameter names, it maps every one correctly so you don’t need to make any changes. Note: The designer is not able to automatically detect the name of the field being returned.
Under the Result Column Bindings section, click and enter variable name. The designer should automatically select the entity key property for this final mapping.
The following code is what I use to initialize the stored procedure, then obtain the result into variable returnedResult, which in this case is the record id of a newly created record.
SqlParameter paramResult = new SqlParameter("#Result", -1);
paramResult.Direction = System.Data.ParameterDirection.Output;
var addParameters = new List<SqlParameter>
{
new SqlParameter("#JobID", EvalModel.JobID),
new SqlParameter("#SafetyEvaluator", EvalModel.SafetyEvaluator),
new SqlParameter("#EvaluationGuid", EvalModel.EvaluationGuid),
new SqlParameter("#EvalType", EvalModel.EvalType),
new SqlParameter("#Completion", EvalModel.Completion),
new SqlParameter("#ManPower", EvalModel.ManPower),
new SqlParameter("#EDate", EvalModel.EDate),
new SqlParameter("#CreateDate", EvalModel.CreateDate),
new SqlParameter("#Deficiency", EvalModel.Deficiency.HasValue ? EvalModel.Deficiency.Value : 0),
new SqlParameter("#DeficiencyComment", EvalModel.DeficiencyComment != null ? EvalModel.DeficiencyComment : ""),
new SqlParameter("#Traffic", EvalModel.Traffic.HasValue ? EvalModel.Traffic.Value : 0),
paramResult
};
// Stored procedure name is AddEval
context.Database.ExecuteSqlCommand("AddEval #JobID, #SafetyEvaluator, #EvaluationGuid, #EvalType, #Completion, #ManPower, #EDate, #CreateDate, #Deficiency, #DeficiencyComment, #Traffic, #Result OUTPUT", addParameters.ToArray());
var returnedResult = paramResult.Value;
NewEvaluationID = Convert.ToInt32(returnedResult);

SDL Tridion GetListKeywords using Anquilla Framework

I'm writing a GUI extension and using the Anquilla framework to get a list of Keywords within a Category. I'm obtaining an XML document for the list of keywords then working with that document within my extension.
My problem is that the returned XML doesn't contain the Keyword's 'Description' value. I have the Title and Key etc.
My original code looks like this:
var category = $models.getItem("CATEGORYTCMID:);
var list = category.getListKeywords();
list.getXml();
A typical node returned is this:
<tcm:Item ID="tcm:4-1749-1024"
Type="1024" Title="rate_one" Lock="0" IsRoot="true"
Modified="2012-12-17T23:01:59" FromPub="010 Schema"
Key="rate_one_value" IsAbstract="false"
CategoryTitle="TagSelector"
CategoryID="tcm:4-469-512" Icon="T1024L0P0"
Allow="268560384" Deny="96" IsNew="false"
Managed="1024"/></tcm:ListKeywords>
So I've tried using a Filter to give me additional column information:
var filter = new Tridion.ContentManager.ListFilter();
filter.columns = Tridion.Constants.ColumnFilter.EXTENDED;
var list = category.getListKeywords(filter);
Unfortunately this only gives the additional XML attributes:
IsShared="true" IsLocalized="false"
I'd really like the description value to be part of this XML without having to create a Keyword object from the XML. Is such a thing possible?
cough any ideas? cough
I'm afraid you'll have to load the Keyword itself to get the Description.
It's not used in any lists, so it's not returned in the XML.
You could always create a List Extender to add this information to the list, but try to be smart about it since this extender will execute everytime a GetList is called.
Won't save you from having to open every keyword in the list, but you'll be doing it server-side (with Core Service/NetTcp for instance) which will probably be easier and faster than opening each keyword with Anguilla.
In this instance I only need the one keyword, so I simply get it from the CMS. Getting an object in Anguilla is a bit weird, here's the code:
In your main code area:
var selectedKy = $models.getItem("TcmUriOfKeywordHere");
if (selectedKy.isLoaded()) {
p.selectedKy = selectedKy;
this.onselectedKyLoaded();
} else {
$evt.addEventHandler(selectedKy, "load", this.onselectedKyLoaded);
selectedKy.load();
}
It's worth noting how I store the keyword in the properties of the item, so I can obtain it in the onselectedKyLoaded function
The function called once the item is loaded
ContentBloom.ExampleGuiExtension.prototype.onselectedKyLoaded = function (event) {
var p = this.properties;
var selectedDescription = p.selectedKy.getDescription();
// do what you need to do with the description :)
};
I resolved this, thanks to the answer here: https://stackoverflow.com/a/12805939/1221032 - Cheers Nuno :)

Resources