put LINQ code in sitecore code - linq

I would to get "comment" by article ID . and i only can to get all comment in all article.
my plan is make LINQ code in my code
please check my code
var childrenss = new List<Sitecore.Data.Items.Item>();
foreach (var child in item.GetChildren())
{
childrenss.Add((Sitecore.Data.Items.Item)child);
}
any advice is appreciated. Thanks.

Well it looks like you should be able to use:
using System.Linq;
...
var children = item.GetChildren().ToList();

Ok I'm going to make a lot of assumptions here so if any of these are false and you need an explanation regarding any of the following let me know.
First of all I'm assuming your data in sitecore looks like this:
Video Item
Comment 1
Comment 2
Comment 3
Video Item 2
Comment 4
Comment 5
I also assume that you created a Sublayout that is meant to show the comments and that the Datasource of that Sublayout is a Video Item. (Incase this is not true you should consider it, integration of Sitecore DMS will later then be a lot easier)
In that case in your code behind of your sublayout there is no need to use any LINQ. You can simply use the following code:
public void Load_Page(object sender, EventArgs e)
{
Sublayout sublayout = Parent as Sublayout;
string datasource = sublayout.Datasource; // Contains Item GUID as string (if not using queries)
Item datasourceItem = Sitecore.Context.Database.GetItem(new ID(datasource));
Repeater.Datasource = datasourceItem.GetChildren();
Repeater.Databind();
}
So as you can see there's little to no reason at all to use any LINQ. For the sake of testing and argument you could demand that the Comment items are retrieved by using the Sitecore Index. To do that you can use the code from your other question.

Related

Using Parameters in LINQ

net. I have a doubt. How do we introduce user defined variables as parameters in where clause of a LINQ query. I am querying an XML file. Here is my code
XElement books = XElement.Load(#"Friends.xml");
var titles =
from book in books.Elements("Friend")
where (string)book.Element("Date") == "27" && (string)book.Element("Month") == "05"
select book.Element("Name");
foreach (var title in titles)
Console.WriteLine(title.Value);
Instead of harcoding values 27 and 05, I want to use variables instead.How to use them?
Sorry for the dumb question, I misunderstood the problem. Actually I am blocking certain dates in a calendar. Now using the
private void calendar1_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{....}
works only for non blocked dates. Since a particular day I tried with the variable was a blocked one, it wasn't working. Now please suggest me a solution for this. All I need is to click on a date(blocked or non blocked) and I have to run a event. Which event should I use??
use a simply variable:
XElement books = XElement.Load(#"Friends.xml");
string yourDate = "27";
string yourMonth = "05";
var titles =
from book in books.Elements("Friend")
where (string)book.Element("Date") == yourDate && (string)book.Element("Month") == yourMonth
select book.Element("Name");
foreach (var title in titles)
Console.WriteLine(title.Value);
And so on. Of course, use good names that are readable according your code and system
In addition, I think you could define a class of book with appropriate properties as XML tag. For example :
class Book {
string Date {...} //
}
It's could be quite easy when reading XML file. Moreover, it could be nice if you build your own tree data structures executing XML file.

How can I use set operations to delete objects in an entitycollection that match a collection of view models?

Here is a very basic example of what I want to do. The code I have come up with seems quite verbose... ie looping through the collection, etc.
I am using a Telerik MVC grid that posts back a collection of deleted, inserted and updated ViewModels. The view models are similar but not exactly the same as the entity.
For example... I have:
Order.Lines. Lines is an entity collection (navigation property) containing OrderDetail records. In the update action of my controller using the I have a List names DeletedLines pulled from the POST data. I also have queried the database and have the Order entity including the Lines collection.
Now I basically want to tell it to delete all the OrderDetails in the Lines EntityCollection.
The way I have done it is something like:
foreach (var line in DeletedLines) {
db.DeleteObject(Order.Lines.Where(l => l.Key == line.Key).SingleOrDefault())
}
I was hoping there was a way that I could use .Interset() to get a collection of entities to delete and pass that to DeleteObject.. however, DeleteObject seems to only accept a single entity rather than a collection.
Perhaps the above is good enough.. but it seemed like there should be an easier method.
Thanks,
BOb
Are the items in DeletedLines attached to the context? If so, what about this?
foreach (var line in DeletedLines) db.DeleteObject(line);
Response to comment #1
Ok, I see now. You can make your code a bit shorter, but not much:
foreach (var line in DeletedLines) {
db.DeleteObject(Order.Lines.SingleOrDefault(l => l.Key == line.Key))
}
I'm not sure if DeleteObject will throw an exception when you pass it null. If it does, you may be even better off using Single, as long as you're sure the item is in there:
foreach (var line in DeletedLines) {
db.DeleteObject(Order.Lines.Single(l => l.Key == line.Key))
}
If you don't want to re-query the database and either already have the mapping table PK values (or can include them in the client call), you could use one of Alex James's tips for deleting without first retrieving:
http://blogs.msdn.com/b/alexj/archive/2009/03/27/tip-9-deleting-an-object-without-retrieving-it.aspx

ABCpdf Table Help

First time poster so please bear with me. Basically I have a pdf document that I am creating on the fly using ABCpdf (via C# project) however the table rows seem to be rendering on top of each other. I have looked at all the documentation etc and searched for an answer but have not found anything relating to this.
I referred to the examples on creating tables which got me to the point I am at now but I cannot understand what is causing this issue. Below is an example of how I am constructing my table. Any help offered would be greatly appreciated. I have created a wrapper for ABCpdf to make it quicker and more code efficient to use but cannot see this causing the issue as it simply calls the same code as it would if I wrote it all out line by line.
PdfTable pdfTable = new PdfTable(_abcPdfWrapper.PdfDocument, 5, 3) {HorizontalAlignment = 1};
pdfTable.NextRow();
pdfTable.NextCell();
pdfTable.AddText(firstStageReference);
pdfTable.NextCell();
pdfTable.AddText(String.Format("{0:#,0.000}", materialWeight) + " Kg");
pdfTable.NextRow();
pdfTable.AddText(weighDepartmentMaterial.sMaterialCode ?? String.Empty);
pdfTable.NextCell();
pdfTable.AddText(weighDepartmentMaterial.sMaterialName ?? String.Empty);
pdfTable.NextCell();
pdfTable.AddText(String.Format("{0:#,0.000}", materialWeight) + " Kg");
pdfTable.NextCell();
pdfTable.AddText(weighDepartmentMaterial.Scale ?? String.Empty);
pdfTable.NextCell();
pdfTable.AddText(weighDepartmentMaterial.AddGroup ?? String.Empty);
There is other code in between these lines but they bear no significance to the construction of the table other than a loop in which the lines from number 2 down are contained to loop through a series of raw materials and create a row for each.
I solved this issue in the end by simply adding these two functions into my wrapper class and then calling them before and after using the table object.
public void PdfTableBegin()
{
PdfDocument.TopDown = false;
}
public void PdfTableEnd()
{
PdfDocument.TopDown = true;
}

Sorting an observable collection with linq

I have an observable collection and I sort it using linq. Everything is great, but the problem I have is how do I sort the actual observable collection? Instead I just end up with some IEnumerable thing and I end up clearing the collection and adding the stuff back in. This can't be good for performance. Does anyone know of a better way to do this?
If you are using Silverlight 3.0, then using CollectionViewSource is the cleanest way. Refer below example: (it can be done via xaml as well)
ObservableCollection<DateTime> ecAll = new ObservableCollection<DateTime>();
CollectionViewSource sortedcvs = new CollectionViewSource();
sortedcvs.SortDescriptions.Add(new System.ComponentModel.SortDescription("Date",
System.ComponentModel.ListSortDirection.Ascending));
sortedcvs.Source = ecAll;
ListBoxContainer.DataContext = sortedcvs;
And in corresponding xaml set
ItemsSource="{Binding}"
for the ListBox or any ItemsControl derived control
Since the collection doesn't provide any Sort mechanism, this is probably the most practical option. You could implement a sort manually using Move etc, but it will probably be slower than doing in this way.
var arr = list.OrderBy(x => x.SomeProp).ToArray();
list.Clear();
foreach (var item in arr) {
list.Add(item);
}
Additionally, you might consider unbinding any UI elements while sorting (via either approach) you only pay to re-bind once:
Interestingly, if this was BindingList<T>, you could use RaiseListChangedEvents to minimise the number of notifications:
var arr = list.OrderBy(x => x).ToArray();
bool oldRaise = list.RaiseListChangedEvents;
list.RaiseListChangedEvents = false;
try {
list.Clear();
foreach (var item in arr) {
list.Add(item);
}
} finally {
list.RaiseListChangedEvents = oldRaise;
if (oldRaise) list.ResetBindings();
}
Note that in Linq, you are given an IEnumerable from your query, and that query has not executed yet. Therefore, the following code only runs the query once, to add it to an ObservableCollection:
var query = from x in Data
where x.Tag == "Something"
select x;
foreach(var item in query)
MyObservableCollection.Add(item);
Take a look at the "OrderBy" extension on IEnumerable:
foreach(var item in query.OrderBy(x => x.Name))
MyObservableCollection.Add(item);
ObservableCollections aren't designed to be sortable. List is sortable, and that's the underlying mechanism used by the answer referencing List.Sort(), but ObservableCollection isn't derived from List so you're out of luck there. Imo, the "right" solution is not to try to sort the ObservableCollection, but to implement ICollectionView and bind an instance of that to your control. That interface adds methods for sorting and has the additional benefit that its recognized by Silverlight controls (well, the ones that support it anyway such as DataGrid) so your sorting could be utilized directly from the UI layer. This question might be helpful:
Silverlight and icollectionview
i followed the link mentioned in this post http://mokosh.co.uk/post/2009/08/04/how-to-sort-observablecollection/comment-page-1/#comment-75
but having issues getting it to work in Silverlight
I created a property public SortableObservableCollection Terms
When I call Terms.Sort(new TermComparer()) the records are still display unsorted on the UI
could some suggest what could be going wrong. thanks
I found this on CodePlex:
Sorted Collections
Haven't used it yet though.
Rick

ADO.NET Data Services, LINQ

I have C# code to populate a dropdown list in Silverlight which works fine except when there are duplicates. I think because IEnumerable<Insurance.Claims> is a collection, it filters out duplicates. How would I code my LINQ query to accept duplicates?
My Sample Data looks like:
Code => CodeName
FGI Field General Initiative
SRI Static Resource Initiative
JFI Joint Field Initiative - This is "overwritten" in results
JFI Joint Friend Initiative
IEnumerable<Insurance.Claims> results;
// ADO.NET Data Service
var claim = (from c in DataEntities.Claims.Expand("Claimants").Expand("Policies")
where c.Claim_Number == claimNumber
select c);
DataServiceQuery<Insurance.Claims> dataServiceQuery =
claim as DataServiceQuery<Insurance.Claims>;
dataServiceQuery.BeginExecute((asyncResult) =>
{
results = dataServiceQuery.EndExecute(asyncResult);
if (results == null)
{
// Error
}
else
{
// Code to populate Silverlight form
}
});
(Not sure if you're still struggling with this but anyway...)
I'm pretty sure it's not the IEnumerable interface but the actual drop down that is causing this behaviour. The code is being used as the key, and so obviously each time the same code is encountered, the item is being overwritten.
I don't think you can override this unless you change the code, or use another identifier as the key field in the dropdown.
You may want to add a try-catch block around dataServiceQuery.EndExecute(asyncResult) to properly handle errors.

Resources