How to display video from xml file? - linq

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")
};

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.

Image in ASP.NET MVC

I have form for upload file and i want to upload thumbnail for the file in the same form I am doing that with this part of code :
var basePath2 = Path.Combine(Directory.GetCurrentDirectory() + "\\Thumbnails\\");
bool basePathExists2 = System.IO.Directory.Exists(basePath2);
if (!basePathExists2)
Directory.CreateDirectory(basePath2);
var thumbnailPath = Path.Combine(basePath2, Thumbnail.FileName);
if (!System.IO.File.Exists(thumbnailPath))
{
using (var stream = new FileStream(thumbnailPath, FileMode.Create))
{
await Thumbnail.CopyToAsync(stream);
}
}
I am saving this model to the database:
var fileModel = new FileUploadViewModel
{
Year = createdOn,
PublishedOn = model.PublishedOn,
FileType = File.ContentType,
Extension = extension,
Name = model.Name,
Description = model.Description,
FilePath = filePath,
Author = model.Author,
ThumbnailPath = thumbnailPath,
};
When I want to show the thumbnail in a view, it doesn't work but in src I have the right path, as you can see in this screenshot:
Screenshot with Source of image
In controller :
string uniqueThumbName = null;
if (Thumbnail != null)
{
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Thumbnails");
uniqueThumbName=Guid.NewGuid().ToString() + "_" + Thumbnail.FileName;
string filePath2 = Path.Combine(uploadsFolder, uniqueThumbName);
Thumbnail.CopyTo(new FileStream(filePath2, FileMode.Create));
}
var fileModel = new FileUploadViewModel
{
ThumbnailPath=uniqueThumbName,
};
In View :
var thumbPath = "~/Thumbnails/" + file.ThumbnailPath;
<img style="width:80px;height:80px;" src="#thumbPath" asp-append-version="true" />

GmailApp - Inline images are attached, and not inline - send email with images in body

I created a Google Script to email several charts as images. When using MailApp it works, and the images are in the body of the email. When using GmailApp, the images are as attachments and not in the email body. I want to use GmailApp because I can use an alias, and because I figured out how to make the email send to a list of people. How do I make a change so that the GmailApp function sends the email with the charts contained in the body? Here is a link to a sample spreadsheet, and here is the code:
function SRpt2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sstotalsheets = ss.getNumSheets();
var clientCode = ss.getSheetByName("Info").getRange("C4").getDisplayValue();
var progmgr = ss.getSheetByName("Info").getRange("D11").getDisplayValue();
var sheetcount = 0;
var token = ScriptApp.getOAuthToken();
var sheets = ss.getSheets();
var blobs = [];
var subject = "Daily " + clientCode +" Digest";
var body = "Your daily update";
var recips = progmgr + ", neill#momentum-behavioral.com";
var emailImages={};
var emailBody="Charts<br>";
for (var i = 5; i < sheets.length ; i++ ) {
var sheet = sheets[i];
var charts = sheet.getCharts();
if(charts.length > 0) {
var template = HtmlService.createTemplateFromFile("reportTemplate");
template.date = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM-dd-yyyy");
blobs[i] = charts[0].getBlob().getAs('image/png').setName("areaBlob");
emailBody= emailBody + "<img src='cid:chart"+i+"'><br>";
emailImages["chart"+i]= blobs[i];
}
}
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases();
if (aliases.length > 0) {
GmailApp.sendEmail(recips, subject, emailBody, {'from': aliases[0],inlineImages:emailImages});
}
MailApp.sendEmail({
to: recips,
subject: subject,
htmlBody: emailBody,
inlineImages:emailImages});
}
And here is the html it refers to:
<html>
<h1>Daily Update <?= date ?></h1>
<p>
<img src="cid:chart" />
</p>
</html>
The incorrectly formatted email body just says the actual html source code (I can't figure out how to paste it into the stackoverflow without it actually treating it as html).
Add the HTML to the options object. And make the body parameter and empty string.
var options;
options = {};//Assign an empty object to the variable options
//{'from': aliases[0],inlineImages:emailImages}
options.from = aliases[0];
options.inlineImages = emailImages;
options.htmlBody = emailBody;
if (aliases.length > 0) {
GmailApp.sendEmail(recips, subject, "", options);//Leave body an empty string
}

Search for a specific picture in google drive folder - Search file name by title

I have a list of possible image file names in a spreadsheet. I'm trying to get the file (if exist) and insert it into the cell next to the name. But I get an error when I call .hasNext(). The code that I am using is:
function listFilesInFolder(folderName) {
var sheet = SpreadsheetApp.getActiveSheet();
var i = 0;
var numberOfRows = sheet.getLastRow();
for (i=0;i<numberOfRows;i+=1) {
var range = sheet.getRange(i+1,1);
var data = range.getValue();
var file = DriveApp.getFolderById("FOLDER_ID_HERE").searchFiles(data);
if (file.hasNext()) {
var rangeDest =sheet.getRange(i+1,2);
var output = file.next();
rangeDest.setValue("=image(\"https://drive.google.com/uc?export=download&id=" + output.getId() +"\")");
};
};
};
Any Ideas?
Thanks!
The problem is from this line:
var file = DriveApp.getFolderById("FOLDER_ID_HERE").searchFiles(data);
Should be:
var searchString = 'title contains "' + data + '"';
var file = DriveApp
.getFolderById("FOLDER_ID_HERE")
.searchFiles(searchString);

Referencing external css file with XMLWorker

I have switched from HtmlWorker to XMLWorker in order to take advantage of the use of external css files. Besides, in this way, I avoid the use of inline styling.
This is currently my code:
public ActionResult ViewPdf(object model)
{
var doc = new Document(PageSize.A3, 10f, 1f, 10f, 30f);
var memStream = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, memStream);
writer.CloseStream = false;
doc.Open();
var xmltext = RenderActionResultToString(View(model));
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(Server.MapPath("~/Content/StyleSheet1.css"), true);
var pipeline = new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));
var worker = new XMLWorker(pipeline, true);
var parser = new XMLParser(worker);
using (var sr = new StringReader(xmltext))
{
parser.Parse(sr);
}
doc.Close();
var buf = new byte[memStream.Position];
memStream.Position = 0;
memStream.Read(buf, 0, buf.Length);
return new BinaryContentResult(buf, "application/pdf");
}
RenderActionResultToString(View(model)) is giving me the string I want to parse into pdf. This all works fine. The problem is with the styles. If I use inline styling such as:
<table style ="width: 400px">
, everything works like a charm. But if I use something like:
<table class = "foo">
, and reference a css file(StyleSheet1.css) like this:
.foo {
width: 400px;
}
, it doesn't work...
I tried referencing the stylesheet in the string I am parsing, like this in my view:
<head>
<link href ="#Server.MapPath("~/Content/StyleSheet1.css")" rel ="stylesheet" type="text/css"/>
</head>
I inserted the link to the css file just as the documentation states, inside the head tags.
Thanks in Advance

Resources