LINQ TO XML Parse RSS Feed - rss

I'm trying to parse an RSS feed using LINQ to Xml
This is the rss feed:
http://www.surfersvillage.com/rss/rss.xml
My code is as follows to try and parse
List<RSS> results = null;
XNamespace ns = "http://purl.org/rss/1.0/";
XNamespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
XDocument xdoc = XDocument.Load("http://www.surfersvillage.com/rss/rss.xml");
results = (from feed in xdoc.Descendants(rdf + "item")
orderby int.Parse(feed.Element("guid").Value) descending
let desc = feed.Element("description").Value
select new RSS
{
Title = feed.Element("title").Value,
Description = desc,
Link = feed.Element("link").Value
}).Take(10).ToList();
To test the code I've put a breakpoint in on the first line of the Linq query and tested it in the intermediate window with the following:
xdoc.Element(ns + "channel");
This works and returns an object as expect
i type in:
xdoc.Element(ns + "item");
the above worked and returned a single object but I'm looking for all the items
so i typed in..
xdoc.Elements(ns + "item");
This return nothing even though there are over 10 items, the decendants method doesnt work either and also returned null.
Could anyone give me a few pointers to where I'm going wrong? I've tried substituting the rdf in front as well for the namespace.
Thanks

You are referencing the wrong namespace. All the elements are using the default namespace rather than the rdf, so you code should be as follow:
List<RSS> results = null;
XNamespace ns = "http://purl.org/rss/1.0/";
XDocument xdoc = XDocument.Load("http://www.surfersvillage.com/rss/rss.xml");
results = (from feed in xdoc.Descendants(ns + "item")
orderby int.Parse(feed.Element(ns + "guid").Value) descending
let desc = feed.Element(ns + "description").Value
select new RSS
{
Title = feed.Element(ns + "title").Value,
Description = desc,
Link = feed.Element(ns + "link").Value
}).Take(10).ToList();

Related

Linq to dataset, Query optimization

I have following linq queries:
var itembind = (from q in dsSerach.Tables[0].AsEnumerable()
select new
{
PatternID = q.Field<int>("PatternID"),
PatternName = q.Field<string>("PatternName") + " " + q.Field<string>("ColorID") + q.Field<string>("BookID"),
ColorID = q.Field<string>("ColorID"),
BookID = q.Field<string>("BookID"),
CoverImage = (from img1 in objJFEntities.ProductImages.ToList()
where img1.PatternName.ToLower() == q.Field<string>("PatternName").ToLower()
select new CoverImage
{
URL = "Images/MediumPatternImages/" +
q.Field<string>("PatternName") + "_" + q.Field<string>("ColorID") + q.Field<string>("BookID") + q.Field<string>("ImageExtension"),
ID = q.Field<int>("ProductImageID")
}).FirstOrDefault(),
TotalCount = q.Field<int>("TotalCount")
}).Distinct();
var patterns = (from r in itembind
group r by new { r.PatternID, r.ColorID } into g
select new SearchPattern
{
PatternID = g.Key.PatternID,
PatternName = string.Join(",", g.OrderBy(s => s.ColorID).OrderBy(s => s.BookID)
.Select(s => String.Format("<a href='{0:s}' title='{1:s}'>{2:s}</a><br />",
new object[] { String.Format("Product.aspx?ID={0}&img={1}", g.Key.PatternID, s.CoverImage.ID), s.PatternName, s.PatternName })).FirstOrDefault()),
CoverImage = g.Count() > 1 ? (from img1 in objJFEntities.ProductImages.ToList()
where img1.ProductImageID == g.Select(i => i.CoverImage.ID).FirstOrDefault() && img1.ColorID.ToString() == g.Key.ColorID
select new CoverImage
{
URL = "Images/MediumPatternImages/" +
img1.PatternName + "_" + img1.ColorID + img1.BookID + img1.ImageExtension,
ID = img1.ProductImageID
}).FirstOrDefault() : g.Select(i => i.CoverImage).FirstOrDefault()
}).ToList();
these queries are taking more then 1 minute to execute for the 1000 records only.
The dsSearch is a dataset filled with records returned from my procedure in SQL.
Am using entity framework. The site is deployed with IIS7.0. The SQL server 2008 is in use.
I got "Error Message:Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." ,
"Cannot open database "DB" requested by the login. The login failed." & "The underlying provider failed on Open." kind of error very frequently site.
Please tell me how to optimize such a query.
EDIT:
Here is the procedure
http://pastie.org/7160934
In the first query you are doing a objJFEntities.ProductImages.ToList() , with the ToList() call you are fetching every entry from the database, and later filter the results in memory.
Rolfvm is correct in pointing out that objJFEntities.ProductImages causes the problem, but the analysis is a bit different. You fetch the entire ProductImages table into memory for each iteration of the query when you enumerate over it. So one optimization would be to fetch the images first in a collection and use that collection in the query statement
var localImages = objJFEntities.ProductImages.ToList();
...
CoverImage = (from img1 in localImages....
But then, your query seems to do far too much. You build the first part itembind without executing it. Then you build the second part (var patterns = (from r in itembind) and execute it by ToList(). But in the second part you never use the CoverImage from the first part. So creating these is a waste of resources. (Or you skimmed the code, hiding another use of the first part).

How to Advance filter for category and author in Smartsearch in kentico

I have created basic search and uses the SearchHelper to get smart search results based on the search paramaters.
Now creating the Advance search based on Category , Author etc but did not find the way to filter the result based on these condition.
I am looking for a way to display the results using the dataset that
// Prepare parameters
SearchParameters parameters = new SearchParameters()
{
SearchFor = searchText,
SearchSort = SearchHelper.GetSort(srt),
Path = path,
ClassNames = DocumentTypes,
CurrentCulture = culture,
DefaultCulture = defaultCulture,
CombineWithDefaultCulture = CombineWithDefaultCulture,
CheckPermissions = CheckPermissions,
SearchInAttachments = SearchInAttachments,
User = (UserInfo)CMSContext.CurrentUser,
SearchIndexes = Indexes,
StartingPosition = startPosition,
DisplayResults = displayResults,
NumberOfProcessedResults = numberOfProceeded,
NumberOfResults = 0,
AttachmentWhere = AttachmentsWhere,
AttachmentOrderBy = AttachmentsOrderBy,
BlockFieldOnlySearch = BlockFieldOnlySearch,
};
// Search
DataSet results = SearchHelper.Search(parameters);
The easiest way is to use the method:
SearchHelper.CombineSearchCondition()
The first parameter is the searchText, with the search terms you probably already have.
The second parameter is searchConditions, which can be formatted as per https://docs.kentico.com/k10/configuring-kentico/setting-up-search-on-your-website/smart-search-syntax
Alternatively you could just append your search conditions to your search text manually, separating each term with a space.
Remember that to filter based on any field they need to be selected as searchable in the SiteManager->Development->DocumentTypes->DocumentType->Search Tab.

How do I pass in feed credentials to XDocument that allows Linq to XML to work

I can take the results of my variable xmlDoc and save it to an xml document (on disk) and the query returns results; however, when I run it live (with the code below) the query results are null.
Why is my query not working against the xmlDoc?? See screen shot below for the debug output 'xmlDoc.Root'.
There must be a cleaner way to create the XDocument??
System.Net.WebClient wc = new System.Net.WebClient();
wc.Credentials = new System.Net.NetworkCredential("bagee18#gmail.com", "my_password");
XDocument xmlDoc = XDocument.Parse(wc.DownloadString(new Uri("https://mail.google.com/mail/feed/atom")), LoadOptions.None);
var q = (from c in xmlDoc.Descendants("entry")
select new
{
name = c.Element("title").Value,
url = c.Element("link").Attribute("href").Value,
email = c.Element("author").Element("email").Value
}).ToList();
q.Dump();
xmlDoc.Root:
.
Take the namespace into account:
XNamespace df = xmlDoc.Root.Name.Namespace;
var q = (from c in xmlDoc.Descendants(df + "entry")
select new
{
name = c.Element(df + "title").Value,
url = c.Element(df + "link").Attribute("href").Value,
email = c.Element(df + "author").Element(df + "email").Value
}).ToList();

ado.net query removes file exention when adding string filename to the database

I am using the code below for saving uploaded picture and makigna thumbnail but it saves a filename without the extension to the database, therefore, I get broken links. How can I stop a strongly typed dataset and dataadapter to stop removing the file extension? my nvarchar field has nvarchar(max) so problem is not string length.
I realized my problem was the maxsize in the dataset column, not sql statement parameter, so I fixed it. You may vote to close on this question.
hasTableAdapters.has_actorTableAdapter adp1 = new hasTableAdapters.has_actorTableAdapter();
if (Convert.ToInt16(adp1.UsernameExists(username.Text)) == 0)
{
adp1.Register(username.Text, password.Text,
ishairdresser.Checked, city.Text, address.Text);
string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName;
string originalrelative = "\\pictures\\" + actorimage.FileName;
actorimage.SaveAs(originalfilename);
string thumbfilename = Server.MapPath(" ") + "\\pictures\\t_" + actorimage.PostedFile.FileName;
string thumbrelative = "\\pictures\\t_" + actorimage.FileName;
Bitmap original = new Bitmap(originalfilename);
Bitmap thumb=(Bitmap)original.GetThumbnailImage(100, 100,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
thumb=(Bitmap)original.Clone(
new Rectangle(new Point(original.Width/2,original.Height/2), new Size(100,100)),
System.Drawing.Imaging.PixelFormat.DontCare);
/*
bmpImage.Clone(cropArea,bmpImage.PixelFormat);
*/
thumb.Save(thumbfilename);
adp1.UpdatePicture(originalrelative, thumbrelative, username.Text);
LoginActor();
Response.Redirect("Default.aspx");
}
}
Looks like the problem is you are using HttpPostedFile.FileName property, which returns fully-qualified file name on the client. So, this code string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName; generates something like this:
c:\inetpub\pictures\c:\Users\Username\Pictures\image1.jpg
Use FileUpload.FileName property everywhere and you will probably get what you want.
Use this to get Image or file extension :
string Extension = System.IO.Path.GetExtension(FileUpload.FileName);

Linq To Sql Get data into Label

I have a label to show BookName. I get it from table which name tblBooks. I don't know how to show Book Name into the label.
var query = from b in dc.tblBooks.Where(b=>b.BookID == 'B01') select b;
Can you help me know.
Your query as written will return a collection of books—IQueryable<Book>. If you're sure there will only be one result in this query, you can call SingleOrDefault, which will execute the query immediately and give you the actual book.
var Book = dc.tblBooks.Where(b => b.BookID == 'B01').SingleOrDefault();
if (Book != null)
myLabel.Text = Book.BookName;
Or you can simply say:
var Book = dc.tblBooks.SingleOrDefault(b => b.BookID == 'B01');
Which does the same thing.
If you're 110% sure there will always be a result, and you don't want to check for null, then you can use Single, which will do the same thing, except throw an exception if no results are found, where SingleOrDefault simple returns null.
var Book = dc.tblBooks.Single(b=>b.BookID == 'B01');
myLabel.Text = Book.BookName;
Try:
label.Text = query.FirstOrDefault().BookName;

Resources