[REQ]How to retrive the Storage Card name - Windows Mobile Software Development

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!

Related

Deploy XAP without Visual Studio

Is it possible to deploy my XAP file without using Visual Studio in either hacked or original emulator image?
With XNA tool WP.exe you can install .xap to Emulator or Device WITHOUT VisualStudio.
On my machine, XNAGSv4=C:\Program Files\Microsoft XNA\XNA Game Studio\v4.0\Tools
Command:
wp install [options] <xap> <app id> <icon> <xapcache>
Example:
%XNAGSv4%\Tools\wp.exe install HellpWP7.xap 71f6d153-0759-4d6e-9bcd-de9a49d8f232 ApplicationIcon.png XapCacheFile.xml
* app id: The GUID found in Propeties\AssemblyInfo.cs
* ApplicationIcon.png: Found in the output directory.
* XapCacheFile.xml: Found in the intermediate (obj) directory.
I have read that the approach using wp.exe from XNA only works for XNA apps. Here is another approach which makes use of CoreCon API: h**p://justinangel.net/WindowsPhone7EmulatorAutomation
XapDeploy
You should use XapDeploy tool from following folder:
c:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Tools\XAP Deployment\
or c:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Tools\XAP Deployment\
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Xml.XPath;
using Microsoft.SmartDevice.Connectivity;
internal static class Utils
{
// Fields
private const string AppIconFileName = "ApplicationIcon.png";
private const string AppNode = "//App";
private const string DefaultAppIcon = "Microsoft.Phone.Tools.DefaultAppIcon.png";
private const string ProductIdNode = "ProductID";
private const string WMAppManifestFile = "WMAppManifest.xml";
// Methods
internal static string ExtractIconFile(string xapPath)
{
string str2;
try
{
using (FileStream stream = new FileStream(xapPath, FileMode.Open, FileAccess.Read))
{
Stream fileStream = new ZipArchive(stream).GetFileStream("ApplicationIcon.png");
if (fileStream == null)
{
fileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.Phone.Tools.DefaultAppIcon.png");
}
string tempFileName = Path.GetTempFileName();
using (FileStream stream3 = new FileStream(tempFileName, FileMode.Create))
{
fileStream.CopyTo(stream3);
}
str2 = tempFileName;
}
}
catch (Exception)
{
str2 = null;
}
return str2;
}
internal static DeviceInfo[] GetDevices()
{
List<DeviceInfo> list = new List<DeviceInfo>();
DatastoreManager manager = new DatastoreManager(0x409);
foreach (Platform platform in manager.GetPlatforms())
{
foreach (Device device in platform.GetDevices())
{
list.Add(new DeviceInfo(platform.Id.ToString(), device.Id.ToString(), device.Name));
}
}
return list.ToArray();
}
internal static Guid? GetXapGuid(string xapPath)
{
Guid? nullable;
try
{
using (FileStream stream = new FileStream(xapPath, FileMode.Open, FileAccess.Read))
{
ZipArchive archive = new ZipArchive(stream);
using (Stream stream2 = archive.GetFileStream("WMAppManifest.xml"))
{
XPathDocument document = new XPathDocument(stream2);
nullable = new Guid(document.CreateNavigator().SelectSingleNode("//App").GetAttribute("ProductID", string.Empty));
}
}
}
catch (Exception)
{
nullable = null;
}
return nullable;
}
internal static RemoteApplication InstallApplication(DeviceInfo deviceInfo, Guid appGuid, string applicationGenre, string iconFile, string xapFile)
{
DatastoreManager manager = new DatastoreManager(0x409);
Device device = manager.GetPlatform(new ObjectId(deviceInfo.PlatformId)).GetDevice(new ObjectId(deviceInfo.DeviceId));
device.Connect();
if (device.IsApplicationInstalled(appGuid))
{
RemoteApplication application = device.GetApplication(appGuid);
application.TerminateRunningInstances();
application.Uninstall();
}
RemoteApplication installApplication = device.InstallApplication(appGuid, appGuid, applicationGenre, iconFile, xapFile);
installApplication.Launch();
return installApplication;
}
internal class DeviceInfo
{
// Methods
internal DeviceInfo(string platformId, string deviceid, string deviceName)
{
this.PlatformId = platformId;
this.DeviceId = deviceid;
this.DeviceName = deviceName;
}
public override string ToString()
{
return this.DeviceName;
}
// Properties
internal string DeviceId
{
get;
set;
}
internal string DeviceName
{
get;
set;
}
internal string PlatformId { get; set; }
}
internal class ZipArchive
{
// Fields
private List<ZipArchiveFile> fileList = new List<ZipArchiveFile>();
private FileStream stream;
// Methods
internal ZipArchive(FileStream stream)
{
this.stream = stream;
for (ZipArchiveFile file = ZipArchiveFile.ReadHeader(stream); file != null; file = ZipArchiveFile.ReadHeader(stream))
{
this.fileList.Add(file);
}
}
internal Stream GetFileStream(string filename)
{
foreach (ZipArchiveFile file in this.fileList)
{
if (string.Compare(file.Name, filename, true) == 0)
{
return file.GetUncompressedStream(this.stream);
}
}
return null;
}
}
internal class DeployArguments
{
internal DeployArguments(DeviceInfo deviceInfo, System.Guid guid, string icon, string xap, OnCompleteAction onComplete)
{
this.DeviceInfo = deviceInfo;
this.Guid = guid;
this.Icon = icon;
this.Xap = xap;
this.OnComplete = onComplete;
}
internal DeviceInfo DeviceInfo
{
get;
set;
}
internal System.Guid Guid
{
get;
set;
}
internal string Icon
{
get;
set;
}
internal OnCompleteAction OnComplete
{
get;
set;
}
internal string Xap { get; set; }
internal delegate void OnCompleteAction(Exception ex);
}
internal class ZipArchiveFile
{
private ushort compressMethod;
private long dataPosition;
// Methods
private ZipArchiveFile()
{
}
internal Stream GetUncompressedStream(Stream zipStream)
{
zipStream.Seek(this.dataPosition, SeekOrigin.Begin);
switch (this.compressMethod)
{
case 0:
return zipStream;
case 8:
return new DeflateStream(zipStream, CompressionMode.Decompress);
}
return null;
}
internal static ZipArchiveFile ReadHeader(FileStream stream)
{
BinaryReader reader = new BinaryReader(stream);
if (reader.ReadUInt32() != 0x4034b50)
{
return null;
}
ZipArchiveFile file = new ZipArchiveFile();
reader.ReadUInt16();
reader.ReadUInt16();
file.compressMethod = reader.ReadUInt16();
reader.ReadUInt16();
reader.ReadUInt16();
reader.ReadUInt32();
uint num2 = reader.ReadUInt32();
reader.ReadUInt32();
ushort count = reader.ReadUInt16();
ushort num4 = reader.ReadUInt16();
file.Name = new string(reader.ReadChars(count));
reader.ReadBytes(num4);
file.dataPosition = reader.BaseStream.Position;
reader.BaseStream.Seek((long)num2, SeekOrigin.Current);
return file;
}
// Properties
internal string Name { get; set; }
}
}
And
Code:
Utils.InstallApplication(Utils.GetDevices()[0], Utils.GetXapGuid(FILENAME).Value, "NormalApp", Utils.ExtractIconFile(FILENAME).Icon, FILENAME);
Regs,
b0l0k
Nice, and only your second post.. Where did you get this?
That's reflected from XapDeploy
You will have to use XapDeploy tool. It requires Zune running on the same environment. You can also use WPConnect, a console tool, if you have Zune installed, see msdn.microsoft.com/en-us/library/gg180729(VS.92).aspx

[Code]C# - App.Config reader

I just want to share my code for reading app.config file. I wrote it earlier for my current project - JWMD Stuick.
I just want it simple and clean and my/an alternative of (I never used it though) OpenNETCF.Configuration.
here's the code
PHP:
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using System.IO;
namespace ApplicationConfiguration
{
public class Configuration
{
XmlDocument xmldoc;
string _applicationname = string.Empty;
string _appconfigfile = string.Empty;
Dictionary<string, string> _appSettings = new Dictionary<string, string>();
public Dictionary<string, string> AppSettings
{
get { return _appSettings; }
}
public Configuration()
{
string startup = System.Reflection.Assembly.GetCallingAssembly().GetName().CodeBase;
FileInfo fi = new FileInfo(startup);
this._applicationname = System.IO.Path.GetFileNameWithoutExtension(startup);
this._appconfigfile = System.IO.Path.Combine(fi.DirectoryName.ToString(), _applicationname + ".exe.config");
Read();
}
void Read()
{
xmldoc = new XmlDocument();
xmldoc.Load(this._appconfigfile);
XmlNodeList nodeCol = xmldoc.SelectNodes("//add");
if (nodeCol != null)
{
foreach (XmlNode thisNode in nodeCol)
{
string key = thisNode.Attributes["key"].Value.ToString();
string value = thisNode.Attributes["value"].Value.ToString();
this._appSettings.Add(key, value);
System.Diagnostics.Debug.WriteLine(key + ", " + value);
}
}
}
}
}
to make this work, make sure app config file is named the way Windows Forms rename the app.config.
e.g. your application name is "mysuperapplication" then the app config file must be "mysuperapplication.exe.config"
below is a application test.

[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] WP7 - Removing an XElement from an XML file

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!

MAPIdotnet and binary message body

Best all,
A while ago I tried to make a simple application which can export all my smses and mmses to my local database server. It runs quite smoothly but I can't manage to get the correct mms body data. It seems that about 5% of the exported body data(for example a sent picture in jpeg format) is different from the original jpeg picture/body data: the exported picture data can't be viewed, it is corrupt.
I suspect the method of exporting the data must be changed from string to binary, but I don't know exactly how to proceed.
I'm using C# 2008 in combination with the MAPIdotnet library, and my target device is a HTC HD Mini with Windows Mobile 6.5 professional.
The part of my code where it's going wrong:
Code:
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(s);
bw.Write(ba);
bw.Close();
fs.Close();
if (messages[msgID].Body != null)
{
FileStream fs2 = File.Create("\\Opslagkaart\\Debug\\body_" + Convert.ToString(msgID) + ".dat");
BinaryWriter bw2 = new BinaryWriter(fs2);
System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
byte[] file = enc.GetBytes(messages[msgID].Body);
//bw2.Write(messages[msgID].Body);
bw2.Write(file);
bw2.Close();
fs2.Close();
}
In combination with MAPIdotnet's code:
Code:
public string Body
{
get
{
IStreamChar s = (IStreamChar)this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0);
if (s == null)
return "";
IntPtr p = Marshal.AllocHGlobal(4);
char[] b = new char[3];
StringBuilder str = new StringBuilder();
int c, len = b.Length * 2;
do
{
s.Read(b, len, p);
c = Marshal.ReadInt32(p);
str.Append(new string(b, 0, c / 2));
}
while (c >= len);
Marshal.FreeHGlobal(p);
return str.ToString();
}
}
Can somebody give a hint of how to proceed?
Thanks,
I suddenly got some more inspiration and, with help from google, I've managed to correctly retrieve the binary jpeg attachments of two of my mmses.
The code part of my program:
Code:
//if (messages[msgID].BodyBinary.Length>0)
//{
FileStream fs2 = File.Create("\\Opslagkaart\\Debug\\body_" + Convert.ToString(msgID) + ".dat");
BinaryWriter bw2 = new BinaryWriter(fs2);
bw2.Write(messages[msgID].BodyBinary);
bw2.Close();
fs2.Close();
//}
The code part of the customized MAPIdotnet:
Code:
private static IntPtr ReadBuffer;
static int Read(OpenNETCF.Runtime.InteropServices.ComTypes.IStream strm, byte[] buffer)
{
if (ReadBuffer == IntPtr.Zero) ReadBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)));
try
{
strm.Read(buffer, buffer.Length, ReadBuffer);
}
catch (NullReferenceException e)
{
//do nothing
}
return Marshal.ReadInt32(ReadBuffer);
}
public byte[] BodyBinary
{
get
{
int buffsize = 1024*1024*2; /* If mms body is bigger than 2MB we have a problem here */
byte[] buffer = new byte[buffsize];
Read(this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0), buffer);
byte[] data = buffer;//ms.ToArray();
Marshal.FreeCoTaskMem(ReadBuffer);
return data;
}
}
But now ALL bodies are saved as 2MB files.. including the empty ones from for example a sms. And not all mms bodies are of the max size of 2mb. My carrier/phone supports up to 1MB. Perhaps I need to get some 'dynamic size' buffer instead of the fixed one. Does anyone have an idea on how to determine the size of the
this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0)
Click to expand...
Click to collapse
stream ?
I've solved all my problems by means of the following code (for mapidotnet):
Code:
private static IntPtr ReadBuffer;
static int Read(OpenNETCF.Runtime.InteropServices.ComTypes.IStream strm, byte[] buffer)
{
int returnvalue = 0;
if (ReadBuffer == IntPtr.Zero) ReadBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)));
try
{
strm.Read(buffer, buffer.Length, ReadBuffer);
returnvalue = Marshal.ReadInt32(ReadBuffer);
}
catch (NullReferenceException e)
{
returnvalue = 0;
}
return returnvalue;
}
public byte[] BodyBinary
{
get
{
int newdatasize = 0;
int buffsize = 1024*1024*3; /* If mms body is bigger than 3MB we have a problem here */
byte[] buffer = new byte[buffsize];
newdatasize = Read(this.msg.OpenProperty(cemapi.PropTags.PR_BODY, 0), buffer);
if (newdatasize < 0) { newdatasize = 0; }
byte[] data = new byte[newdatasize];
Buffer.BlockCopy(buffer, 0, data, 0, newdatasize);
Marshal.FreeCoTaskMem(ReadBuffer);
return data;
}
}
Now all is working fine and the exported files are of their own real size. I'm sure the above code can be optimized but it's working good now.

Categories

Resources