Live Tile not working due to error in setting image? - c#

The App.xaml.cs page of my app contains the following method.
public static void SendLiveTileUpdate(Record rr)
{
string imageUristring = "ms-appdata:///local/" + rr.Id.ToString() + ".jpg";
XmlDocument wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideImageAndText01);
XmlNodeList wideTileTextAttrib = wideTileXml.GetElementsByTagName("text");
wideTileTextAttrib[0].InnerText = rr.Name;
XmlNodeList wideTileImageAttrib = wideTileXml.GetElementsByTagName("image");
//((XmlElement)wideTileImageAttrib[0]).SetAttribute("src", "ms-appdata:///local/" + rr.Id.ToString() + ".jpg");
((XmlElement)wideTileImageAttrib[0]).SetAttribute("src", imageUristring);
((XmlElement)wideTileImageAttrib[0]).SetAttribute("alt", "Image");
//Wide tile Layout done
XmlDocument sqTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareImage);
XmlNodeList sqTileImageAttrib = sqTileXml.GetElementsByTagName("image");
((XmlElement)sqTileImageAttrib[0]).SetAttribute("src", imageUristring);
((XmlElement)sqTileImageAttrib[0]).SetAttribute("alt", "Image");
IXmlNode node = wideTileXml.ImportNode(sqTileXml.GetElementsByTagName("binding").Item(0), true);
wideTileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);
//Square tile set and added to wide tile xml
TileNotification tileNot = new TileNotification(wideTileXml);
tileNot.ExpirationTime = DateTime.Now.AddDays(5);
updater.Update(tileNot);
}
On the page there is also the global variable updater, which is used on page initialization to call EnableNotificationQueue(true) (then later to update the queue as shown).
The problem is that when this code is run it doesn't work. I have deduced that it is something to do with the images because when the image assignments are excluded the live tile updates with the value of rr.Id.ToString(), but included the tile is never updated. this images referenced by imageUristring are present in the apps local storage (and the name corresponds with the Id of the method parameter), yet it still does not work. The images in question are under 200KB, and are 1920x1080. (I think that they will be scaled to fit the tile?)
What am I doing wrong? How could I get the tile to update with the image stored in the local storage?

Your images must be <= 1024x1024. From http://msdn.microsoft.com/en-us/library/windows/apps/Hh781198.aspx:
Tile images must have dimensions less than or equal to 1024x1024
pixels, have a file size of less than or equal to 200 KB, and be of
type .png, .jpg, .jpeg, or .gif.

Related

iPad can't read text file

In my Unity3D project I have several text fields. I saved my text in some text files.
When I test my project on the computer everything works fine, and my code reads the text files. But if I upload to my iPad it won't work and the text fields stay empty.
In the image you can see where I have saved my text files.
To read my text files I use the following code:
public Text infoText;
void Update()
{
readTextFile("FileName", "StepNumber")
}
public void readTextFile(string fileName, string stepNumber)
{
StreamReader txt_Reader = new StreamReader("Assets/Resources/Text_Files/" + fileName + ".txt");
while(!txt_Reader.EndOfStream)
{
string txt_String = txt_Reader.ReadLine();
if(txt_String.Contains(stepNumber))
{
string[] separator = { "_" };
string[] strList = txt_String.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
infoText.text = string.Join("\n", strList.Skip(1));
}
}
}
What do I have to change that my iPad can read from the text files?
EDIT:
My text files looks like this:
Step 1:
* Some Text
* Some Text
Step 2:
* Some Text
* Some Text
* Some Text
Step 3:
* Some Text
Step 4:
* Some Text
So each * should be a new line in my text field. With my old c# code this was no problem, but with
var lines = textFiles.text.Split(new char[] { `*` });
foreach(var line in lines)
{
...
}
i do not know how I can do that, that my text field shows all two lines for step one.
First of all from the Best Practices for the Resources folder
**Don't use it!
Please read the reasons there.
In general for system paths do never use simple string concatenation + "/" +!
Rather use Path.Combine which automatically uses the correct path separators according to the executing platform
Path.Combine(Application.dataPath, "Resources", "Text_Files", fileName + ".txt");
However, you don't/can't simply use a StreamReader to access the Resources folders (See Resources API since it is packed into the build so you have to go through Resources.Load like
// Here you can use / since this is how Unity stores internal paths
// for load you omit the suffix
TextAsset textFile = Resources.Load<TextAsset>("Text_Files/" + filename);
string fileContent = textFile.text;
Or also have a look at Resources.LoadAsync to not block the main thread meanwhile.
BUT
Speaking about blocking the main thread: What you definitely do not want to do is using any of these within Update thus doing heavy FileIO/Loading every frame!
Store the content of that file once as it won't change afterwards anyway!
Depending on your needs you could also simply put your file in any other folder inside the Assets and simply use a TextAsset field directly and drag it into according slot via the Inspector
public TextAsset textFile;
Finally you can then go through the lines one by one using e.g.
var lines = textFile.text.Split(new char[]{'/n'});
foreach(var line in lines)
{
...
}
Note that also that Split is a quite heavy operation since it has to parse every single character in the string and create new substrings so even store these results somewhere in a field of you need them multiple times during runtime!
Typed on smartphone but I hope the idea gets clear
In your case, StreamReader txt_Reader = new StreamReader("Assets/Resources/Text_Files/" + fileName + ".txt"); points to a file on your computer. Assets/Resources/Text_Files/ only exists on your computer.
You need to access a folder that exists on your iPad. It's likely you also didn't save your data to a folder existing on your IPad.
For other devices you could use : Application.persistentDataPath + "/" + fileName
Source: https://docs.unity3d.com/ScriptReference/Application-dataPath.html

Screenshot of a full element in Selenium C#

I need to take a screenshot of a whole element in selenium C# using chromedriver. The element is table and though I am getting the width and height of the element, the screenshot I am getting is of only 15 rows.
IWebElement element = driver.FindElement(By.XPath("Xpath of the element"));
string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
System.Drawing.Rectangle croppedImage = new System.Drawing.Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
screenshot = screenshot.Clone(croppedImage, screenshot.PixelFormat);
screenshot.Save(String.Format(#"path" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg));
Is there any way other than this from which I can get the screenshot of the whole table scrolling the webpage?
Does the table have an ID? If so you could take a screenshot of the table using that id rather than the element name?
WebElement ele = driver.findElement(By.id("yourTableID"));
From the similar question (but not Xpath):
How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?
Seems to suggest you might need to force the window to be larger before taking the screenshot?
this.driver.manage().window().setSize(new Dimension(1680, 1050));
You can use this package https://www.nuget.org/packages/Noksa.WebDriver.ScreenshotsExtensions/
In order to take a screenshot of the element, use the OnlyElementDecorator:
using WDSE;
using WDSE.Decorators;
using WDSE.ScreenshotMaker;
var vcs = new OnlyElementDecorator(new ScreenshotMaker());
var screen = _driver.TakeScreenshot(vcs);

C# - Unable to display image in picturebox

Working on a project that does (or will eventually do) the following:
Access all images in a folder (for test phase using a folder in AppData called 'Test Images')
Place them in a new folder, where the image name is used to place it in or create a sub-folder using an algorithm
Save images in a 'List' so that when they have been saved, they can be displayed in a picturebox on the application - where they can be cycled through using prev/next buttons
The first two steps work fine, and I have checked that the images (only using two image files for the test phase) have been placed in subfolders.
I initialised an array of strings using the Directory.GetAllFiles() function in order to do this, meaning this array contains the paths of all the files that are being copied and manipulated. As a part of this process, I added each file path to the List<Bitmap> so they were able to be displayed in the picturebox.
However, whenever I try to run the function to display the image in the picturebox, the whole application crashes. No exception thrown or anything, just the whole thing stops working. I have no idea what is going on.
I've tried this using picbox.Image = to the element on the List<Bitmap> or using picbox.ImageLocation = to it's file path, but neither has been successful.
The code that should make this happen is shown below:
public void saveLatestImages()
{
//specific path for My Pictures only
string testImagesPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images";
//if there is a Pictures folder
if (Directory.Exists(testImagesPath))
{
//get number of files in folder
int fileCount = Directory.GetFiles(testImagesPath).Count();
//more than one file in folder
if (fileCount > 0)
{
//create data structures to store file info
//filePaths holds path of each file represented as a string
string[] filePaths = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images");
//for each file in Pictures...
for (int index = 0; index < fileCount; ++index)
{
//get name of image at current index
imageName = filePaths[index];
//separate the part relating to the patient name (everything before (DD/MM/YYYY))
string subSpecifier = imageName.Split('\\').Last();
subSpecifier = subSpecifier.Split('_')[0];
//add to root directory to form subfolder name
subDirectory = Path.Combine(rootDirectory, subSpecifier);
//subdirectory name formulated, check for pre-existing
//subfolder does not exist
if(!Directory.Exists(subDirectory))
{
//create it
Directory.CreateDirectory(subDirectory);
}
//otherwise, file will be added to existing directory
//take everything from end and folder\file division to get unique filename
string fileName = imageName.Split('\\').Last();
//add this to the existing subDirectory
fileName = Path.Combine(subDirectory, fileName);
//copy the image into the subfolder using this unique filename
File.Copy(imageName, fileName, true); //true gives instruction to overwrite any existing file with the same path
//add full filename to list of bitmap images
images.Add(new Bitmap(fileName));
//update the shortcut to the file in the image storage shortcut folder
shortcutDirectory = getShortcut(subSpecifier, fileName);
}
}
}
}
public void displayLatestImages()
{
//there are images in list
if (images.Count > 0)
{
//picbox defaults to first image
picboxImage.ImageLocation = Path.GetFileName(images.First().ToString());
}
//check for images before or after current image to enable buttons
checkFirstLast();
}
This shows everything that saves the images to their new file location, and should then allow the first image added to the List to be displayed.
Any advice on how to correct this would be greatly appreciated!
Thanks,
Mark

Web image as tile from local storage

I'm currently trying to download an image, save it to a folder within the LocalStorage container, and then use it as tile. However, everytime I try to do so, the tile is just blank. All there is the name of the app and a title.
I'm unable to test if this occurs because the image isn't saved correctly or because the URI is incorrect.
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var channelFolder = await localFolder.CreateFolderAsync(_currentChannel.Name, CreationCollisionOption.OpenIfExists);
var thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(_currentChannel.Logo));
var remoteFile = await StorageFile.CreateStreamedFileFromUriAsync("profilePicture.jpeg", new Uri(_currentChannel.Logo), thumbnail);
await remoteFile.CopyAsync(channelFolder, "profilePicture.jpeg", NameCollisionOption.ReplaceExisting);
string tileXmlString = "<tile>"
+ "<visual>"
+ "<binding template='TileSquareText04'>"
+ "<image id='1' src='ms-appdata:///local/" +_currentChannel.Name + "/profilePicture.jpeg'>" + "</image>"
+ "<text id='1'>" + "Latest Image" + "</text>"
+ "</binding>"
+ "</visual>"
+ "</tile>";
Windows.Data.Xml.Dom.XmlDocument tileDOM = new Windows.Data.Xml.Dom.XmlDocument();
tileDOM.LoadXml(tileXmlString);
TileNotification tile = new TileNotification(tileDOM);
TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);
_currentChannel.Logo is a string with a url to a jpeg image.
I end up with a transparent tile every time.
After the code runs, you should be able to see if the image is in your \AppData\Microsoft\Packages\\Local folder. If not, then there's a problem downloading it. If it's there, make sure it's both 200KB or less and 1024px or smaller in both dimensions. Those are the limits for tile images which, if exceeded, will cause the image to not appear. In that case you'll need to resample the image.
You should also test your tile updating code separately with a known small image, e.g. something in the package using an ms-appx URI or a remote image with an http URI. If those don't work either, then your updating code is suspect. Check for any errors or exceptions from that section of your code.

iTextSharp Parsing PDF Objects with a view to removing those not in use

As per question Remove unused image objects
I was told I'd effectively have to parse a PDF file, take note of the global object names, then remove those not in use.
I would not have even an inkling of where to start.
I was having a look in VS2010 local viewer and I could see in a page there was an array called Matrix. This seems to contain the XObjects in use in the page. But Matrix does not seem to be a property that the API allows.
I also found in my reader an xrefObj array, which seems to be every object. WHen looking at the XObjects i found a number of PRStream objects which corresponded in size to teh actual images.
iTextSharp.text.pdf.PdfDictionary dictionary = reader.GetPageN(i);
iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, i);
iTextSharp.text.pdf.PdfDictionary res = (iTextSharp.text.pdf.PdfDictionary)iTextSharp.text.pdf.PdfReader.GetPdfObject(dictionary.Get(iTextSharp.text.pdf.PdfName.RESOURCES));
iTextSharp.text.pdf.PdfDictionary xobj = (iTextSharp.text.pdf.PdfDictionary)iTextSharp.text.pdf.PdfReader.GetPdfObject(res.Get(iTextSharp.text.pdf.PdfName.XOBJECT));
foreach (iTextSharp.text.pdf.PdfName name in xobj.Keys)
{
iTextSharp.text.pdf.PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
iTextSharp.text.pdf.PdfDictionary tg = (iTextSharp.text.pdf.PdfDictionary)iTextSharp.text.pdf.PdfReader.GetPdfObject(obj);
iTextSharp.text.pdf.PdfName type = (iTextSharp.text.pdf.PdfName)iTextSharp.text.pdf.PdfReader.GetPdfObject(tg.Get(iTextSharp.text.pdf.PdfName.SUBTYPE));
if (iTextSharp.text.pdf.PdfName.IMAGE.Equals(type))
{
int XrefIndex = Convert.ToInt32(((iTextSharp.text.pdf.PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
iTextSharp.text.pdf.PdfObject pdfObj = reader.GetPdfObject(XrefIndex);
iTextSharp.text.pdf.PdfStream pdfStream = (iTextSharp.text.pdf.PdfStream)pdfObj;
}
}
}
This block, seems to give me the entire catalog of resources - as opposed to the specific used ones on the page.
So I guess what I'm asking for is:
-How can I match what is actually in my PDF file (I assume I make a list of all the ObjNum) references on each actual page of my File against the master list that is held in the reader.
-Remove all references that are not kept in my references list and save in place (this is a temporary file so in place would be fine.
Thanks in advance.
So to identify the images on the page, I used a PdfReaderContentParser.
iTextSharp.text.pdf.parser.PdfReaderContentParser parser = new iTextSharp.text.pdf.parser.PdfReaderContentParser(reader);
MyImageRenderListener listener = new MyImageRenderListener();
while (i < numberofPages)
{
i++;
parser.ProcessContent(i, listener);
}
The MyImageRenderListener is a new class inheriting: iTextSharp.text.pdf.parser.IRenderListener
All I did was add all the names to a list that's accessible from the original class:"
public void RenderImage(iTextSharp.text.pdf.parser.ImageRenderInfo renderInfo)
{
iTextSharp.text.pdf.parser.PdfImageObject image = renderInfo.GetImage();
if (image == null) return;
ImageNames.Add(renderInfo.GetRef().Number);
}
The I used the code posted in the original question as the basis of the master image list.

Categories

Resources