[Q] WP7 - Removing an XElement from an XML file - Windows Phone 7 Software Development

Hi there,
I'm having a big issue, when trying to remove an XElement from an XML file created in IsolatedStorage.
--------------------------------------------------------------------------------------------
Code to CREATE the XML file
Dim File_to_Create As String = "Tracks.xml"
Dim file As XDocument = <?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlnsd="urn:schemas-microsoft-comfficedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Cartridges.xsd" generated="2010-11-23T14:26:55">
<Carts>
<CART_NAME>First</CART_NAME>
<CART_COLOR>White</CART_COLOR>
</Carts>
<Carts>
<CART_NAME>Second</CART_NAME>
<CART_COLOR>Black</CART_COLOR>
</Carts>
</dataroot>
Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Try
If isoStore.FileExists(File_to_Create) Then
MessageBox.Show(File_to_Create + " TRUE")
Else
MessageBox.Show(File_to_Create + " FALSE")
Dim oStream As New IsolatedStorageFileStream(File_to_Create, FileMode.Create, isoStore)
Dim writer As New StreamWriter(oStream)
writer.WriteLine(file)
writer.Close()
MessageBox.Show("OK")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'open selected file
Dim isoStream As IsolatedStorageFileStream
isoStream = New IsolatedStorageFileStream(File_to_Create, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore)
Dim XML_File As XDocument = XDocument.Load(isoStream)
Dim Cart_Query As System.Collections.IEnumerable = From query In XML_File.Descendants("Carts") Order By _
CStr(query.Element("CART_NAME")) Descending, CStr(query.Element("CART_NAME"))
Select New Class_Cartridge_Data With {.Cart_Name = CStr(query.Element("CART_NAME")), _
.Cart_Color = CStr(query.Element("CART_COLOR"))}
Me.ListBox_Cartridges.ItemsSource = Cart_Query
isoStore.Dispose()
isoStream.Close()
End Try
--------------------------------------------------------------------------------------------
Code to ADD / EDIT XElement
Dim File_to_Create As String = "Tracks.xml"
Dim XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()
' Check that the file exists if not create it
If Not (XML_IsolatedStorage.FileExists(File_to_Create)) Then
Return
End If
Dim XML_StreamReader As New StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read))
Dim XML_Document As XDocument = XDocument.Parse(XML_StreamReader.ReadToEnd())
XML_StreamReader.Close()
' Update the element if it exist or create it if it doesn't
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c) c.Element("CART_NAME").Value.Equals("First")).FirstOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' Add new
Dim newProgress As New XElement("Cartridges", New XElement("CART_NAME", "Fourth"), New XElement("CART_COLOR", "Blue"))
Dim rootNode As XElement = XML_Document.Root
rootNode.Add(newProgress)
End If
Using XML_StreamWriter As New StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write))
XML_StreamWriter.Write(XML_Document.ToString())
XML_StreamWriter.Close()
End Using
--------------------------------------------------------------------------------------------
Now my issue and request for some help!
If I use
XML_XElement.Remove
then the following exception is raised whenever I try to "refresh" the bounded ListBox
System.Xml.XmlException was unhandled
LineNumber=37
LinePosition=12
Message=Data at the root level is invalid. Line 37, position 12.
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString, String[] args)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream)
at ListBox_Data_from_XML_LINQ.MainPage.Button_Create_XML_Click(Object sender, RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
InnerException:
--------------------------------------------------------------------------------------------
In short, I can add or edit, but cannot DELETE an XElement...
Any ideas?
Thanks in advance!

Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.

Ren13B said:
Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.
Click to expand...
Click to collapse
Well, I did nothing special, just the XML_Element.remove, instead of adding a new xelement.
Then the error raises whenever I try to reopen the XML file.
My point is, how can I delete an specific xelement?
As far as I know, the following code should work
Code:
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c ) c.Element("CART_NAME").Value.Equals("First")).Firs tOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' remove the selected record
XML_XElement.Remove
End If
Honestly I don't know if the foregoing code is correct or if the issue is related to how WP7 handles the removal thus corrupting the original file.
Please let me know if you need anything else.
Any help is very appreciated!
PS: Thanks for the other replies, helped a lot!

Here's how I did it in c#. My xml file is very different than yours so the query will be different but the important parts are where you load and close the file streams and then write.
Code:
//Get users private store info
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
//open selected file
isoStream = new IsolatedStorageFileStream(list, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument xml = XDocument.Load(isoStream);
isoStream.Close();
//Find section
XElement sectionElement = xml.Descendants("section").Where(c => c.Attribute("name").Value.Equals(groupn)).FirstOrDefault();
//Find item and remove it
sectionElement.Elements("setting").Where(c => c.Attribute("name").Value.Equals(litem)).FirstOrDefault().Remove();
isoStream.Close(); //Seems unnecessary but it's needed.
//Write xml file
isoStream = new IsolatedStorageFileStream(list, FileMode.Create, FileAccess.Write, isoStore);
xml.Save(isoStream);
isoStream.Close();

Thanks again for your help, greatly appreciated.
However I'm still getting the same error.
Sorry for asking, but are you getting any errors when deleting in WP7 ?
My knowledge on XML is extremely new and I'm sure that I'm making some mistakes somewhere...
But so far, I cannot get past the same exception.
Seems that the XML gots "corrupted" after the delete operation.
On the other hand, if is not too much to ask for, using my current code, how will handle the delete of the selected record?
Thanks!

I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx

Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Problem is my country is not listed so I cannot register...
Here is the C# version of my current code for adding/editing
Code:
public static void ADD_XML_Record()
{
string File_to_Create = "Tracks.xml";
var XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
// Check that the file exists if not create it
if (! (XML_IsolatedStorage.FileExists(File_to_Create)))
{
return;
}
StreamReader XML_StreamReader = new StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read));
XDocument XML_Document = XDocument.Parse(XML_StreamReader.ReadToEnd());
XML_StreamReader.Close();
// Update the element if it exist or create it if it doesn't
XElement XML_XElement = XML_Document.Descendants("Carts").Where((c) => c.Element["CART_NAME"].Value.Equals("dd")).FirstOrDefault();
if (XML_XElement != null)
{
XML_XElement.SetElementValue("CART_NAME", "bbbbb");
}
else
{
// Add new
XElement newProgress = new XElement("Carts", new XElement("CART_NAME", "dd"), new XElement("CART_COLOR", "ff"));
XElement rootNode = XML_Document.Root;
rootNode.Add(newProgress);
}
using (StreamWriter XML_StreamWriter = new StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write)))
{
XML_StreamWriter.Write(XML_Document.ToString());
XML_StreamWriter.Close();
}
}
I tried your code but I'm having a bad time making it to work.
If not a big deal, please could you tell me how to modify it ?
I mean, if a record is found, instead of editing, to remove it?
Honestly I'm stuck and any help is more than apprecisted!

Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Ren,
Just to say thank you for your last code. I made a little mod and now it works ok!
Thanks a lot for helping me out!

Related

[REQ]How to retrive the Storage Card name

Hi all,
Does anyone know how to retrive (identify) the system name of the Storage Card using .Net C.F. and Visual Basic language?
This is because often changig the WM version or the localization of the device, can also change the name of the Storage Card (with related "Path not found" error in the program).
Thanks for help
using C#.net
Code:
private static string GetStorageCardPath()
{
DirectoryInfo di = new DirectoryInfo(@"\");
FileSystemInfo[] fsi = di.GetFileSystemInfos();
foreach (FileSystemInfo fileSystemInfo in fsi)
{
if ((fileSystemInfo.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)
{
return fileSystemInfo.FullName;
}
}
return null;
}
and with convert csharp to vb in VB.net
Code:
Private Shared Function GetStorageCardPath() As String
Dim di As New DirectoryInfo("\")
Dim fsi As FileSystemInfo() = di.GetFileSystemInfos()
For Each fileSystemInfo As FileSystemInfo In fsi
If (fileSystemInfo.Attributes And FileAttributes.Temporary) = FileAttributes.Temporary Then
Return fileSystemInfo.FullName
End If
Next
Return Nothing
End Function
Thanks HeliosDev!

[Q] Writing in an XML File Problem

Hey Guys!
I'm sitting in front of an XML-Problem for five days now and really don't know what's to do. Expect of asking you.
I want to write a small shopping list application that manages the data in an XML-File looking like that:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<Items>
<Item>
<Name>Bananas</Name>
<Store>supermarket</Store>
<Repeat>true</Repeat>
</Item>
<Item>
<Name>LG E900 Optimus 7</Name>
<Store>superhandy</Store>
<Repeat>false</Repeat>
</Item>
(...)
I have a ListBox called ItemShowcase that I fill with instances of my ShowCaseEntry-Class
Reading Data from the FIle works perfectly with this code:
Code:
private void updateItemList()
{
// load XML-File
var items = XElement.Load("MissingItems.xml");
foreach (var a in items.Elements())
{
ShowCaseEntry sce = new ShowCaseEntry(a.Element("Name").Value, "Store: " + a.Element("Store").Value, false);
ItemShowcase.Items.Add(sce);
}
}
No Problem until here.
But now I want to add a new Iem to my XML-File.
I have 2 Textfields in what I ask for the Item-Name and Store-Name. Repeat is always true.
I tried that:
Code:
public void addXMLItem(String name, String store, Boolean repeat)
{
// XML-Datei Laden
var items = XDocument.Load("MissingItems.xml");
// neues Item erstellen
XElement newItem = new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat) );
// Hinzufügen und spreichern
items.Root.Add(newItem);
FileStream F = new FileStream("MissingItems.xml", FileMode.Open);
items.Save(F);
}
The last line give me the following Error:
Attempt to access the method failed: System.IO.FileStream..ctor(System.String, System.IO.FileMode)
Is anyone here who would help me?
You would save my weekend!
Thank you so much!
Best wishes and greets
Robby
Try something like this:
Code:
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
//Add your xml items here.
xml.Save(isoStream);
isoStream.Close();
First of all thanks for your answer.
Unfortunately I don't really know how to add the XML-Items.
Like this?
Code:
public void addXMLItem(String name, String store, Boolean repeat)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
//Add your xml items here.
var items = XDocument.Load("MissingItems.xml");
XElement newItem = new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat));
items.Root.Add(newItem);
items.Save(isoStream);
isoStream.Close();
}
Another answer would be very nice
Best regards
Robby
I don't have time to test it but hopefully this works for you.
Code:
public void addXMLItem(String name, String store, Boolean repeat)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
//Add your xml items here.
XDocument items = XDocument.Load(isoStream);
items.Element("Items").Add(
new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat)));
items.Save(isoStream);
isoStream.Close();
}
Thank you really much for your engangement, but there is still one problem.
In this line the program throws an XML-Error called "root element is missing":
XDocument items = XDocument.Load(isoStream);
How to explain the Load-Method that "Items" is my root Element?
Greets
Robby
Sorry my code had errors. This is tested and working.
Code:
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument items = XDocument.Load(isoStream);
isoStream.Close();
items.Element("Items").Add(
new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat.ToString())));
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
items.Save(isoStream);
isoStream.Close();
That code results in this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<Items>
<Item>
<Name>Bananas</Name>
<Store>supermarket</Store>
<Repeat>true</Repeat>
</Item>
<Item>
<Name>LG E900 Optimus 7</Name>
<Store>superhandy</Store>
<Repeat>false</Repeat>
</Item>
<Item>
<Name>Test Name</Name>
<Store>Test Store</Store>
<Repeat>False</Repeat>
</Item>
</Items>
I really, really thank you for your anxiety. Thank you for your time, but I just have one more error.
This line throwes an Isolated Storage Exception called "Operation not permitted on IsolatedStorageFileStream.":
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
You would save my week with a short answer!
Thank you so much till yet
Robby
It sounds like the file stream is already open somewhere else. If you are doing any other reads or writes to the file prior to your addxmlitem method you need to close the stream before calling addxmlitem.
Not really
Sorry, I am sure that I'm annoying but I really need to fix that problem.
My last try to solve ist is to send you the full code:
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
namespace MyShoppingList
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Item[] itemArray = new Item[2];
CheckBox[] checkBoxArray = new CheckBox[2];
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
updateItemList();
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
/// <summary>
/// Adds new Item to the XML-File
/// </summary>
/// <param name="name">Itemname</param>
/// <param name="store">Storename</param>
/// <param name="repeat">Repeat</param>
public void addXMLItem(String name, String store, Boolean repeat)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument items = XDocument.Load(isoStream);
isoStream.Close();
items.Element("Items").Add(
new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat.ToString())));
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
items.Save(isoStream);
isoStream.Close();
}
/// <summary>
/// Updates Item List
/// </summary>
private void updateItemList()
{
// XML-Datei Laden
var items = XElement.Load("MissingItems.xml");
foreach (var a in items.Elements())
{
ShowCaseEntry sce = new ShowCaseEntry(a.Element("Name").Value, "Store: " + a.Element("Store").Value, false);
ItemShowcase.Items.Add(sce);
}
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
addXMLItem(tBoxAddItemName.Text, tBoxAddItemStore.Text, false);
//updateItemList();
}
}
}
Can you find any mistakes?
I'm getting desperate...
Thanks a lot for your engagement!
I'n not really sure why that's happening. The only thing I can think of is XElement.Load() is causing the problem so here's how to use XDocument.Load() instead. I really hope this works for you because I'm out of ideas.
Code:
private void updateItemList()
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument xml = XDocument.Load(isoStream);
var items = from c in xml.Elements("Items").Elements("Item")
select new {
name = c.Element("Name").Value,
store = c.Element("Store").Value,
repeat = c.Element("Repeat").Value
};
foreach (var item in items)
{
ShowCaseEntry sce = new ShowCaseEntry(item.name, "Store: " + item.store, false);
ItemShowcase.Items.Add(sce);
}
isoStream.Close();
}
Same Error on this line:
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
Operation not permitted on IsolatedStorageFileStream.
I'm at the end of my motivation
I really tried everything, you really tried everything and I cannot find anything helpful to this error message..
Does anyone has an idea?
Does this line works for you?
Big Thanks to Ren13B till yet!
Attached is my working test project. Maybe it will help you.
If you are accessing the Isolated Storage from within a referenced assembly, you will need to access the IsolatedStorageFile for that assembly
Thanks for your reply but how to do that?

[Q] Coding in Error checking for VB.net CF app

Hello all, Sorry for the dumb question but i'm pretty new to VB.Net CF.
I'm working on a little program that exports settings from the registry and then writes to the SD card for XDA_UC to import when a new rom installed. I'm currently struggling with the error checking code. I want it to be able to tell if there was an issue updating an already existing file with new settings but i can't seem to find a way to do it. I have managed to get it to check the file was written but this only works the first time. After that it always reports a success if the file is present in the expected location.
I've pated what i have below. I appreciate all and any thoughts you may have.
Code:
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Private[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] BTIdent_Click([/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] sender [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] System.Object, [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] e [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] System.EventArgs) [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Handles[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] BTIdent.Click[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]'Setup The variables so we can have them ready to write the .reg file[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] BTIdentity [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] = Registry.GetValue([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"HKEY_LOCAL_MACHINE\Software\WIDCOMM\BTConfig\General"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"DeviceName"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2], 0)[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] sw [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] IO.StreamWriter = IO.File.CreateText([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\BT_Ident.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]'Format and then write the reg file to disk[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]sw.WriteLine([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Windows Registry Editor Version 5.00"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2]sw.WriteLine()[/SIZE]
[SIZE=2]sw.WriteLine([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"[HKEY_LOCAL_MACHINE\Software\WIDCOMM\BTConfig\General]"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2]sw.WriteLine([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"""DeviceName""="""[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] + BTIdentity.ToString + [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]""""[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2]sw.Flush()[/SIZE]
[SIZE=2]sw.Close()[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]'Check that the file wrote successfully (this needs work becuase it will always report "operation successful" once the file has been written once[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] File.Exists([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\XDA_UC\BT_Ident.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]) [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]MessageBox.Show([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Operation Complete."[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Else[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]MessageBox.Show([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Operation Failed."[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][/COLOR][/SIZE]
[/COLOR][/SIZE][/COLOR][/SIZE]
You could use FileSystemInfo properties of the file to make sure it was actually updated.
Code:
Dim fsi As FileSystemInfo = New FileInfo("\Storage Card\XDA_UC\BT_Ident.reg")
This will reveal the FileSystemInfo properties of the file, as defined here:
http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo_members(v=VS.71).aspx
LastWriteTime is the last time the file was written to. If it wasn't within the last few seconds then the update has failed.
I've got to a point in my project where i actually need to look at doing this so thanks for taking the time to post.
this i what i've come up with so far
Code:
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]File.Exists([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\XDA_UC\VolumeTest.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]) [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] fsi [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] FileSystemInfo = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] FileInfo([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\XDA_UC\volumetest.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] fsi.LastWriteTime = DateAndTime.Now [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]OpComplete()[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Else[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]OpFailed()[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End If[/COLOR][/SIZE][/COLOR][/SIZE]
It should work but i would like to say dateandtime.now +/- say 5 seconds and i'm having trouble figuring that part out.
Any ideas?
This should do the trick.....
Code:
Dim Seconds5 As New TimeSpan(0,0,5)
If File.Exists("\Storage Card\XDA_UC\VolumeTest.reg") Then
Dim fsi As FileSystemInfo = New FileInfo("\Storage Card\XDA_UC\volumetest.reg")
If (DateAndTime.Now - fsi.LastWriteTime) < Seconds5 Then
OpComplete()
Else
OpFailed()
End If
End If
Alternatively, drop line 1 and put it straight into the compare, as that what the compiler will do anyway, when you switch it to a 'Release' build.
Code:
If File.Exists("\Storage Card\XDA_UC\VolumeTest.reg") Then
Dim fsi As FileSystemInfo = New FileInfo("\Storage Card\XDA_UC\volumetest.reg")
If (DateAndTime.Now - fsi.LastWriteTime) < New TimeSpan(0,0,5) Then
OpComplete()
Else
OpFailed()
End If
End If
Cool, thanks. I really do appreciate you taking the time to help.

ListBox.ItemTemplate error

hey guys I am getting an error when I am trying to put a twitter feed in my blog app. The error says
“The attachable property ‘ItemTemplate’ was not found in type ‘ListBox’.”
what does this mean. Here is the code that I put in my listbox on the Xaml.
Code:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding UserName}" Foreground="#FF2276BB" FontSize="28" />
<TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
<HyperlinkButton Content="{Binding TweetSource}" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="18" Foreground="#FF999999" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
any help would be appreciated.
Posted XAML code is OK so I can only guess. Probably you've referenced a wrong assembly in your project. Post whole project.
http://blog.objectgraph.com/index.php/2010/03/26/how-to-create-a-twitter-client-on-windows-phone-7/
I am using that site as a guide and putting it in the Wordpress Starter Kit I added a panarama item called Twitter, added a list box and a button and a TextBlock (the text block says OmegaRa) and the buttons says refresh. I am at work currently, so I can't post the rest of my code...
edit: if it matters I named the listbox Twitterfeed, I know I had to alter a couple spots with that to get rid of errors. Plus the original code is for 7.0, in VS2010, I right clicked on the Solution and clicked Upgrade to 7.1...
Seems like this toolkit has a different assemblies for 7.0 and 7.1 (located at sl3-wp & sl4-windowsphone71 folders), check your project references for correct library (7.1).
okay, I am a complete newb when it comes to coding (hence the starter kit and tutorial) how would I go about doing that?
Solution Explorer (on your right) -> References -> click on assembly and check properties. Press Del to remove assembly. Right click and press "Add assembly" from the context menu.
P.S. But before start coding I'm strongly recommend you to RTFM (Read The Following Manual, not the "fu%?ng" one ). Download/buy and read a good manual for Visual Studio and .NET first...
That would probably be a good idea LOL. I just like figuring it out sometimes though, but it would probably go faster if I read something about it first lol.
edit: I will try looking at that when I get home from work and after my daughters birthday dinner lol
Okay, I am home and looking at the references, which assembly would it be?
progress, fixed that part forgot the
Code:
<listbox></listbox>
surrounding it, but when I hit refresh...is doen't get my feed, lol it says something about wordpress starter kit + tweet or something lol.
here is the code for the button
Code:
private void button3_Click(object sender, RoutedEventArgs e)
{
WebClient twitter = new WebClient();
twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + tbUsername.Text));
}
void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
XElement element = XElement.Parse(e.Result);
TwitterFeed.ItemsSource = from tweet in element.Descendants("status")
select new Tweet
{
UserName = tweet.Element("user").Element("screen_name").Value,
Message = tweet.Element("text").Value,
ImageSource = tweet.Element("user").Element("profile_image_url").Value,
TweetSource = FormatTimestamp(tweet.Element("source").Value, tweet.Element("created_at").Value)
};
}
catch (Exception)
{
}
}
public class Tweet
{
public string UserName { get; set; }
public string Message { get; set; }
public string ImageSource { get; set; }
public string TweetSource { get; set; }
}
private string StripHtml(string val)
{
return System.Text.RegularExpressions.Regex.Replace(HttpUtility.HtmlDecode(val), @"<[^>]*>", "");
}
private string DateFormat(string val)
{
string format = "ddd MMM dd HH:mm:ss zzzz yyyy";
DateTime dt = DateTime.ParseExact(val, format, System.Globalization.CultureInfo.InvariantCulture);
return dt.ToString("h:mm tt MMM d");
}
private string FormatTimestamp(string imageSource, string date)
{
return DateFormat(date) + " via " + StripHtml(imageSource);
}
}
}
what the screen says when I hit refresh is WordpressStarterKit.Mainpage+Tweet, and I notice that the button and the Text Block stay on the screen no matter if I pan or not....
PM me your project in archive, I'll correct your errors and send back.
If I change
Code:
twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + tbUsername.Text));
to
Code:
twitter.DownloadStringAsync(new Uri"http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=OmegaRa" );
would that fix it? I am just curious to see if I am right..
All issues solved, mod can close thread if they want.

[GENERAL KNOWLEDGE]View files/resources a 3rd party app read/writes to

Hello all,
Just curious about some general knowledge (salute; reference: HIMYM) on whether or not it's possible to see what an app is doing (during installation, in the background, app initialization, and foreground usage)
It's not my own app in question so I understand physically seeing the code is out of the question; however I'm more concerned about what the app is doing and the files/directories it accesses, and whether or not there's a way for me to view these activities.
If you must know, the app in question is the Adidas Confirmed app as RootCloak (and various other apps) DO NOT WORK. I'm attempting to isolate the issue, and I'm fairly certain it has to do with an external resource (within the device; i.e. different partition, files, folders, etc.) that permanently marks the device 'rooted' during initial installation. Maybe if I can see exactly what the app reaches out to, I can then come up with a fix action.
Any input would be greatly appreciated.
You could try to decompile this app, but it might not work very well if the app obfuscates the code http://decompileandroid.com/
Rijul.A said:
You could try to decompile this app, but it might not work very well if the app obfuscates the code http://decompileandroid.com/
Click to expand...
Click to collapse
This actually worked PERFECTLY. I was able to go inside the src and see exactly the commands the app calls for to check root.
If anyone is interested...I'm going to try a few things out, play with some variables and see if I can't allow the app access on my rooted device.
Code:
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.gpshopper.adidas.objects;
import android.os.Build;
import java.io.File;
// Referenced classes of package com.gpshopper.adidas.objects:
// ExecShell
public class Root
{
private static String LOG_TAG = com/gpshopper/adidas/objects/Root.getName();
public Root()
{
}
public static boolean checkRootMethod1()
{
String s = Build.TAGS;
return s != null && s.contains("test-keys");
}
public static boolean checkRootMethod2()
{
label0:
{
label1:
{
boolean flag = false;
boolean flag1;
try
{
File file = new File("/system/app/Superuser.apk");
File file1 = new File("/system/app/SuperSU/SuperSU.apk");
if (file.exists())
{
break label1;
}
flag1 = file1.exists();
}
catch (Exception exception)
{
return false;
}
if (!flag1)
{
break label0;
}
}
flag = true;
}
return flag;
}
public static boolean checkRootMethod3()
{
return (new ExecShell()).executeCommand(ExecShell.SHELL_CMD.check_su_binary) != null;
}
public static boolean isDeviceRooted()
{
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3();
}
}
There is a similar file also in the src using a different language I've not yet been able to comprehend. I'm really new at this in case you couldn't already figure lol...is it possible to view my device's database where apps store variables? It may be possible the app is permanently storing the variable even after its removal so best case would be to start from a fresh ROM install. Just a theory.
The other language is generally irrelevant
Delete /data/data/<packagename>/ or clear app data normally, that will work, no need for a fresh install.
If you need help hooking this method, please quote me in a reply.

Categories

Resources