possible interop-lock back door - Windows Phone 7 Development and Hacking

My gift... I discovered this .NET trick 4 years ago that allows execution of preassemblyed machine code in .NET. Someone doing WP7 development may want to see if this trick works in WP7 to bypass the Interop security exception in order to directly call the COM interfaces. Code is VB, sorry. You'll need to translate to C#. Maybe there is a way to use a similar trick in WP7.1.
Code:
Namespace MachineCode
<UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)> _
Public Delegate Sub MachineCodeDelegate(ByVal bufferptr As IntPtr)
<Flags()> _
Friend Enum AllocationTypes As UInteger
Commit = &H1000
Reserve = &H2000
Reset = &H80000
LargePages = &H20000000
Physical = &H400000
TopDown = &H100000
WriteWatch = &H200000
End Enum
<Flags()> _
Friend Enum MemoryProtections As UInteger
Execute = &H10
ExecuteRead = &H20
ExecuteReadWrite = &H40
ExecuteWriteCopy = &H80
NoAccess = &H1
[ReadOnly] = &H2
ReadWrite = &H4
WriteCopy = &H8
GuartModifierflag = &H100
NoCacheModifierflag = &H200
WriteCombineModifierflag = &H400
End Enum
<Flags()> _
Friend Enum FreeTypes As UInteger
Decommit = &H4000
Release = &H8000
End Enum
Public Class CpuId
Public Shared Function CallMachineCode(x86() As Byte, x64() As Byte) As Byte()
Dim buffer(Math.Max(x86.Length, x64.Length) - 1) As Byte
If IntPtr.Size = 4 Then
Dim p As IntPtr = NativeMethods.VirtualAlloc( _
IntPtr.Zero, _
New UIntPtr(CType(x86.Length, UInteger)), _
AllocationTypes.Commit Or AllocationTypes.Reserve, _
MemoryProtections.ExecuteReadWrite)
Try
Marshal.Copy(x86, 0, p, x86.Length)
Dim del As MachineCodeDelegate = CType(Marshal.GetDelegateForFunctionPointer(p, GetType(MachineCodeDelegate)), MachineCodeDelegate)
Dim sourceGCHandle As GCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned)
Dim sourceAddress As Integer = sourceGCHandle.AddrOfPinnedObject.ToInt32
del.Invoke(sourceAddress)
sourceGCHandle.Free()
Finally
NativeMethods.VirtualFree(p, 0, FreeTypes.Release)
End Try
ElseIf IntPtr.Size = 8 Then
Dim p As IntPtr = NativeMethods.VirtualAlloc( _
IntPtr.Zero, _
New UIntPtr(CType(x64.Length, UInteger)), _
AllocationTypes.Commit Or AllocationTypes.Reserve, _
MemoryProtections.ExecuteReadWrite)
Try
Marshal.Copy(x64, 0, p, x64.Length)
Dim del As MachineCodeDelegate = CType(Marshal.GetDelegateForFunctionPointer(p, GetType(MachineCodeDelegate)), MachineCodeDelegate)
Dim sourceGCHandle As GCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned)
Dim sourceAddress As Integer = sourceGCHandle.AddrOfPinnedObject.ToInt32
del.Invoke(sourceAddress)
sourceGCHandle.Free()
Finally
NativeMethods.VirtualFree(p, 0, FreeTypes.Release)
End Try
End If
Return buffer
End Function
#Region "ASM"
Private Shared x86 As Byte() = New Byte() { _
&H53, _
&H31, &HC0, _
&HF, &HA2, _
&H8B, &H44, &H24, &H8, _
&H89, &H18, _
&H89, &H50, &H4, _
&H89, &H48, &H8, _
&H5B, _
&HC3}
'0x53, // push %ebx
'0x31, 0xc0, // xor %eax,%eax
'0x0f, 0xa2, // cpuid
'0x8b, 0x44, 0x24, 0x08, // mov 0x8(%esp),%eax
'0x89, 0x18, // mov %ebx,0x0(%eax)
'0x89, 0x50, 0x04, // mov %edx,0x4(%eax)
'0x89, 0x48, 0x08, // mov %ecx,0x8(%eax)
'0x5b, // pop %ebx
'0xc3 // ret
Private Shared x64 As Byte() = New Byte() { _
&H49, &H89, &HD8, _
&H49, &H89, &HC9, _
&H48, &H31, &HC0, _
&HF, &HA2, _
&H4C, &H89, &HC8, _
&H89, &H18, _
&H89, &H50, &H4, _
&H89, &H48, &H8, _
&H4C, &H89, &HC3, _
&HC3}
'0x49, 0x89, 0xd8, // mov %rbx,%r8
'0x49, 0x89, 0xc9, // mov %rcx,%r9
'0x48, 0x31, 0xc0, // xor %rax,%rax
'0x0f, 0xa2, // cpuid
'0x4c, 0x89, 0xc8, // mov %r9,%rax
'0x89, 0x18, // mov %ebx,0x0(%rax)
'0x89, 0x50, 0x04, // mov %edx,0x4(%rax)
'0x89, 0x48, 0x08, // mov %ecx,0x8(%rax)
'0x4c, 0x89, 0xc3, // mov %r8,%rbx
'0xc3 // retq
#End Region
Private Class NativeMethods
Declare Auto Function VirtualAlloc Lib "kernel32.dll" ( _
ByVal lpAddress As IntPtr, _
ByVal dwSize As UIntPtr, _
ByVal flAllocationType As AllocationTypes, _
ByVal flProtect As MemoryProtections) As IntPtr
'[return: MarshalAs(UnmanagedType.Bool)]
Declare Auto Function VirtualFree Lib "kernel32.dll" ( _
ByVal lpAddress As IntPtr, _
ByVal dwSize As UIntPtr, _
ByVal flFreeType As FreeTypes) As Boolean
End Class
End Class
End Namespace

I don't think it's possible. We can't call native VirtualAlloc function without ComBridge and corresponding permissions.
P.S. Also, your example:
- converted from well known C# source to VB
- uses x86/64 instructions set (WP7 is arm based)

Well, ComBridge doesn't actually require ID_CAP_INTEROPSERVICES. However, all that you're really likely to be able to do with this is the same as can already be done with the DllImport project. Calling native code from managed code in WP7 isn't terribly hard. The problem is, that only gets you out of the API sandbox, not out of the permissions sandbox. WP7 apps run with super-low permissions. The way to get higher permissions is call into a driver/service that is running with more permissions. However, in order to open a handle to one (so you can call into it) you need ID_CAP_INTEROPSERVICES. The call will fail otehrwise, even using native code.

GoodDayToDie said:
Well, ComBridge doesn't actually require ID_CAP_INTEROPSERVICES.
Click to expand...
Click to collapse
Technically you're right but do you have manf's signed dll with COM-bridges to native VirtualAlloc, GlobalAlloc etc.? Please share!
GoodDayToDie said:
The way to get higher permissions is call into a driver/service that is running with more permissions.
Click to expand...
Click to collapse
Probably also (probably 'cause I'm not an expert in SL security nor a black hat ) we can use some "standard" techniques like a stack overflow by calling natives (PocketIE, system media player)... Last year I worked closely with MediaElement (SL wrapper to the system media player) and (mostly at the beginning) I've had a lot of system freezes / reboots by committing wrong/non-expected data to ME (just mark - I worked in SL "protected" (sic!) sand box)

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)

[REF] Compass api on HTC LEO

Use at your own risk!
Code:
/*
HTC HD2 Compass interface
MilaCzeque (at) gmail.com
This program is licensed under the terms of the GNU General Public License (GPL).
*/
#include <windows.h>
#include <service.h>
struct compass_data
{
short x;
short y;
short z;
short angle;
short d;
short dummy[10]; //just to make sure nothing get overwritten
};
struct compass
{
compass_data data;
HANDLE h;
HANDLE service;
int init()
{
h = CreateFile( TEXT( "SEN0:" ), 0, 0, 0, 3, 0x80, 0 );
if( h == INVALID_HANDLE_VALUE || h == 0 )
{
h = 0;
service = RegisterService( TEXT( "SEN" ), 0, TEXT( "HTCSensorService.dll" ), 1 );
if( service == 0 )
{
return 0;
}
h = CreateFile( TEXT( "SEN0:" ), 0, 0, 0, 3, 0x80, 0 );
if( h == INVALID_HANDLE_VALUE || h == 0 )
{
h = 0;
return 0;
}
}
if( 0 == DeviceIoControl( h, 0x3000001, 0, 0, 0, 0, 0, 0 ))
{
CloseHandle( h );
h = 0;
return 0;
}
return true;
}
short update()
{
if( !h )
{
return 0;
}
DWORD read = 0;
if( 0 == DeviceIoControl( h, 0x3000003, 0, 0, &data, 0, &read, 0 ))
{
return 0;
}
else
{
return 1;
}
}
int deinit()
{
if( h )
{
if( 0 == DeviceIoControl( h, 0x3000002, 0, 0, 0, 0, 0, 0 ))
{
CloseHandle( h );
h = 0;
return 0;
}
}
return 1;
}
};
Edit:
Plese do mind that this code is licensed under GPL and so is anything based on it (including C# and VB code in this thread). This means that if you use it in your project you MUST release it under GPL (and with source code).
I'm sick of everyone ignoring this. :-(
Multitouch and the compass at a similar time?
The Leo is definately getting better!
Thanks!
Someone should inform the Layar developers about this.
maati:
Don't think that Layar would agree with GPL.
l3v5y:
It will be even better with FM Radio API working.
I had a play with this, the issue is, at current I haven't found exactly what the "angle" is. Do you know whether it's the angle between the device and North? or the bearing of the device?
It's the same number as you can see in original compass application. Angle between device and magnetic north.
MilaCzeque, thanks a lot the leo is indeed getting better and better!
I don't think you can help with this, but do you have any idea about how we might get hardware compass support in Google Maps, iGO, and other software?
I'd like to refer to this thread by the way. Thx!
Maybe someone can write program which will emulate COM port with nmea from internal gps but with heading from compass.
@MilaCzeque
Hi,
See here: http://forum.xda-developers.com/showthread.php?t=571266
Is it possible to see some sample code written in C# as well ?
Thank you very much.
Thanks!
Anyone managed to get into the proximity sensor?
Great!!!
How can this be used in C# or Vb.net ?
I dont develop in C++ for Windows Mobile.
retrieving capacitive sensor data similar. Hack touch.dll and get DeviceIOControl codes....
Can anybody translate that code in C#?
Better yet, let's make a .net library so its accessible to everyone! l3v5y?
shirreer said:
Better yet, let's make a .net library so its accessible to everyone! l3v5y?
Click to expand...
Click to collapse
That would be the best.
I tried this:
Code:
Imports System.Runtime.InteropServices
Public Class clsCompass
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As System.UInt32, ByVal dwShareMode As System.UInt32, ByVal lpSecurityAttributes As IntPtr, ByVal dwCreationDisposition As System.UInt32, ByVal dwFlagsAndAttributes As System.UInt32, ByVal hTemplateFile As IntPtr) As Integer
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function RegisterService(ByVal lpszType As String, ByVal dwIndex As System.UInt32, ByVal lpszLib As String, ByVal dwInfo As System.UInt32)
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function DeviceIoControl(<[In]()> ByVal hDevice As Integer, <[In]()> ByVal dwIoControlCode As Integer, <[In]()> ByVal lpInBuffer As IntPtr, <[In]()> ByVal nInBufferSize As Integer, <Out()> ByVal lpOutBuffer As IntPtr, <[In]()> ByVal nOutBufferSize As Integer, <Out()> ByRef lpBytesReturned As Integer, <[In]()> ByVal lpOverlapped As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Const DIO_INIT As Int32 = &H3000001
Const DIO_READ As Int32 = &H3000003
Const DIO_QUIT As Int32 = &H3000002
Const INVALID_HANDLE_VALUE As Int64 = -1
Structure compass_data
Public x As Short
Public y As Short
Public z As Short
Public angle As Short
Public d As Short
Public dummy As String
End Structure
Private devHandle As Integer
Private srvHandle As Integer
Public compassData As New compass_data
Public Function initCompass()
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then
devHandle = 0
srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1)
If srvHandle = 0 Then Return False
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then Return False
End If
If DeviceIoControl(devHandle, DIO_INIT, 0, 0, 0, 0, 0, 0) = 0 Then Return False
Return True
End Function
Public Function updateData()
Dim readBytes As System.UInt32
If devHandle = 0 Then Return False
If DeviceIoControl(devHandle, DIO_READ, 0, 0, compassData, 0, readBytes, 0) = 0 Then
Return False
Else
Return True
End If
End Function
Public Function shutdownCompass()
If devHandle <> 0 Then
If DeviceIoControl(devHandle, DIO_QUIT, 0, 0, 0, 0, 0, 0) = 0 Then
Return False
Else
Return True
End If
End If
Return True
End Function
End Class
However, this does not compile:
Error 2 Value of type 'GPSLib.clsCompass.compass_data' cannot be converted to 'System.IntPtr'. C:\Dokumente und Einstellungen\Marco\Eigene Dateien\Visual Studio 2008\Projects\GPSLib\GPSLib\clsCompass.vb 44 55 GPSLib
I have no idea how to convert this instance of a struct to a int pointer... any ideas??
Solved that one. Now during run w/ this code, I get a NotSupported exception in updateData():
Code:
Imports System.Runtime.InteropServices
Public Class clsCompass
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As System.UInt32, ByVal dwShareMode As System.UInt32, ByVal lpSecurityAttributes As IntPtr, ByVal dwCreationDisposition As System.UInt32, ByVal dwFlagsAndAttributes As System.UInt32, ByVal hTemplateFile As IntPtr) As Integer
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function RegisterService(ByVal lpszType As String, ByVal dwIndex As System.UInt32, ByVal lpszLib As String, ByVal dwInfo As System.UInt32)
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function DeviceIoControl(<[In]()> ByVal hDevice As Integer, <[In]()> ByVal dwIoControlCode As Integer, <[In]()> ByRef nInputBuffer As Integer, <[In]()> ByVal nInBufferSize As Integer, <Out()> ByVal lpOutBuffer As compass_data, <[In]()> ByVal nOutBufferSize As Integer, <Out()> ByRef lpBytesReturned As Integer, <[In]()> ByVal lpOverlapped As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function DeviceIoControl(<[In]()> ByVal hDevice As Integer, <[In]()> ByVal dwIoControlCode As Integer, <[In]()> ByRef nInputBuffer As Integer, <[In]()> ByVal nInBufferSize As Integer, <Out()> ByVal lpOutBuffer As Integer, <[In]()> ByVal nOutBufferSize As Integer, <Out()> ByRef lpBytesReturned As Integer, <[In]()> ByVal lpOverlapped As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Const DIO_INIT As Int32 = &H3000001
Const DIO_READ As Int32 = &H3000003
Const DIO_QUIT As Int32 = &H3000002
Const INVALID_HANDLE_VALUE As Int64 = -1
Structure compass_data
Public x As Short
Public y As Short
Public z As Short
Public angle As Short
Public d As Short
Public dummy As String
End Structure
Overrides Function toString() As String
Return "X: " + compassData.x + vbNewLine _
+ "X: " + compassData.x + vbNewLine _
+ "Y: " + compassData.y + vbNewLine _
+ "Z: " + compassData.z + vbNewLine _
+ "a: " + compassData.angle + vbNewLine _
+ "d: " + compassData.d + vbNewLine
End Function
Private devHandle As Integer
Private srvHandle As Integer
Public compassData As New compass_data
Public Function initCompass()
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then
devHandle = 0
srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1)
If srvHandle = 0 Then Return False
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then Return False
End If
If DeviceIoControl(devHandle, DIO_INIT, 0, 0, 0, 0, 0, 0) = 0 Then Return False
Return True
End Function
Public Function updateData()
Dim readBytes As System.UInt32
If devHandle = 0 Then Return False
If DeviceIoControl(devHandle, DIO_READ, 0, 0, compassData, 0, readBytes, 0) = 0 Then
Return False
Else
Return True
End If
End Function
Public Function shutdownCompass()
If devHandle <> 0 Then
If DeviceIoControl(devHandle, DIO_QUIT, 0, 0, 0, 0, 0, 0) = 0 Then
Return False
Else
Return True
End If
End If
Return True
End Function
End Class
System.NotSupportedException was unhandled
Message="NotSupportedException"
StackTrace:
bei GPSLib.clsCompass.updateData() bei GPSLib.frmMain.Timer1_Tick(Object sender, EventArgs e) bei System.Windows.Forms.Timer._WnProc(WM wm, Int32 wParam, Int32 lParam) bei System.Windows.Forms.ApplicationThreadContext._InternalContextMessages(WM wm, Int32 wParam, Int32 lParam) bei Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain) bei System.Windows.Forms.Application.Run(Form fm) bei GPSLib.frmMain.Main()
InnerException:
Finally finished
FINALLY!
I am not sure about the meaning of the data returned however.
Code:
Imports System.Runtime.InteropServices
Public Class clsCompass
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Public Shared Function CreateFile _
(ByVal lpFileName As String, _
ByVal dwDesiredAccess As Integer, _
ByVal dwShareMode As Integer, _
ByVal lpSecurityAttributes As IntPtr, _
ByVal dwCreationDisposition As Integer, _
ByVal dwFlagsAndAttributes As Integer, _
ByVal hTemplateFile As IntPtr) As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Shared Function RegisterService _
(ByVal lpszType As String, _
ByVal dwIndex As Integer, _
ByVal lpszLib As String, _
ByVal dwInfo As Integer) As Integer
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Shared Function LocalAlloc _
(ByVal uFlags As Integer, _
ByVal uBytes As Integer) As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Shared Function LocalFree _
(ByVal hMem As IntPtr) As IntPtr
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> _
Public Shared Function DeviceIoControl _
(<[In]()> ByVal hDevice As IntPtr, _
<[In]()> ByVal dwIoControlCode As Integer, _
<[In]()> ByVal lpInputBuffer As IntPtr, _
<[In]()> ByVal nInBufferSize As Integer, _
<Out()> ByVal lpOutBuffer As IntPtr, _
<[In]()> ByVal nOutBufferSize As Integer, _
<Out()> ByRef lpBytesReturned As Integer, _
<[In]()> ByVal lpOverlapped As IntPtr) As Integer
End Function
Const DIO_INIT As Int32 = &H3000001
Const DIO_READ As Int32 = &H3000003
Const DIO_QUIT As Int32 = &H3000002
Const INVALID_HANDLE_VALUE As Int64 = -1
Const LMEM_FIXED = &H0
Const LMEM_ZEROINIT = &H40
Const LPTR = (LMEM_FIXED Or LMEM_ZEROINIT)
Structure compass_data
Public x As Short
Public y As Short
Public z As Short
Public angle As Short
Public d As Short
Public dummy As String
End Structure
Public rdBuf(8) As Byte
Overrides Function toString() As String
Return _
"X: " + rdBuf(0).ToString + vbNewLine _
+ "Y: " + rdBuf(1).ToString + vbNewLine _
+ "Z: " + rdBuf(2).ToString + vbNewLine _
+ "a: " + rdBuf(3).ToString + vbNewLine _
+ "d: " + rdBuf(4).ToString + vbNewLine
End Function
Private devHandle As IntPtr
Private srvHandle As Integer
Public compassData As New compass_data
Public Function initCompass()
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle.ToInt32 = INVALID_HANDLE_VALUE Or devHandle.ToInt32 = 0 Then
devHandle = IntPtr.Zero
srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1)
If srvHandle = 0 Then Return False
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle.ToInt32 = INVALID_HANDLE_VALUE Or devHandle.ToInt32 = 0 Then Return False
End If
If DeviceIoControl(devHandle, DIO_INIT, 0, 0, 0, 0, 0, 0) = 0 Then Return False
Return True
End Function
Public Function updateData()
' Dim readBytes As Integer
Dim buf(8) As Byte
Dim result As Integer
Dim getMemory As New IntPtr()
If devHandle = 0 Or devHandle = IntPtr.Zero Then Return False
getMemory = LocalAlloc(LPTR, buf.Length)
Marshal.Copy(buf, 0, getMemory, buf.Length)
result = DeviceIoControl(devHandle, DIO_READ, IntPtr.Zero, 0, getMemory, buf.Length, 0, IntPtr.Zero)
Marshal.Copy(getMemory, buf, 0, buf.Length)
If getMemory <> IntPtr.Zero Then LocalFree(getMemory)
If result = 0 Then
Return False
Else
rdBuf = buf
Return True
End If
End Function
Public Function shutdownCompass()
If devHandle <> 0 Then
If DeviceIoControl(devHandle, DIO_QUIT, 0, 0, 0, 0, 0, 0) = 0 Then
Return False
Else
Return True
End If
End If
Return True
End Function
End Class
Almost there...
Mapping your buffer to short[5] gives me a fair compass heading in number 4. No idea what 1..3 are, they seem to react to the device's orientation (GSensor?)
Here's the C# code (convert it back to VB with Red-Gate's .NET Reflector if you wish):
using System;
using System.Runtime.InteropServices;
namespace Sensors
{
public interface ICompass
{
/// <summary>
/// Compass heading.
/// </summary>
double Angle { get;}
/// <summary>
/// Angle is valid
/// </summary>
bool IsValid { get;}
/// <summary>
/// Start compass sensor
/// </summary>
void Start();
/// <summary>
/// Stop compass sensor
/// </summary>
void Stop();
/// <summary>
/// Reset compass sensor
/// </summary>
void Reset();
}
public class HTCCompass:ICompass
{
private IntPtr devHandle;
private int srvHandle;
public short[] buffer = new short[5];
#region ICompass
public double Angle
{
get
{
// try to connect if necessary
if(!ready) ready = initCompass();
return ready && updateData() ? buffer[3] : -1.0;
}
}
bool ready = false;
public bool IsValid { get { return ready; } }
public void Start() { ready = initCompass(); }
public void Stop() { shutdownCompass(); ready = false; }
public void Reset() { Stop(); Start(); }
#endregion
private const int DIO_INIT = 0x3000001;
private const int DIO_QUIT = 0x3000002;
private const int DIO_READ = 0x3000003;
private const long INVALID_HANDLE_VALUE = -1L;
//private const int LMEM_FIXED = 0;
//private const int LMEM_ZEROINIT = 0x40;
//private const int LPTR = 0x40;
public bool initCompass()
{
if (this.devHandle != IntPtr.Zero)
return true;
this.devHandle = CreateFile("SEN0:", 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
if ((this.devHandle.ToInt32() == INVALID_HANDLE_VALUE) | (this.devHandle.ToInt32() == 0))
{
this.devHandle = IntPtr.Zero;
this.srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1);
if (this.srvHandle == 0)
return false;
this.devHandle = CreateFile("SEN0:", 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
if ((this.devHandle.ToInt32() == INVALID_HANDLE_VALUE) | (this.devHandle.ToInt32() == 0))
return false;
}
int read = 0;
if (DeviceIoControl(this.devHandle, DIO_INIT, IntPtr.Zero, 0, IntPtr.Zero, 0, out read, IntPtr.Zero) == 0)
return false;
return true;
}
public bool shutdownCompass()
{
if (this.devHandle != IntPtr.Zero)
{
int read = 0;
if (DeviceIoControl(this.devHandle, DIO_QUIT, IntPtr.Zero, 0, IntPtr.Zero, 0, out read, IntPtr.Zero) == 0)
return false;
this.devHandle = IntPtr.Zero;
}
return true;
}
public override string ToString()
{
return ("X: " + buffer[0].ToString() +
"\r\nY: " + buffer[1].ToString() +
"\r\nZ: " + buffer[2].ToString() +
"\r\nA: " + buffer[3].ToString() +
"\r\nS: " + buffer[4].ToString() +
"\r\n");
}
public bool updateData()
{
byte[] buf = new byte[10];
IntPtr getMemory = new IntPtr();
if ((this.devHandle == IntPtr.Zero) | (this.devHandle == IntPtr.Zero))
{
return false;
}
getMemory = LocalAlloc(0x40, buf.Length);
Marshal.Copy(buf, 0, getMemory, buf.Length);
int read = 0;
int result = DeviceIoControl(this.devHandle, DIO_READ, IntPtr.Zero, 0, getMemory, buf.Length, out read, IntPtr.Zero);
Marshal.Copy(getMemory, buf, 0, buf.Length);
if (getMemory != IntPtr.Zero)
{
LocalFree(getMemory);
}
if (result == 0)
{
return false;
}
Buffer.BlockCopy(buf, 0, buffer, 0, buf.Length);
return true;
}
# region PInvokes
[DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LocalAlloc(int uFlags, int uBytes);
[DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int RegisterService(string lpszType, int dwIndex, string lpszLib, int dwInfo);
[DllImport("coredll.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("coredll.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern int DeviceIoControl([In] IntPtr hDevice, [In] int dwIoControlCode, [In] IntPtr lpInputBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);
#endregion
}
}

Webclient Help

how do i replicate this under windows mobile. The first function works flawlessly however the second version (Which is required to run on windows mobile 6.1-6.5) doesn't.. If anyone has any idea how to fix it i'm willing to try it out.
Thanks
Code:
private static byte[] WebPost(string url, byte[] data)
{
var webClient = new WebClient();
return webClient.UploadData(url, data);
}
This dont.
Code:
private static byte[] WebPost(string url, byte[] data)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Timeout = 10000; // 10 secs
request.Method = "POST";
byte[] requestPostBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(ByteArrayToStr(data));
request.ContentLength = requestPostBuffer.Length;
Stream requestPostData = request.GetRequestStream();
requestPostData.Write(requestPostBuffer, 0, requestPostBuffer.Length);
requestPostData.Close();
// initialize the httpweresponse object
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
// set our encoding
Encoding enc = System.Text.Encoding.GetEncoding(1252);
//initialis the webresponse stream with our encoding
StreamReader webResponseStream = new StreamReader(webResponse.GetResponseStream(),enc);
// create a string to copy it all into.
string streamedData = webResponseStream.ReadToEnd();
webResponse.Close();
webResponseStream.Close();
byte[] convertedResponse = StrToByteArray(streamedData);
convertedResponse = Encoding.Convert(System.Text.Encoding.Default, Encoding.GetEncoding(1252),convertedResponse);
return convertedResponse;
}

[Q] LINQ to XML - NULL value in SELECT

Hi, I have the following code, where one element can be NULL.
Code:
Select New Class_Data_Inventory With {.PARTS_AC = CDbl(Data_Inventory.Element("PARTS_AC").Value), _
.PARTS_COMPANY = Data_Inventory.Element("PARTS_COMPANY").Value, _
.PARTS_DIAM = CDbl(Data_Inventory.Element("PARTS_DIAM").Value), _
[B][COLOR="Red"].PARTS_LENGTH = CDbl(If(Data_Inventory.Element("PARTS_LENGTH").Value Is Nothing, Data_Inventory.Element("PARTS_LENGTH").Value, "0")), [/COLOR][/B]_
.PARTS_NAME = Data_Inventory.Element("PARTS_NAME").Value, _
.PARTS_SD = CDbl(Data_Inventory.Element("PARTS_SD").Value), _
.PARTS_STOCK = Data_Inventory.Element("PARTS_STOCK").Value, _
.PARTS_TYPE = Data_Inventory.Element("PARTS_TYPE").Value}).ToList()
My question is, how can I handle the NULL value, and assing a 0 to that element?
So far, no luck!
In the code, I tried the IF clause, but doesn't work at all...
the .PARTS_LENGTH element is defined as DOUBLE and is the value I'd like to make 0 if it's NULL.
Any help is much appreciated in advance.
Code:
Select New Class_Data_Inventory With {.PARTS_AC = CDbl(Data_Inventory.Element("PARTS_AC").Value), _
.PARTS_COMPANY = Data_Inventory.Element("PARTS_COMPANY").Value, _
.PARTS_DIAM = CDbl(Data_Inventory.Element("PARTS_DIAM").Value), _
[B][COLOR="Red"].PARTS_LENGTH = CDbl(If(Data_Inventory.Element("PARTS_LENGTH") Is Nothing, "0", Data_Inventory.Element("PARTS_LENGTH").Value)), [/COLOR][/B]_
.PARTS_NAME = Data_Inventory.Element("PARTS_NAME").Value, _
.PARTS_SD = CDbl(Data_Inventory.Element("PARTS_SD").Value), _
.PARTS_STOCK = Data_Inventory.Element("PARTS_STOCK").Value, _
.PARTS_TYPE = Data_Inventory.Element("PARTS_TYPE").Value}).ToList()
Does taking the .Value off the line fix it?
And swap the order of the If: If...Expression...When true...When false
So for your example it would be:
If...Is nothing...Then 0...Else Value
My VB.Net is a tad rusty
Dave
Use HasElement
Presumably you're using an xelement object, if so check out HasElement
CDbl(If(Data_Inventory.HasElement("PARTS_LENGTH"), Data_Inventory.Element("PARTS_LENGTH").Value, "0")), _
Also I'd recommend putting the logic in it's in it's own method
antonydenyer said:
Presumably you're using an xelement object, if so check out HasElement
CDbl(If(Data_Inventory.HasElement("PARTS_LENGTH"), Data_Inventory.Element("PARTS_LENGTH").Value, "0")), _
Also I'd recommend putting the logic in it's in it's own method
Click to expand...
Click to collapse
Thanks for the answer but it doesn't work.
.HasElements is not part of an XElement.
If you have any other idea, please let me know.
Hi,
Have you tried:
.PARTS_LENGTH = If(Data_Inventory.Elements("PARTS_LENGTH").Any(), Data_Inventory.Element("PARTS_LENGTH").Value, "0")
Excuse the VB.net it's been a while
Hope it helps.
Kong
Hi, thanks for the answer!
Will try it out and let you know how it's working.

[Q] How to convert IR Pattern from Android ~4.4.2 to 4.4.3

Is there a way to convert a IR pattern from a Android ~4.4.2 to 4.4.3 compatible pattern.
Here is a example how they look like
Code:
private static final int SAMPLE_FREQ = 38400;
private static final int[] IR_SIGNAL_PULSE_COUNT = {171,171,22,64,22,64,22,64,22,21,22,21,22,21,22,21,22,21,22,64,22,64,22,64,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,64,22,21,22,21,22,21,22,21,22,21,22,64,22,64,22,21,22,64,22,64,22,64,22,64,22,64,22,876};
private static final int[] IR_SIGNAL_TIME_LENGTH = {4499,4499,578,1683,578,1683,578,1683,578,552,578,552,578,552,578,552,578,552,578,1683,578,1683,578,1683,578,552,578,552,578,552,578,552,578,552,578,552,578,552,578,1683,578,552,578,552,578,552,578,552,578,552,578,1683,578,1683,578,552,578,1683,578,1683,578,1683,578,1683,578,1683,578,23047};
I'm getting a close but not perfect result with this..
Code:
private int[] toCompIR(IrDataCompat data){
int inUs = 1000000/data.getFrequency();
int[] frame = data.getFrame();
int[] arrayOfInt = new int[-1 + frame.length];
for (int j = 1; j < frame.length; j++)
arrayOfInt[(j - 1)] = frame[(j - 1)] * inUs;
return arrayOfInt;
}

Categories

Resources