[Tutorial] How to simply get TRACE output from native dll to managed VS2010 debugger - Windows Phone 7 Development and Hacking

Hi friends.
There is simple tutorial. We use WP7 DllIprort Project, or another native Dlls, to enable our managed (mostly Silverlight) applications to do any system calling. But, debuging of hybrid applications is difficult. May be, somebody is able to make publicly usable source to use standard Visual Studio way to test and debug native Dlls, but Ultrashot and others have no time, they have important things to do.
Then, I prepared simple library, which export native TRACE macro and managed wrapper too.
Using:
1. Copy all content from attachment NativeDebugTraceVS2008 directory to your VS2008 native dll project directory.
2. Add NativeDebug2008.dll and NativeDebugTrace.h to your native dll project.
3. Add line:
#include "NativeDebugTrace.h"
on top of your native c++ source code.
4. Use TRACE macro in your code. Syntax is usual, example:
...
int nVal = 1+1;
TRACE(L"%s = %d", L"nVal", nVal);
...
Output is showed in "normal" VS2008 Output window too, when you debug under VS2008.
If you have used another TRACE macro in your code, you can rename TRACE macro to ANY_OTHER_TRACE_NAME in NativeDebugTrace.h and call this another macro.
5. Copy all content from attachment NativeDebugTraceVS2010 directory to your VS2010 managed application or dll project directory.
6. Add both NativeDebug2010.dll and NativeDebug2008.dll to your project, set Copy if newer its option.
7. Add reference to NativeDebug2010.dll to your project.
8. Add Initialisation to your App constructor:
Code:
...
public App()
{
...
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
...
NativeDebug.Init();
}
else
{
NativeDebug.RegisterOnly();
}
}
...
I am not sure why, but RegisterOnly() calling is necessary to work without debugging, your native dll will not load properly instead.
9. Add garbage release to your App closing:
Code:
...
private void Application_Closing(object sender, ClosingEventArgs e)
{
NativeDebug.Destroy();
...
}
...
10. Change your VS2010 view to Expert (Menu/Tools/Settings/Expert Settings).
11. Open your Output window on top (Menu/View/Output, click to Window Position/Float).
Now you can see all managed System.Diagnostics.Debug.WriteLine and native TRACE ouput in one Output window. Attention - option "Menu/Tools/Options/Debugging/Redirect all Output text to Immediate window" does not work for me.
You can also write output to TRACE file by standard way (see System.Diagnostics.Debug.WriteLine help).
Attention: Debug Trace Library is fully synchronised, but I did not test it to debug more then one application alternately. May be any deadlock can occure, but I beleive will not. When your managed code use another unicode string prefix then L"...", try to change calling, and write your experience here.
See example picture, follow red text:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Picture is from old version, included to W.I.N.C.O native library. But, yestarday I have got total hard disc crash crying::crying::crying, all my programs from long time are lost. I must programm this feature again today, I believe it is better then last weak.
Note:
Attachment is functional, but will be changed in future. Little COM mishmash and WP7 WatchDog problems occured.
Next code probably solve it, but I am not sure. Do not forget to set HKLM\Software\Microsoft\TaskHost\DehydrateOnPause to 0 first, when you want to debug application calling ShellExecuteEx() etc.
Code:
private void Application_Activated(object sender, ActivatedEventArgs e)
{
NativeDebug.Start();
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
NativeDebug.Stop();
}

TRACE Output example. MFC integrated to ATL for WP7, registry export to file.
This is output from registry exporting wiht MFC using. Without tracing it woud be very difficult to tune to a flawless running:
'UI Task' (Managed): Loaded 'C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v2.0\WindowsCE\mscorlib.dll'
'UI Task' (Managed): Loaded 'System.Windows.RuntimeHost.dll'
'UI Task' (Managed): Loaded 'System.dll'
'UI Task' (Managed): Loaded 'System.Windows.dll'
'UI Task' (Managed): Loaded 'System.Net.dll'
'UI Task' (Managed): Loaded 'System.Core.dll'
'UI Task' (Managed): Loaded 'System.Xml.dll'
'UI Task' (Managed): Loaded '\Applications\Install\8F4EF9C1-BE29-4252-BE77-EAD8CE2E9D4E\Install\Phonmander.dll', Symbols loaded.
'UI Task' (Managed): Loaded 'Microsoft.Phone.dll'
'UI Task' (Managed): Loaded 'Microsoft.Phone.Interop.dll'
'UI Task' (Managed): Loaded '\Applications\Install\8F4EF9C1-BE29-4252-BE77-EAD8CE2E9D4E\Install\NativeDebug2010.dll', Symbols loaded.
'UI Task' (Managed): Loaded 'Microsoft.Phone.InteropServices.dll'
'UI Task' (Managed): Loaded '\Applications\Install\8F4EF9C1-BE29-4252-BE77-EAD8CE2E9D4E\Install\wxNativeCOM.dll', Symbols loaded.
'UI Task' (Managed): Loaded '\Applications\Install\8F4EF9C1-BE29-4252-BE77-EAD8CE2E9D4E\Install\wlCoreWp7.dll'
Managed ==> Native
RegGetStringSimple dwKey = 80000002, szSubKey = Pokus2012, szValueName = ValStr, lpszValue = 35EF09C
RegGetDwordSimple RegQueryValueEx returns 80070057 Parametr není správný.
RegExportKeySimple(DWORD dwKey = 80000002, LPCWSTR szSubKey = HARDWARE\DEVICEMAP, LPCWSTR szFileName = \Pokus2012.txt)
ExportRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP, CFile &out = 45FFFC48)
ExportRegKey BOM
ExportRegKey Editor Version
DumpRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP, CFile &out = 45FFFC48)
RegEnumValueW returns 103 No more data is available.
DumpRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP\TOUCH, CFile &out = 45FFFC48)
RegEnumValueW returns 0 The operation completed successfully. DriverName
RegEnumValueW returns 103 No more data is available.
DumpRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP\TOUCH\BUTTONS, CFile &out = 45FFFC48)
RegEnumValueW returns 0 The operation completed successfully. Count
RegEnumValueW returns 0 The operation completed successfully. Area
RegEnumValueW returns 103 No more data is available.
DumpRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP\TOUCH\BUTTONS\3, CFile &out = 45FFFC48)
RegEnumValueW returns 0 The operation completed successfully. VKey
RegEnumValueW returns 0 The operation completed successfully. VKeyPuvodni
RegEnumValueW returns 0 The operation completed successfully. Area
RegEnumValueW returns 0 The operation completed successfully. Name
RegEnumValueW returns 103 No more data is available.
DumpRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP\TOUCH\BUTTONS\2, CFile &out = 45FFFC48)
RegEnumValueW returns 0 The operation completed successfully. VKey
RegEnumValueW returns 0 The operation completed successfully. Name
RegEnumValueW returns 0 The operation completed successfully. Area
RegEnumValueW returns 103 No more data is available.
DumpRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP\TOUCH\BUTTONS\1, CFile &out = 45FFFC48)
RegEnumValueW returns 0 The operation completed successfully. VKey
RegEnumValueW returns 0 The operation completed successfully. Name
RegEnumValueW returns 0 The operation completed successfully. Area
RegEnumValueW returns 103 No more data is available.
DumpRegKey(HKEY hroot = 80000002, const CString &root = HKEY_LOCAL_MACHINE, const CString &key = HARDWARE\DEVICEMAP\KEYBD, CFile &out = 45FFFC48)
RegEnumValueW returns 0 The operation completed successfully. Status
RegEnumValueW returns 0 The operation completed successfully. CurLang
RegEnumValueW returns 0 The operation completed successfully. RingerState
RegEnumValueW returns 103 No more data is available.
RegExportKeySimple ExportRegKey lRes = 1)
...

Related

copied exe-file is not a valid application

Hi,
I have written a litte application (eMbedded Visual C++) for Pocket PC 2002
to copy an exe-file from the root-directory to the startmenu-directory.
It seems to work fine, but when I start the copied application (the exe-file) I get the message
"... is not a valid Pocket PC application"
What is wrong with this applcation?
Or does anyone know how to call Copy from an Pocket PC application directly?
Here is the code:
// Setup.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#define SOURCEFILE_NAME "\\banking.exe"
#define DESTINATIONFILE_NAME "\\Windows\\Start Menu\\banking.exe"
#define DESTINATIONFILE_NAME_GERMAN "\\Windows\\Startmenü\\banking.exe"
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
BOOL german = FALSE;
FILE *file = 0;
FILE *rfile = 0;
rfile = fopen (SOURCEFILE_NAME, "rb");
if (!rfile)
{
MessageBox (0, TEXT("Error"), TEXT("Setup"), MB_TOPMOST);
return 1;
}
file = fopen (DESTINATIONFILE_NAME_GERMAN, "wb");
if (!file)
file = fopen (DESTINATIONFILE_NAME, "wb");
else
german = TRUE;
if (file)
{
char buffer [1000];
size_t num_read = 0;
size_t num_written = 0;
size_t num_read_tot = 0;
size_t num_written_tot = 0;
do
{
num_read = fread (buffer, sizeof (char), 1000, rfile);
if (feof(rfile))
break;
num_read_tot += num_read;
if (num_read > 0)
{
num_written= fwrite (buffer, sizeof (char), num_read, file);
num_written_tot += num_written;
}
else
break;
} while (1);
fclose (file);
}
fclose (rfile);
DWORD attr = 0;
BOOL rc = 0;
attr = GetFileAttributes (TEXT(SOURCEFILE_NAME));
if (german)
rc = SetFileAttributes (TEXT(DESTINATIONFILE_NAME_GERMAN), attr);
else
rc = SetFileAttributes (TEXT(DESTINATIONFILE_NAME), attr);
MessageBox (0, TEXT("Ready"), TEXT("Setup"), MB_TOPMOST);
return 0;
}
// END
Hello,
You are trying to reinvent the wheel by copying yourself the info from the file. Use the CopyFile function.
But your error
"... is not a valid Pocket PC application"
Click to expand...
Click to collapse
has probably appeared for another reason...
You should also look at SHFileOperation
It's not a good idea to copy *.exe files to start menu...
Create a shortcut with CECreateShortcut(...) instead.
If this is part of a application setup (in a cab file) just create the shortcut with the build in features:
...
[DefaultInstall]
...
CEShortcuts = Shortcuts
...
[Shortcuts]
BankingMenuText,0,banking.exe
...
John
John,
thank you for your comment.
Perhaps you ore someone else can tell me how to create a shortcut (for the banking.exe) from a Pocket PC - application ?
(The background is as follows:
I want to deliver my banking-application on SD-Card;
a little setup-application on the SD-Card copies the banking.exe from SD-Card into the program-directory of the Pocket PC.
And last but not least this setup-application shoult insert a shortcut for the copied banking.exe in the Start Menu.
OK,
cabwiz.exe does exactly the job.
One open question:
How can I achieve, that after executing the cab-file is N O T deleted?
Create Shortcut with SHCreateShortcut.
Not deleting cab file : mark it as read-only on the desktop (before copying) 8)

Device Power Management in WM

Dear сolleagues and development guru!
I have some stopper in Power Management. I hope somebody will help me to understand.
Technologies: C#, .NET 3.5
The main point of application:
Make beep periodically.
Main problem is:
When PocketPC in active mode application running correct, but when PocketPC went to sleep mode it does not make a beep. As I understood speaker is turned off in sleep mode (like all other devices in PocketPC).
Question:
How can I turn on speaker in sleep mode?
Simply what I need is turn on speaker, make beep and back speaker to previous mode without wake up all device.
I tried code like this:
Code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using System.Runtime.InteropServices;
namespace TestProject
{
static class Program
{
public const int POWER_NAME = 0x00000001;
public enum DevicePowerState : int
{
Unspecified = -1,
D0 = 0,
D1,
D2,
D3,
D4,
}
[DllImport("coredll.dll", SetLastError = true)]
public static extern int SetDevicePower(
string pvDevice,
int dwDeviceFlags,
DevicePowerState DeviceState
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr SetPowerRequirement(
string device,
DevicePowerState state,
uint deviceFlags,
IntPtr systemState,
ulong stateFlags
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern int ReleasePowerRequirement(IntPtr handle);
[MTAThread]
static void Main()
{
MessageBox.Show("Application is running...", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
string deviceName = "WAV1:"; // speaker
for (; ; )
{
// set D0 power value
IntPtr handle = SetPowerRequirement(deviceName, DevicePowerState.D0, 1, IntPtr.Zero, 0);
// make a beep
SystemSounds.Beep.Play();
// set default power value
ReleasePowerRequirement(handle);
Thread.Sleep(10000);
}
}
}
}
And like this:
Code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using System.Runtime.InteropServices;
namespace TestProject
{
static class Program
{
public const int POWER_NAME = 0x00000001;
public enum DevicePowerState : int
{
Unspecified = -1,
D0 = 0,
D1,
D2,
D3,
D4,
}
[DllImport("coredll.dll", SetLastError = true)]
public static extern int SetDevicePower(
string pvDevice,
int dwDeviceFlags,
DevicePowerState DeviceState
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr SetPowerRequirement(
string device,
DevicePowerState state,
uint deviceFlags,
IntPtr systemState,
ulong stateFlags
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern int ReleasePowerRequirement(IntPtr handle);
[MTAThread]
static void Main()
{
MessageBox.Show("Application is running...", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
string deviceName = "WAV1:"; // speaker
int resDevicePowerOn = SetDevicePower(deviceName, POWER_NAME, DevicePowerState.D0);
for (; ; )
{
// make a beep
SystemSounds.Beep.Play();
Thread.Sleep(10000);
}
}
}
}
But any of these codes does not work - there are no beep in sleep mode.
Hi, I just happened to find an article from codeproject.
You may want to take a look at it.
http://www.codeproject.com/KB/mobile/WiMoPower1.aspx
I think what you need is cerunappattime.
It seems you are enabling the audio device to run in low-power mode, but you are not actually telling the CPU to keep running ("unattended mode").
Lookup PowerPolicyNotify, specifically PPN_UNATTENDEDMODE.
You may also need to periodically call SHIdleTimerResetEx and/or SystemIdleTimerReset to keep the device active in unattended mode or it will still truely suspend.
Prevent the system enter sleep mode
The system will stop all activitis when the system enter sleep mode.So you must prevent the system enter sleep mode.
The system sleep mode:
on -> unattended -> suspend
You can run:
on -> unattended -> resuming
my code:time up is system on
ex file:screenblack.rar
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace ScreenBlack
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//取得系統狀態 Get system state
[DllImport("Coredll.dll", SetLastError = true)]
public static extern int GetSystemPowerState(StringBuilder PowerState, int length, ref int Flags);
//設定系統電源狀態
[DllImport("Coredll.dll")]
public static extern int SetSystemPowerState(int psState, int StateFlags, int Options);
public const int POWER_STATE_ON = 0x12010000;
public const int NULL = 0;
public const int POWER_FORCE = 0x00001000;
private void Form1_Load(object sender, EventArgs e)
{
//設定 timer1 的設定值 0.5 秒 Set timer1 activie in 0.5 second
timer1.Interval = 500;
//啟動定時器 Start timer1
timer1.Enabled = true;
}
//宣告變數判斷是否有改變 suspend 0:沒有改變 1:有改變
int change = 0;
//宣告變數判斷執行秒數 10
int second = 20;
private void timer1_Tick(object sender, EventArgs e)
{
//設定其標為 0
int flags = 0;
//取得系統狀態名稱 on、suspend、unattended、resuming
StringBuilder stb = new StringBuilder(260);
//取得系統狀態 Get Current system state
GetSystemPowerState(stb, stb.Capacity, ref flags);
//判斷目前系統狀態
if (flags.ToString() == "4194304")
{
//改變 unattended 為 resuming Chang unattended into resuming
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Power\State\Suspend", true);
reg.SetValue("Flags", "268435456", RegistryValueKind.DWord);
reg.Close();
//設定 reg 有改變
change = 1;
}
else if (flags.ToString() == "268435456")
{
//秒數減一
second--;
//判斷 second 是否等於零
if (second == 0)
{
//************
// your code
//************
//system on
SetSystemPowerState(NULL, POWER_STATE_ON, POWER_FORCE);
//設定秒數
second = 20;
}
}
else
{
//判斷是否有改變
if (change == 1)
{
//改變 unattended 為 resuming Chang unattended into resuming
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Power\State\Suspend", true);
reg.SetValue("Flags", "2097152", RegistryValueKind.DWord);
reg.Close();
//設定 reg 有改變
change = 0;
//設定秒數
second = 20;
}
}
}
}
}

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

[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?

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