rss feed retrieval using LINQ - linq

I have a rss feed which is below format.
<response>
<results>
<game>
<image>
<icon_url>
<![CDATA[
http://-------------------
]]>
</icon_url>
<medium_url>
<![CDATA[
http://----
]]>
</medium_url>
</image>
</game>
</results>
</response>
Now, I want to retrieve the medium_url using LINQ.
var items = from item in rssFeed.
Elements("response").Elements("results").Elements("game")
select new
{
Image1 = item.Element("image").Element("medium_url").value
}
This doesn't seem to work.

You just need to make a small change:
var items = from item in rssFeed.
Elements("response").Elements("results").Elements("game")
select new
{
Image1 = (string)item.Element("image").Element("medium_url")
};
or
var items = from item in rssFeed.
Elements("response").Elements("results").Elements("game")
select new
{
Image1 = item.Element("image").Element("medium_url").Value
};

Related

Cannot save pdf file on my phone or bluestacks Xamarin.Forms

i'm trying to create a pdf using PdfSharpCore for Xamarin Forms but I've run into some issues.
private void CreatePdf(object sender)
{
PdfDocument pdf = new PdfDocument();
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
graph.DrawString("This is my first PDF document", font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string localFilename = "test.pdf";
string localPath = Path.Combine(documentsPath, localFilename);
MemoryStream stream = new MemoryStream();
pdf.Save(stream, false);
byte[] bytes = stream.ToArray();
File.WriteAllBytes(localPath, bytes);
}
This is my function that generate the pdf and save it but when I press the button that invoke it, nothing happens.
I've already add the the permissions on the AndroidManifest.xml file like this:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I've tried using a library called Xamarin.Forms.SaveOpenPDFPackage. With this library you can
save and open your brand new pdf by doing this:
await CrossXamarinFormsSaveOpenPDFPackage.Current.SaveAndView("myFile1.pdf", "application/pdf", stream, PDFOpenContext.InApp);
It half works: it opens my new pdf but it doesn't save it.
Do you have any tip?
You could try to use Syncfusion.Xamarin.PDF.
Install from NuGet package first.
Creating a PDF document with table:
//Create a new PDF document.
PdfDocument doc = new PdfDocument();
//Add a page.
PdfPage page = doc.Pages.Add();
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
//Add values to list
List<object> data = new List<object>();
Object row1 = new { ID = "E01", Name = "Clay" };
Object row2 = new { ID = "E02", Name = "Thomas" };
Object row3 = new { ID = "E03", Name = "Andrew" };
Object row4 = new { ID = "E04", Name = "Paul" };
Object row5 = new { ID = "E05", Name = "Gray" };
data.Add(row1);
data.Add(row2);
data.Add(row3);
data.Add(row4);
data.Add(row5);
//Add list to IEnumerable
IEnumerable<object> dataTable = data;
//Assign data source.
pdfGrid.DataSource = dataTable;
//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new PointF(10, 10));
//Save the PDF document to stream.
MemoryStream stream = new MemoryStream();
doc.Save(stream);
//Close the document.
doc.Close(true);
//Save the stream as a file in the device and invoke it for viewing
Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("Output.pdf", "application/pdf", stream);
For more details about the ISave, you could get the whole code from Syncfusion official document.

Filtered subgrid - createCallbackFunctionObject throwing indescript error

I am attempting to create a filtered N:N subgrid with the code from here:
This is a Dynamics 365 Online instance if that helps. The problem I am facing though is strange in that the lookup window comes up, filters perfectly, and allows me to choose items. But when I click "add" I get a general error message.
As far as I can tell everything in the code is fine but I am unclear as to how I should proceed to debug this. My initial thought is that I could start debugging in the crmWindow.Mscrm.Utilities.createCallbackFunctionObject function but I am unclear as to how to debug that function in the global.ashx file in an online environment. My thought is that within there I may be able to get an error I can use.
Any idea?
//filters an add existing lookup view (N:N)
function addExistingFromSubGridCustom(gridTypeCode, gridControl, crmWindow, fetch, layout, viewName) {
var viewId = {DB2C6D94-48F2-E711-A2B6-00155D045E00}; // a dummy view ID
var relName = gridControl.GetParameter(relName);
var roleOrd = gridControl.GetParameter(roleOrd);
//creates the custom view object
var customView = {
fetchXml: fetch,
id: viewId,
layoutXml: layout,
name: viewName,
recordType: gridTypeCode,
Type: 0
};
var parentObj = crmWindow.GetParentObject(null, 0);
var parameters = [gridTypeCode, , relName, roleOrd, parentObj];
var callbackRef = crmWindow.Mscrm.Utilities.createCallbackFunctionObject(locAssocObjAction, crmWindow, parameters, false);
crmWindow.LookupObjectsWithCallback(callbackRef, null, multi, gridTypeCode, 0, null, , null, null, null, null, null, null, viewId, [customView]);
}
function filterAddExistingContact(gridTypeCode, gridControl, primaryEntity) {
debugger;
var crmWindow = Xrm.Internal.isTurboForm() ? parent.window : window;
var lookup = new Array();
lookup = Xrm.Page.getAttribute(new_channel).getValue();
if (lookup != null) {
var name = lookup[0].name;
var id = lookup[0].id;
var entityType = lookup[0].entityType;
}
else
{
crmWindow.Mscrm.GridRibbonActions.addExistingFromSubGridAssociated(gridTypeCode, gridControl); //default button click function
return;
}
if (primaryEntity != nxt_callreport) {
crmWindow.Mscrm.GridRibbonActions.addExistingFromSubGridAssociated(gridTypeCode, gridControl); //default button click function
return;
//Mscrm.GridRibbonActions.addExistingFromSubGridAssociated(gridTypeCode, gridControl); //default button click function
//return;
}
//fetch to retrieve filtered data
var fetch = <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> +
<entity name="new_market"> +
<attribute name="new_marketid" /> +
<attribute name="new_name" /> +
<attribute name="createdon" /> +
<order attribute="new_name" descending="false" /> +
<filter type="and"> +
<condition attribute="new_channel" operator="eq" uiname=" + name + " uitype=" + entityType + " value=" + id + " /> +
</filter> +
</entity> +
</fetch>;
//columns to display in the custom view (make sure to include these in the fetch query)
var layout = <grid name="resultset" object="1" jump="new_name" select="1" icon="1" preview="1"> +
<row name="result" id="new_name"> +
<cell name="new_name" width="300" /> +
</row> +
</grid>;
addExistingFromSubGridCustom(gridTypeCode, gridControl, crmWindow, fetch, layout, Filtered Markets);
}
Update this line:
var crmWindow = Xrm.Internal.isTurboForm() ? parent.window : window;
To
var crmWindow = Xrm.Internal.isTurboForm() ? top.parent.window : top.window;
and update:
crmWindow.Mscrm.Utilities.createCallbackFunctionObject(

How can I use condition and filters in LinkEntity?

I want to create a QueryExpression to simulate this SQL statement
select * from A
inner join B on A.b_id=B.ID
where B.Name like "% what ever %"
this is how the FetchXML might look like
<?xml version="1.0" encoding="UTF-8"?>
<fetch distinct="true" mapping="logical" output-format="xml-platform" version="1.0">
<entity name="A">
<attribute name="ID" />
<attribute name="sce_name" />
<link-entity name="B" alias="ab" to="b_id" from="A">
<filter type="and">
<condition attribute="Name" value="% what ever %" operator="like" />
</filter>
</link-entity>
</entity>
</fetch>
How I can make this in QueryExpression LinkQuery Conditions and Filters, also I don't want to start from B since A might have its conditions too.
This is what I have tried so far
QueryExpression query = new QueryExpression("A");
query.ColumnSet.AllColumns = true;
var link = new LinkEntity()
{
JoinOperator = JoinOperator.Inner,
EntityAlias = "c",
LinkFromEntityName = "A",
LinkToEntityName = "B",
LinkFromAttributeName = "b_id",
LinkToAttributeName = "ID",
};
using (var Service = new OrganizationService("con"))
{
EntityCollection entities = Service.RetrieveMultiple(query);
}
Hopefully this should be self explanatory.
QueryExpression query = new QueryExpression("a") //Start on A
{
ColumnSet = new ColumnSet(), //Columns to retrieve from A
Criteria = new FilterExpression(LogicalOperator.And) //Conditions for A
{
Conditions =
{
new ConditionExpression()
}
},
LinkEntities =
{
//Link to B
new LinkEntity("a", "b", "aid", "bid", JoinOperator.Inner)
{
Columns = new ColumnSet(), //Columns to retrieve from B
LinkCriteria = new FilterExpression() //Conditions for B
{
Conditions =
{
new ConditionExpression()
}
}
}
}
};
In addition to James' answer, don't forget you can also query using the fetch statement you already have:
RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
{
Query = new FetchExpression(
#"<fetch distinct="true" mapping="logical" output-format="xml-platform" version="1.0">
<entity name="A">
...
</entity>
</fetch>");
};
I rarely bother writing out QueryExpressions because executing with fetch is much easier.

How to display video from xml file?

Hi am using xml file given below,how can i get videos from xml file?
<Category name="Videos">
<article articleid="68">
<videourl>
<iframe src="http://player.vimeo.com/video/52375409?fullscreen=0" width="500" height="298" frameborder="0"></iframe>
</videourl>
</article>
</Category>
My Code is
XDocument loadedData = XDocument.Load("CountriesXML.xml");
var data = from query in loadedData.Descendants("Country")
select new CountryData
{
url = (string)query.Element("videourl").Elements("iframe").Single().Attribute("src").Value,
};
countryList = data.ToList();
but i got NullReferenceException error
var xdoc = XDocument.Load("CountriesXML.xml");
var videos = from f in xdoc.Descendants("iframe")
select new {
Src = (string)f.Attribute("src"),
Width = (int)f.Attribute("width"),
Height = (int)f.Attribute("height")
};
Or with your updated code:
var xdoc = XDocument.Load("CountriesXML.xml");
var data = from c in xdoc.Descendants("Category") // you have Category element
select new CountryData {
url = (string)c.Element("article") // there is also article element
.Element("videourl")
.Elements("iframe")
.Single().Attribute("src")
};

Can I 'flatten' an XDocument with Linq?

I have a heavily nested XML document that I need to load into my db for additional processing. For various reasons beyond the scope of this discussion I need to 'flatten' that structure down, then load it into a DataTables and then I can SQLBulkCopy it into the db where it will get processed. So assume my original XML looks something like this (mine is even more heavily nested, but this is the basic idea):
<data>
<report id="1234" name="XYZ">
<department id="234" name="Accounting">
<item id="ABCD" name="some item">
<detail id="detail1" value="1"/>
<detail id="detail2" value="2"/>
<detail id="detail3" value="3"/>
</item>
</department>
</report>
</data>
and I want to flatten that down into a single (albeit redundant) table structure where each attribute becomes a column (i.e. ReportId, ReportName, DepartmentId, DepartmentName, ItemId, ItemName, Detail1, Detail2, Detail3).
So my question is simply 'is it possible to accomplish this with a simple Linq query'? In the past I would just write some XSLT and be done with it but I'm curious if the Linq library can accomplish the same thing?
thanks!
Is this what you're looking for?
var doc = XDocument.Load(fileName);
var details =
from report in doc.Root.Elements("report")
from department in report.Elements("department")
from item in department.Elements("item")
from detail in item.Elements("detail")
select new
{
ReportId = (int)report.Attribute("id"),
ReportName = (string)report.Attribute("name"),
DepartmentId = (int)department.Attribute("id"),
DepartmentName = (string)department.Attribute("name"),
ItemId = (string)item.Attribute("id"),
ItemName = (string)item.Attribute("name"),
DetailId = (string)detail.Attribute("id"),
DetailValue = (int)detail.Attribute("value"),
};
If you want it as a DataTable, you can use the following extension method:
public static DataTable ToDataTable<T>(this IEnumerable<T> source)
{
PropertyInfo[] properties = typeof(T).GetProperties()
.Where(p => p.CanRead && !p.GetIndexParameters().Any())
.ToArray();
DataTable table = new DataTable();
foreach (var p in properties)
{
Type type = p.PropertyType;
bool allowNull = !type.IsValueType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
allowNull = true;
type = Nullable.GetUnderlyingType(type);
}
DataColumn column = table.Columns.Add(p.Name, type);
column.AllowDBNull = allowNull;
column.ReadOnly = !p.CanWrite;
}
foreach (var item in source)
{
DataRow row = table.NewRow();
foreach (var p in properties)
{
object value = p.GetValue(item, null) ?? DBNull.Value;
row[p.Name] = value;
}
table.Rows.Add(row);
}
return table;
}
Use it like this:
var table = details.CopyToDataTable();

Resources