The DllImport Project (+/also C++ Wrapper) [Mango Support] - Windows Phone 7 Development and Hacking

The DllImport Project
This project is part "Real DllImport" and also not the same time. It has limited DllImport to only types "void();" (well isn't that DllImport )
Other CORE functions that require multiple [IN] or/and [OUT] are to complex for the code right now (there are so many possibilities).
Terms of use, using the code (free to use, under my name "fiinix00 @ XDA"~ in app)
As posted to JaxBot
Well thanks for asking, this project is free for everyone, the one purpose it was made for.
The only thing i needed back is my name (fiinix @ XDA) included in whose projects (external) that take use of my code base. There is no licence or something (GNU e.g.), it just make people mad and confused.
So feel free to take advantage of the code whenever you want, just remember, i want my name on it. =D
Click to expand...
Click to collapse
UPDATE @ (2011y-03m-26d - 23:08)
Ohyeah, i can control zune from my application (Resume, Stop, Pause, NextSong, PrevSong, ShutdownZune, StartZune, ... to come)
Turn on/off radio remote from code. (DAMN, the radio begins to play without "No antenna" but no sound, plugin again and it sounds :/)
UPDATE @ (2011-03-27 - 14:35)
- Set clipboard (lol, doesent even have NODO): DllImportCaller.lib.Clipboard_SET("Hello");
- Get clipboard: DllImportCaller.lib.Clipboard_GET(ref [string]);
- Enchanted: Phone.Clipboard.Value { get { ... } set { ... } }
- Basic calls against void without arguments: DllImportCaller.lib.VoidCall( [DLL] , [Method] );
- API for verifying method existence: DllImportCaller.NativeMethodExists( [DLL] , [Method] );
- Raw API for controlling vibrator (unlimited "on", also continues to vibrate on exit, dont forget to turn off ): Phone.Vibrator. { Vibrate(), Stop() }
Source code + test XAP updated (2011-03-27-17:38) (Clipboard GET; is corrupt)
HELLO THERE TASKMANAGER!!
(I can now enumerate the running processes on the phone )
Proof: http://moitox.com/WP7tskMngr.png
Hook to keyboard, for some reason it only show interest in the "Search" button.
Documentation of proc:
[WP7Process].{ CreationTime, ExitTime, KernelTime, UserTime, <-UpdateTimes(), Kill(exitCode), { PROCESSENTRY32 RAW } }
^ for "currentProcess.Kill()" use "Phone.TaskManager.GentlyExitCurrentProcess();" the Kill(exitCode) KILLS
WP7Process[] = Phone.TaskManager.Named("taskhost");
WP7Process = Phone.TaskManager.CurrentProcess();
Documentation of network
- ConnectionType { Unk0, Unk1, Unk2, Connected, Unk3 ... }
- ConnectionType = Phone.Network.GetWirlessState;
Phone.KeyboardHook.IsKeyDown(int key)
> Search = 124 (lol)
Misc finds
DllImportCaller.NativeMethodExists("urlmon", "IsIntranetAvailable");
DllImportCaller.NativeMethodExists("urlmon", "ObtainUserAgentString");
- Code updated! (2011-03-28-22:12)
Added "Phone.DEP", dep is a wrapper against info stored in "Microsoft.Phone.Info.DeviceExtendedProperties"
Full "TaskHost.exe" support
HostInformation = Phone.TaskHost.GetCurrenHostInfo();
HostInformation {
fDehydrating = 0,
fRehydrated = 0,
hHostWnd = -25821178 /* This silverlight managed window (host window) */
szAppDataFolder = "\\Applications\\Data\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Data"
szAppInstallFolder = "\\Applications\\Install\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Install"
szAppIsolatedStorePath = "\\Applications\\Data\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Data\\IsolatedStore"
szProductId = "{8DC5214E-88FA-4C2D-A379-2CD74FE24B72}"
szTaskPage = "MainPage.xaml" /* Current page? */
szUri = "app://8DC5214E-88FA-4C2D-A379-2CD74FE24B72/_default"
ullLastInstanceId = 39 /* fully retarded property? */
}
Code updated! (2011-03-29-23:25)
new Phone functionality
Phone.OS.{ Shutdown(ewxCode) } /* 1.0.2 can still call it with "DllImportCaller.lib.ShutdownOS" (failed tho on mine in 1.0.2) */
Added "GetLastError7" (C++ ::GetLastError()) for better C# side error handling.
Code updated! (2011-04-03-12:37)
Code updated! (2011-04-04-21:48)
- App launcher code!!
- Enchanted IO support
- 1.0.6!
Code updated! (2011-04-05-22:08)
- Enchanted task support
- Console7.Title { get; set; } etc.
Code updated! (2011-04-08-00:03)
- Stable%: 97 :/
- Battery support (see battery info (CORE only))
- Phone.Sound { MasterVolume!! { get; set; }, etc } (controlling phone master volume over all processes)
- Phone.OS.Kernel.ResetDevice(); (instant stops kernel, instant shutdown, not recommended!)
Code updated! (2011-04-09-22:39)
- Enchanted "Phone.Battery" class
- Phone.TaskManager.+GetCurrentProcessId
- WiFi Controll! (On/Off) (from code!)
- Bluetooth Controll! (On/Off) (from code here toe!)
- Phone.OS.+GetSystemStartupItems(),+GetDesktopWindowHandle()
- New class "Phone.Search."+SearchFor,+OpenSearch,+BindSearchButtonToPage (FAILS)
- New class "Phone.XboxLive"+GetIsXboxLiveEnable,+GetIsSignedIn
- Yep: 1.0.9!
Code updated! (2011-04-17-22:01) //damn, not update in 8 days~
- Phone.OS.OSLanguage { SubLanguageID, PrimaryLanguageID }
- Phone.WP7Process.+ CurrentProcessID (int),+GetCurrentProcess() returns guaranteed the right taskhost @class_WP7Process
- Improved Phone.OS.Memory
- + Extra i don't remember (8 days)
Code updated! (2011-05-22-21:25)
- 1.2.1 (because 1.2 methods was commented out to set things right (less crash))
- HUGE improvements
- Removed unneeded **** to speed things up
- Screenshot 161 ms per capture (non-save-to-gallery) =D
- =D
Mango support added(2011-10-26-19:30)
- yep, "ATL" Mango compiled. I have not yet tested to run it on a NoDo.
- Trying to implement a ASM virtual machine; example:
Code:
[ASMMethod(Dll = "coredll", EntryPoint = "GetLastError")]
public delegate int GetLastError();
var last = ASMGenerator.GenerateDelegateFor<GetLastError>();
int code = last();
Custom tile support added(2011-11-07-23:08)
- Custom core tiles ftw!
[/CODE]
Source: Attatchment
-Compile VS2008 folder with C++ compiler from WM6 SDK
-Windows Mobile SDK 6 PRO
-Visual Studio 2010 (+ WP7 Silverlight SDK)
Test-app: Attatchment
-Deploy
-No need anymore to do a initialize button call, automatic called on first use in code "DllImportcaller.lib.cctor" by JIT (Net Framework just in time).
-Do some tests from the scrolling list. (due there are more CORE back-code API's than buttons, all tests can not be tested).
OLDER VERSIONS WILL BE DEPRECATED AND WILL BE REPLACED BY NEWER, MAX ATTACHMENTS IS 8.

fiinix said:
Searched for dllimport but did not found what i was searching for; so i need to ask about if it is possible to do a dllimport with interop in meta?
Because if not, i think i have found something quite the same without dllimport.
Click to expand...
Click to collapse
We can't p/invoke, but only use COM interfaces to interop with native code. What did you find?

Im trying the method, of c++ calling the calls for me.
In c++ i call "HMODULE dll = LoadLibrary("MyDLL.dll");" to get the native kerner32.dll e.g.
Then call "Dword addr = GetProcAddress(dll, "MyMethod");"
Code:
typedef HRESULT (STDAPICALLTYPE * LPFNBOX) (void);
C# -> COM (LoadLibrary e.g.) ->
return dll addr -> return to C#
C# -> COM -> LPFNBOX * val = (LPFNBOX)GetProcAddress(addr, "method"); ->
return val(); ->
return to C#
May work with some privileges bypass, not tested. (^ Not programmer, skip it)

Step 1 of 2 "LoadLibrary7" S_OK (success!)

int result;
var hr = lib.MessageBox7("lpText", "lpCaption", MB.MB_OK, out result);
And: It shows a native msg box

It ** worked!
var t = DllImportCaller.Call<string, string>("coredll.dll", "CeRunAppAtEvent", "emptyArgs");
LoadLibrary7( .. "coredll.dll" .. ) @ -1304248592
GetProcAddress7( .. CeRunAppAtEvent" .. ) @ 1105512120
Now just "box" and call it

Sounds sweet. Any code to share?

kuerbis2 said:
Sounds sweet. Any code to share?
Click to expand...
Click to collapse
Well, last step now is to box it. Due "Compact Framework 3.7" there is no "Marshal.GetDelegateForFunctionPointer". But iw found something quite common.
Code, yes. (if i succeed)

Well, there we go. I did just shut down the phone with code (phone sided code)!
DllImportCaller.lib.ShutdownOS();

nevermind.

So you wrapped LoadLibrary/GetProcAddress via C++/COM, how is this any different than what we have now? It's easier to simply write C++ code and provide a calling mechanism. (Which is what we're doing.)

WithinRafael said:
So you wrapped LoadLibrary/GetProcAddress via C++/COM, how is this any different than what we have now? It's easier to simply write C++ code and provide a calling mechanism. (Which is what we're doing.)
Click to expand...
Click to collapse
The use of dllimports (gdiplus.dll located in "\Windows\" for example) in C# code. And you dont need to know c++/programmer to call c++ methods anymore.

The last annoying, to get that IntPtr (native) to become a managed method... (it is possible). Anyways its going great, i'll continue tomorrow

Hey any code on this?

Flow WP7 said:
Hey any code on this?
Click to expand...
Click to collapse
Very soon (today @ Central European Time, dinner). Due im currently at work. The preview will not do all the way down to dllimport because the last thing for me is to figure out how to call the native IntPtr from c# with c# arguments.
Glad you guys are asking

Yeah, would be really cool if thats possible, then it would be possible todo everything over mscoree.dll, i guess?!
I found something intresting myself yesterday, the mscorlib.dll and System.dll on the phone are different from the ones in the sdk. (They contain a lot more stuff) Also the the mscorlib contains DllImports for almost everything.
If there is some way to get an internal class that would be also a great alternative...

Flow WP7 said:
Yeah, would be really cool if thats possible, then it would be possible todo everything over mscoree.dll, i guess?!
I found something intresting myself yesterday, the mscorlib.dll and System.dll on the phone are different from the ones in the sdk. (They contain a lot more stuff) Also the the mscorlib contains DllImports for almost everything.
If there is some way to get an internal class that would be also a great alternative...
Click to expand...
Click to collapse
Internal's -> typeof(CLASS).GetMethod( ... ).Invoke( ... ). Works perfect with </Interop> in manifest. Else "MethodAccessException".
And all those dllimports in mscore, plenty of them, most doing calls to mscoree
Goad is to do "DllImportCaller.Call( DLL, METHOD, ARGS )"~

I just tried this:
Type type = Type.GetType("System.PInvoke.PAL");
Type type1 = Type.GetType("System.Host.HostNative+FIND_DATA");
object createInstance = Activator.CreateInstance(type1);
And this results into MethodAccessException
I have a WPInteropManifest.xml, so what do you mean by:
Works perfect with </Interop> in manifest. Else "MethodAccessException".
Click to expand...
Click to collapse
regards,
Flow

Flow WP7 said:
I just tried this:
Type type = Type.GetType("System.PInvoke.PAL");
Type type1 = Type.GetType("System.Host.HostNative+FIND_DATA");
object createInstance = Activator.CreateInstance(type1);
And this results into MethodAccessException
I have a WPInteropManifest.xml, so what do you mean by:
regards,
Flow
Click to expand...
Click to collapse
This is going kind of off topic. Stay to topic.
Anyways, Activaror.CreateInstance cannot create internal constructots, you need TYPE.GetConstructor( ... ).Invoke. Check visibility of ctor.

fiinix said:
The last annoying, to get that IntPtr (native) to become a managed method... (it is possible). Anyways its going great, i'll continue tomorrow
Click to expand...
Click to collapse
Having some difficulties (its killing itself on call) :/ Ill publish as fast as possible.

Related

Help me understand C++ code with notifications (beers offered)

Hi,
I need to use the C++ version of this. The code should gather information and show this in a notification.
The notification works but I want to receive the choice the user made in the html form.
I know I need to use the hwsink, a message map, and some events but cannot find info (book, example, etc.) how.
Could some one finish this code so I can test what has been chosen. If NOT, please give me an C++ example from which I can learn/copy. I have been searching on google for days now
Thx, for your help
BTW:
I started with this http://www.krvarma.com/?p=146 downloaded code but was a bit to complicated. In it is all I need but i would like it to be in 1 cpp file.
I'm offering 2 beers if you have the solution
Code:
#include "stdafx.h"
#include <stdlib.h>
#include "resource.h"
// {4E8A9888-D15C-4395-9C9A-B4B572F20081}
static const GUID NOTIFICATION_GUID =
{ 0x4e8a9888, 0xd15c, 0x4395, { 0x9c, 0x9a, 0xb4, 0xb5, 0x72, 0xf2, 0x0, 0x81 } };
int _tmain(int argc, _TCHAR* argv[])
{
SHNOTIFICATIONDATA stcNtData = {0};
stcNtData.cbStruct = sizeof(stcNtData);
stcNtData.dwID = 1;
stcNtData.npPriority = SHNP_INFORM;
stcNtData.csDuration = 15;
// stcNtData.hicon = LoadIcon((HINSTANCE)GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON2));
stcNtData.clsid = NOTIFICATION_GUID;
//What todo here... stcNtData.hwndSink = hWnd;
stcNtData.grfFlags = SHNF_SILENT | SHNF_TITLETIME | SHNF_CRITICAL | SHNF_FORCEMESSAGE;
stcNtData.pszTitle = L"ReRemind";
//stcNtData.pszHTML = TEXT("<html><body>This is a sample application to show the SHNotificationAdd API")
// TEXT("<p><b>This line should be bold</b>.<br><i>This one should be italics.</i><br>")
// TEXT("This is a line with a <a href='cmd:10000'>link</a></p>")
// TEXT("<p>This is a line with <input type='button' name='cmd:10001' value='Click'></p><br><br><br><br>");
stcNtData.pszHTML = TEXT("<form method='get' action='TestBubble://Test'>")
TEXT("<table width=100% cellspacing=0 cellpadding=0>")
TEXT("<tr><td colspan=2>")
TEXT("<b>Choose a fruit:</b><p>")
TEXT("<input type='radio' value='0' id='Apples' checked name='Fruit'><label for='Apples'>Apples</label><br>")
TEXT("<input type='radio' value='1' id='Oranges' name='Fruit'><label for='Oranges'>Oranges</label></p></td><td>")
TEXT("<input type='submit' value='Submit' name='Submit'>")
TEXT("</td></tr><tr><td width=42>")
TEXT("<a href='cmd:12288'>Settings</a></td></tr></table></form><br><br><br><br>");
SHNotificationAdd(&stcNtData);
Sleep(15000);
SHNotificationRemove(&NOTIFICATION_GUID, 1);
return 0;
}
I'm offering beers now. No need to finish it, just give me some hints
Hi,
as I understand your article (http://www.krvarma.com/?p=146)
you need to create window, then assign it's HWND
to SHNOTIFICATIONDATA member HWND hwndSink;
then "The system will send WM_COMMAND with wParam set to 1000 to the hwndSink window." so - you need to handle WM_COMMAND in your window and check wParam - if it is equal to your parameter, then this message means "system sends you user choice from your html".
serfer222 said:
Hi,
as I understand your article (http://www.krvarma.com/?p=146)
you need to create window, then assign it's HWND
to SHNOTIFICATIONDATA member HWND hwndSink;
then "The system will send WM_COMMAND with wParam set to 1000 to the hwndSink window." so - you need to handle WM_COMMAND in your window and check wParam - if it is equal to your parameter, then this message means "system sends you user choice from your html".
Click to expand...
Click to collapse
Exactly as i understand it.
So I tried copying code from that article into my code but got stuck with really not understandable compiler errors. I think I need to find a good book explaining this message map.
The first thing I do not understand is that I only want to show the notification bubble (is working). If I create a windows handle (how?) will this overwrite the current screen (this is something I do not want).
window can be invisible.
I'm Win32 programmer, and I don't know exactly about WinCE.
If you are using VisualC++, I think you should use MFC, it's very easy to create window and then create message handler for this window.
search google for some
"WinCE c++ tutorial" and you will find how to create window and setup message loop. (add "Hello world" phrase to your search - this is usually used as very first example)
for example: http://www.codeproject.com/KB/mobile/ltwtdlg.aspx
serfer222 said:
window can be invisible.
I'm Win32 programmer, and I don't know exactly about WinCE.
If you are using VisualC++, I think you should use MFC, it's very easy to create window and then create message handler for this window.
search google for some
"WinCE c++ tutorial" and you will find how to create window and setup message loop. (add "Hello world" phrase to your search - this is usually used as very first example)
for example: http://www.codeproject.com/KB/mobile/ltwtdlg.aspx
Click to expand...
Click to collapse
Can you switch between MFC, ATL, etc. ? I know they are some kind of libraries but thought "don't look at it, there too much to learn/understand anyway ".
I've search but somehow you think there is the solution and then you learn the hard way, it's very old code. Will search further offcourse and I am reading a chapter on classes and if I can find; messages.
it's already very easy to handle messages without any MFC overload. Just check the uMsg parameter in your DefWindowProc. If you create a new Win32 project in Visual C++ wizard then you see what it's looking like. This is mandatory knowledge. Usually first thing you learn after Hello World. If you didn't know about message processing in Windows/Wince then it's the same like sitting in a car and don't know how to turn the keys.
Do you know how to open dsm file in textbox???
RAMMANN said:
it's already very easy to handle messages without any MFC overload. Just check the uMsg parameter in your DefWindowProc. If you create a new Win32 project in Visual C++ wizard then you see what it's looking like. This is mandatory knowledge. Usually first thing you learn after Hello World. If you didn't know about message processing in Windows/Wince then it's the same like sitting in a car and don't know how to turn the keys.
Click to expand...
Click to collapse
Thats how I feel exactly. It's strange. I read quickly thru 3 books about C++ and no mention of these messages. C#/Basic are easier to understand because of all the examples.
Found these:
- http://www.youtube.com/watch?v=kWVGqV2Yklw
- http://www.youtube.com/watch?v=cbe6yxBHEiU
The video does explain that the linked example doesn't look so different. What a lot of source code Ms creates for you..
If created a WIN32 smart device project and DefWindowsProc is only called when to pass the message to other programs. I need the windows handle for the notification and NOT display the window.
But again it's a bit to much for me at this moment. I haven't got a solution yet..Could somebody help me with not displaying this window. I would still like to use the windows handle to make sure I get the callbakcs to the WM_COMMAND.
Yes - I think you only need at end of WinMain before SHNotificationRemove
to add:
Code:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hacc, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Then a new function:
Code:
/* Redefine generic HANDLE_WM_ACTIVATE macro for Pocket PC */
#undef HANDLE_WM_ACTIVATE
#define HANDLE_WM_ACTIVATE(hwnd,wParam,lParam,fn) \
(SHHandleWMActivate((hwnd), (wParam), (lParam), &g_sai, 0), /*return*/ 0L)
/* Redefine generic HANDLE_WM_SETTINGCHANGE macro for Pocket PC */
#undef HANDLE_WM_SETTINGCHANGE
#define HANDLE_WM_SETTINGCHANGE(hwnd,wParam,lParam,fn) \
(SHHandleWMSettingChange((hwnd), (wParam), (lParam), &g_sai), /*return*/ 0L)
static LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
HANDLE_MSG(hwnd, WM_CREATE, Main_OnCreate);
HANDLE_MSG(hwnd, WM_ACTIVATE, /* SHHandleWMActivate()*/ 0);
HANDLE_MSG(hwnd, WM_SETTINGCHANGE, /* SHHandleWMSettingChange() */ 0);
HANDLE_MSG(hwnd, WM_PAINT, Main_OnPaint);
HANDLE_MSG(hwnd, WM_COMMAND, Main_OnCommand);
HANDLE_MSG(hwnd, WM_DESTROY, Main_OnDestroy);
[B]// Remark: Here you can add more messages - also for what user has chosen.[/B]
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
}
and then the message handlers like this:
Code:
static BOOL Main_OnCreate(HWND hwnd, CREATESTRUCT *pcs)
{
SHMENUBARINFO mbi;
memset(&mbi, 0, sizeof(mbi));
mbi.cbSize = sizeof(mbi);
mbi.hwndParent = hwnd;
mbi.nToolBarId = IDR_MNU_MAIN;
mbi.hInstRes = g_hInstance;
if (!SHCreateMenuBar(&mbi)) /* create the menu bar */
return FALSE;
g_hwndMB = mbi.hwndMB;
return TRUE;
}
But your Compiler should already make such a project by default and you can simple add the code fom _tmain to WinMain, which you've posted above.
Greetz
Micha
Thank you, yesterday I debugged and and debugged trying to understand how this works but the debugger doesn't stop always in all source code.
If f.i. you click on the screen I expected this to be an event, but the debugger didn't stop at all. Is there a command to always stop when a line of code is processed? Now it only stops when I have set a break point. I want to see every line processed...
I will try to implement your suggestions. For a newby it still looks difficult I hope someday I will look back to this and say "wow, that was so easy".
ajhvdb said:
Thank you, yesterday I debugged and and debugged trying to understand how this works but the debugger doesn't stop always in all source code.
If f.i. you click on the screen I expected this to be an event, but the debugger didn't stop at all. Is there a command to always stop when a line of code is processed? Now it only stops when I have set a break point. I want to see every line processed...
I will try to implement your suggestions. For a newby it still looks difficult I hope someday I will look back to this and say "wow, that was so easy".
Click to expand...
Click to collapse
Well, actually that's the reason why breakpoints exist. To stop the debugger and allow you look at the running code..... or what else did you think??
RAMMANN said:
Well, actually that's the reason why breakpoints exist. To stop the debugger and allow you look at the running code..... or what else did you think??
Click to expand...
Click to collapse
I want to say "stop and show at the current code line".
For example you start your program, goto the appropiate window, type in some data and NOW before you click on SAVE. You say to your debugger "catch this/coming event".
Debugger would stop if you'd handle this event and set break point to 1st command of this function.
then yo can go step by step through each line of code.
and hey: it's not soo easy,which I posted.But your Compiler (vs2008 or PellesC or whatever) would make this automatically for you and you only have to copy your part of code into WinMain of this automatic processed code.
The "Managers" then can help you also to add eventhandlers automatically.
you only have to set Breakpoints to the automatic processed Event-Handle-Function - them you can see,if this event is triggered like you want it.
You only think from the wrong direction
Ok, I learned a lot.
(The VS2008 debugger has bugs. If I set a breakpoint on line 100, and start debug, line 109 has the breakpoint. It looks like only the original code can be debugged)
I did start a new project and used the tips from above. I can catch a click on a link ahref field in the notification bubble.
I have disabled the screen so only the bubble is shown
Now I need to catch the menu button and more important the data in the html form (input type radio) in the notification bubble. For this I need to convert the param to a structure...!
I also need to extend the "while getmessage" loop with a timer. If 15 seconds have passed, I need to step out of the loop and quit automatically.
A lot of searching again.
BTW.
Thx all for helping me. Not really one tip did it, you all guided me a bit. If you think your tip helped me a lot then send me a PM with your paypal code. You can also send me your address/or your businessaddress. I will send you a small present/surprise related to my country (Holland).
in Germany we have a good cheese, too and the sense of a community like this great one,is for helping each other-especially beneath developers.
And it's always a question of finding out,how to manage something new
All the best for your further development.
Micha
Attached is the code of my subproject. I will update it if those last points are done. Hope it helps others.
If someone has a link or example code for those points. (or improvements of my code) please let me know.

[SDK] XFControls - Advanced UI SDK [UPDATED w/ Sense UI Example!]

This is an Advanced UI SDK for developing finger-friendly Application UIs.
The reason for developing this SDK was mainly to learn about programming for Windows Mobile and the Compact Framework 3.5. I also developed this SDK because I could not find good UI controls that gave total display control to the programmer while taking care of all of the Physics, windowing, and frame buffering AND was open source.
Finally, this SDK was originally developed as part of the XDAFacebook application that I am currently developing.
I am releasing this SDK and its source so that people can have a good foundation to build finger-friendly Windows Mobile applications, and so that programmers starting off in the Windows Mobile world won't have to start from scratch when creating useful UI Controls.
Here are some of the features and uses of this SDK.
Features:
Fully customizable
Easily create custom UI Controls
Resolution independent
Full physics for rendering smooth scrolling
Uses:
Quickly create UI controls
Develop full UI SDKs
Learn basic UI programming for .net CF 3.5
I ask that if you use these controls, please provide feedback so that everyone can benefit!
Thank you and I hope you find these controls useful!
SDK Documentation
Even though the controls are easy to implement, they can seem intimidating at first. Here is an over-view of the core pieces to the SDK:
The IXFItem Interface:
Here are Properties of the interface
PHP:
XFPanelBase Parent { get; set; } // The item's List container
XFItemState State { get; set; } /* An Enum to describe the current item's state
This could include things like [B]Selected[/B] or [B]Normal[/B]*/
Bitmap Buffer { get; set; } // This is the item's cache buffer. Allows for speedy rendering
XFItemStyle Style { get; set; } // CSS like style object. Allows for easy customization
XFItemType ItemType { get; set; } /* Enum to label the type of the current object.
For example, [B]Clickable[/B] or [B]Display[/B] meaning the item won't change*/
The following are the methods that need to be implemented
PHP:
int GetHeight(); /* This returns the height of the item. This value is usually calulated
but in some instances is static. The value should be cached because this method
is called several times during the rendering process.*/
void ResetHeight(); // What ever needs to be done to reset the height cache
void ItemPaint(Graphics g, int x, int y); // Where the magic happens. More on this later
XFItemClickResult GetClickResult(); // An enum is return with what the action of clicking this item was.
The main part of the interface is the ItemPaint method. This method is called from the XFPanelList and passes a Graphics object created from the Buffer Bitmap of the Item. In this method, you do all of your graphics logic, drawing it with the supplied graphics object. The x and y are any offset numbers that should influence when the objects are based. Most of the time, these numbers will be 0, 0.
Because the programmer has total control over how the item is rendered, special care must be used when creating the items, to draw all the features with respect to the XFItemStyle object. This object usually is created in CTOR. An example of the XFItemStyle object being created in one of the SenseUI XFItem's CTORs:
PHP:
public SenseItem()
{
ItemType = XFItemType.Clickable;
Style = new XFItemStyle()
{
BoarderBottomColor = Color.FromArgb(189, 182, 189),
DashStyleBottom = System.Drawing.Drawing2D.DashStyle.Dash,
TextColor = Color.Black,
TextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SelectedTextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SelectedSecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SecondaryTextColor = Color.FromArgb(57, 52, 57),
SelectedTextColor = Color.White,
SelectedBackgroundColor = Color.FromArgb(43, 36, 43),
SelectedSecondaryTextColor = Color.FromArgb(182, 178, 182),
Padding = 11,
PaddingBottom = 12,
PaddingLeft = 10,
PaddingRight = 16
};
}
You will also notice that the ItemType is also set here.
How you use the Style is a little more involved. In the ItemPaint, the programmer should base all of the features off of what is in the Style object. Here is an example of how the above Style object was used in the ItemPaint method:
PHP:
public void ItemPaint(Graphics g, int x, int y)
{
int width = Parent == null ? Screen.PrimaryScreen.WorkingArea.Width : Parent.Width;
XFControlUtils.DrawBoarders(Style, g, 0, 0, width, GetHeight());
int currX = Style.PaddingLeft;
int currY = Style.PaddingTop;
int mHeight = 0;
int sHeight = 0;
if (Icon != null)
currX += _iconSize + Style.PaddingLeft;
SizeF mText = new SizeF();
if (!string.IsNullOrEmpty(MainText))
{
mText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, MainText, Style.TextFont);
MainText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, MainText, Style.TextFont);
}
SizeF sText = new SizeF();
if (!string.IsNullOrEmpty(SecondaryText))
{
sText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
SecondaryText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
}
mHeight = (GetHeight() / 2) - ((int)mText.Height / 2);
if (!string.IsNullOrEmpty(SecondaryText))
{
mHeight = (GetHeight() / 2) - _textSpace - (int)mText.Height;
sHeight = (GetHeight() / 2) + _textSpace;
}
if (State == XFItemState.Selected)
{
XFControlUtils.DrawBackgroundSelected(Style, g, x, y, width, GetHeight());
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.SelectedTextColor))
g.DrawString(MainText, Style.SelectedTextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SelectedSecondaryTextColor))
g.DrawString(SecondaryText, Style.SelectedSecondaryTextFont, b, currX, sHeight);
}
else
{
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.TextColor))
g.DrawString(MainText, Style.TextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SecondaryTextColor))
g.DrawString(SecondaryText, Style.SecondaryTextFont, b, currX, sHeight);
}
if (Icon != null)
XFControlUtils.DrawAlphaFirstPix(g, Icon, Style.PaddingLeft, Style.PaddingTop);
}
That is as complex as it gets. Other than doing normal Event Handling for ClickReturns, this is all that is required to create beautiful UI Controls for your application.
I hope that this helps! Feel free to PM me or post a reply if you need further clarification.
Class List
Form Controls:
XFPanelContainer - The main control that interacts with the Form.
XFPanels:
XFPanelBase - Basic building block. Handles most of the generic functionality
XFPanelList - Can add IXFItem items.
XFPanelHeader - The top header bar for an XFPanelContainer
XFItems
IXFItem - Interface that all XFItems inherate
XFItemSimpleText - Simple item that displays text
XFItemBack - Special item that allows a panel to slide back
XFItemLoading - Item that allows for work to be down in the background.
XFControlUtils: Library of static, useful utilities for this SDK
DrawAlpha - Draws an image with a supplied Graphics object with a specific level of opacity
DrawAlphaFirstPix - Draws an image and renders all pixels that are the same color as pixel (1,1) are 100% transparent
DrawJustifiedString - draws a justified string
GetEllipsisStringMeasure - Takes a string and if it is more than the supplied width, clips the string and adds a trailing "..." at the end
EllipsisWord - same as the GetEllipsisStringMeasure, except it ellipsis at the words and not at the char level.
GetSizedString - Takes a string and adds "\n" so that the string wraps according to the supplied width
Many Others!
Sense UI Example
Here is a working example. I made this Sense UI example in about 3 hours 15 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XFSenseUI
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
UPDATE: I've added the XFSense to the Google Code page and have made some pretty extensive updates to it. I've added a few controls including sliders, toggles, checkboxes and radio buttons. It still isn't complete but I will be working to make it a full fledge Sense SDK.
Stay tuned!
Releases:
Initial Release - 9/1/10
When major updates occur, the DLLs will be posted here. The best thing to do is pull the source from the Google Code page and use that.
This will guarantee the freshes code will be used for your projects
Instructions:
Download and unzip the latest XFControls.zip from below.
Add the .dll as a reference.
Program!
The source can be found at: http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XDAFacebook/XFControls
List of downloads:
10/6/10 - Updated for speed and better scrolling! - XFControls 0.2.zip
9/1/10 - Initial upload - XFControls 0.1.zip
Other things I might have missed
Reserved Other
Sounds interesting! Definitely looking forward to some screenshots.
kliptik said:
Sounds interesting! Definitely looking forward to some screenshots.
Click to expand...
Click to collapse
Screenshots are up!
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
joe_coolish said:
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
Click to expand...
Click to collapse
Just DL'd a copy. I'm super swamped at the moment trying to get the next release of KD-Font out, but I'll try and check this out when I get a chance.
Thank you for your contribution!
I will definitely give this a test run at some point. Good work!
you have to add you own graphics to this sdk?
janneman22 said:
you have to add you own graphics to this sdk?
Click to expand...
Click to collapse
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
joe_coolish said:
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
Click to expand...
Click to collapse
oh right. but does it place controls in the toolbox, or have you to create the controls hard coded?
i could help you to make some grapics packages for this sdk
Ok, I've updated the binaries to be the latest and greatest. The scrolling is super smooth and things are starting to look pretty good!
I also will be updating the XFSense and I'll probably be extending it a little more because I plan on bringing it into the XDA Facebook app.
As always, let me know what you think!
EDIT: Oh, and to answer the question about adding objects to the toolbox, I have not added the OCX files (or whatever they are) so that they can be added to the tool box. But, after you've added the container and the panels, everything is logic after that, so adding the items to the toolbox really doesn't benefit too much.
As far as graphics, I would love help with graphics! Send me a PM and we'll talk!
joe_coolish said:
Here is a working example. I made this Sense UI example in about 3 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
Click to expand...
Click to collapse
Very nice control. I downloaded the sample (had problem with missing XFControl project but downloaded it from code.google).
Have a couple questions, how would i go about adding image to a child panel?
What I'm trying to so is have about 75 items on the main screen and each item will have sub-panel, when clicking on sub-panel I need to have label x2 and image.
Also when compiling the project I get error:
"Error 1 'XFControls.XFPanels.XFPanelHeader' does not contain a definition for 'BackgroundImage' and no extension method 'BackgroundImage' accepting a first argument of type 'XFControls.XFPanels.XFPanelHeader' could be found (are you missing a using directive or an assembly reference?) C:\downloads\C#\XFSenseUI\XFSenseUIDemo\Form1.cs 39 24 XFSenseUIDemo"
Alright, I'll post an example if I get some time in a bit. But as for the error, it is because the Core XFControls has been modified since the last time I updated this thread. You can download the freshes code from the google code page or use the attached DLL. I'd suggest the Google Code page, since it gets updated more frequently. But then you get all the XDAFacebook with it, so it can also be negative.
Basically to add an image to an XFItem to be added to the XFPanelList, you can either create your own item by inheriting from the IXFItem and doing all the image manipulation in the ItemDraw() method.
For an example of how to do that, look at the XFItemImageDisplay item in the XFControls.XFPanels.XFPanelItems namespace.
If you need something specific, let me know and I'll see if I can whip up an example
I'm new to C# and the compact framework so sample would be good...
Thanks
JarekG said:
I'm new to C# and the compact framework so sample would be good...
Thanks
Click to expand...
Click to collapse
Ok, could you describe how you want the control to look? Also, what you want to supply to the constructor? IE a path for an image, upper text, lower text, maybe even some style things. ETC

Successful TCP Connection via CoreCon

So during my break today I added a few more registry paths to check on my HTC Radar and I found HKCU\Software\Microsoft\ConMan\HostLauncher\HostData\. There I found a few Service entries:
Code:
7ABBE0D5-B437-42CA-B57B-CEED61680E4F
11EE50CA-6CD3-45BA-9D65-46E133CFF009
B2FC26AB-D6EC-4426-91FA-9E039F92A639
The first entry did not take me any where but the other two did.
Running those in my test application sent back:
Code:
Int32Type: 0
Int32Type: -2147024809
I know it isnt much and I am not sure what to send to the ConMan so if someone does please tell me:
Code:
private static void ExecutionTest()
{
#region Create Objects
ObjectId DeviceID = new ObjectId("30F105C9-681E-420b-A277-7C086EAD8A4E");
Platform platform = datastoremanager.GetPlatform(PlatformObjectID);
Device device = platform.GetDevice(DeviceID);
#endregion
try
{
//Connect to the device.
device.Connect();
if (device.IsConnected())
{
RemoteAgent ra = device.GetRemoteAgent(new ObjectId("910DCB1B-487B-452b-87FC-73852B5A239C"));
DevicePacketStream ps = ra.CreatePacketStream(new ObjectId(new Guid("11EE50CA-6CD3-45BA-9D65-46E133CFF009")));
// Create and write a packet of data.
Packet packet;
packet = new Packet();
for (int i = 0; i < 4; i++) packet.WriteInt32(i);
packet.WriteString("Hello Smart Device");
ps.Write(packet);
#region While stream is connected, try to read a packet.
while (ps.IsConnected())
{
if (ps.IsPacketAvailable())
{
packet = ps.Read();
while (!packet.IsEndOfPacket())
{
switch (packet.ReadDataType())
{
case DataType.BoolType: bool boolValue = packet.ReadBool(); break;
case DataType.ByteArrayType: byte[] buffer = packet.ReadBytes(); break;
case DataType.ByteType: byte byteValue = packet.ReadByte(); break;
case DataType.CharType: char charValue = packet.ReadChar(); break;
case DataType.Int32Type: Console.WriteLine("Int32Type: " + packet.ReadInt32().ToString()); break;
case DataType.StringType: Console.WriteLine("String: " + packet.ReadString()); break;
default: break;
}
}
break;
}
System.Threading.Thread.Sleep(1000);
}
#endregion
}
}
catch (Exception ex)
{
throw ex;
}
finally { device.Disconnect(); }
}
Huh, you got the remote "GetRemoteAgent" working. Right?
I think i might know how to resolve what to call in to the packet. VS2010 talks to wp7, and uses one of those GUID's; meaning one should be able do binary search all files (in a rom) to see who owns the GUID (what dll handler), disassemble that dll (to ASM/c), and extract "what it wants".
Or if MS has a hidden caller class somewhere
Ill look further into this, thanks
fiinix said:
Huh, you got the remote "GetRemoteAgent" working. Right?
I think i might know how to resolve what to call in to the packet. VS2010 talks to wp7, and uses one of those GUID's; meaning one should be able do binary search all files (in a rom) to see who owns the GUID (what dll handler), disassemble that dll (to ASM/c), and extract "what it wants".
Or if MS has a hidden caller class somewhere
Ill look further into this, thanks
Click to expand...
Click to collapse
Yes I did . Yeah I just need to know what to actually send to to the device. I know Visual Studio communicates this way.
MJCS said:
Yes I did . Yeah I just need to know what to actually send to to the device. I know Visual Studio communicates this way.
Click to expand...
Click to collapse
Great
I, myself tried 20+ GUID's once (from wp7 that _could_ be); all threw exceptions (aka not a remote agent handler).
It feels better now knowing what GUID's i can use.
Well the reg path was quite obvious; why did i not stumble upon that one earlier..
fiinix said:
Great
I, myself tried 20+ GUID's once (from wp7 that _could_ be); all threw exceptions (aka not a remote agent handler).
It feels better now knowing what GUID's i can use.
Well the reg path was quite obvious; why did i not stumble upon that one earlier..
Click to expand...
Click to collapse
Well I only found it since I know have an HTC Radar. My Dell venue pro requires you to manually enter in registry paths to see if they exist or not. I was able to decompile an older HTC registry viewer and then fix it so it didnt require interop unlock.
It should be possible to do registry browsing (but not editing) just fine on a DVP using the standard tools, unless there's a check that specifically blocks them. The browsing uses a native homebrew DLL that doesn't require ID_CAP_INTEROPSERVICES and has no device-specific dependencies. It's the editing that requires interop-unlock and device-specific DLLs.
GoodDayToDie said:
It should be possible to do registry browsing (but not editing) just fine on a DVP using the standard tools, unless there's a check that specifically blocks them. The browsing uses a native homebrew DLL that doesn't require ID_CAP_INTEROPSERVICES and has no device-specific dependencies. It's the editing that requires interop-unlock and device-specific DLLs.
Click to expand...
Click to collapse
There is no GetSubKeys method...anyways lets get back on topic.
I've been trying for weeks to get anything out of this. Nothing so far. I did find out that the Developer unlock is just a byte array of a cookie taken from Microsoft's auth server.
Has anyone had any success with this socket method yet? I really don't know enough about sockets to try.
BTW you have to have a core con connection to the device already open either from app debugging or some other method

[APP][WIP][11.12.12] BullForce - Game Engine

Official web page: http://bullforce.quaternionstudios.com
Donate via Paypal.​Logo is in drawing.
Features:
* Written in pure heavily optimized C++ and GLSL.
* Powerfull scripting in all .NET (Mono) compaible languages and component architectures provide best quality of code. //We are working on API
* Photorealistic renderer with support of most beautifull effects, such as HDR, SSAO, DOF, Shadow mapping and much more.
* Crossplatform: Support of OS X®, Linux and Windows®, iOS® and Android.
* Techonologies to make it best: OpenGL®, OpenAl®, BulletPhysics®, Autodesk HumanIK®, Mono®.
* BullStudio (WYSIWYG-style editor, work in progress).
Red text = NOT READY
Download latest version from here:
Download:
Build from: 11.12.12
You should open "Demo/UnderwaterAwakens.xml" with "Engine/BullForce.exe"
Code:
11.12.12:
* Initial release.
* SSAO and HDR are disabled, for now.
Bug Tracker is located here: bugtracker.quaternionstudios.com/bullforce
If you like us, please donate via paypal. Link is above. Your money will help us a lot. You will get per life license for free
reserved
Sounds very cool. However, your site is currently not working (404 error on home page and all links).
Since you're targeting Android and iOS as well (meaning you'll already have an ARM port), does that mean that you'll also support Windows RT? In general, I'm less likely to buy a Win8 app that won't run on my tablet too...
GoodDayToDie said:
Sounds very cool. However, your site is currently not working (404 error on home page and all links).
Since you're targeting Android and iOS as well (meaning you'll already have an ARM port), does that mean that you'll also support Windows RT? In general, I'm less likely to buy a Win8 app that won't run on my tablet too...
Click to expand...
Click to collapse
Yea, we gonna add suport of WinRT, but we don't have enough money to buy Surface. In Russia it costs about 2000$ I better bought MacbookAir; and we need money for hosting, etc.
And Yea, site is currently under developing. Our web master works hard. But bugtracker should work
Code of scene, in demo:
Code:
using System.Collections;
using QuaternionStudios.BullForce.Engine;
public class House : Component
{
Transform _myTransform;
void Init()
{
_myTransform = transform;
}
void Update()
{
_myTransform.rotation += new Vector3(0.01f);
}
}
Code:
using System.Collections;
using QuaternionStudios.BullForce.Engine;
public class Scene0
{
GameObject object0 = new GameObject(); //This is Camera;
GameObject object1 = new GameObject(); //House;
private void Initialize()
{
//-------------------------------------------
//Object0
object0.AddComponent<Transform>();
object0.transform.position = new Vector3(0.0f, 0.5f, -3.0f);
object0.transform.rotation = new Vector3(0.0f);
object0.transform.scale = new Vector3(1.0f);
object0.AddComponent<Camera>();
object0.camera.fieldOfView = 60.0f;
object0.camera.clippingPlanes = new Vector2(0.3f, 1000.0f);
object0.camera.clearColor = new Color(0.00f, 0.00f, 0.56f, 1.00f);
object0.camera.projection = Camera.Projection.Perspective;
object0.camera.renderingRect = new Vector4(0.0f, 0.0f, 1.0f, 1.0f);
//-------------------------------------------
//Object1
object1.AddComponent<Transform>();
object1.transform.position = new Vector3(0.0f, 0.0f, 0.0f);
object1.transform.rotation = new Vector3(0.0f);
object1.transform.scale = new Vector3(1.0f);
object1.AddComponent<MeshRenderer>();
object1.meshRenderer.material = Resource.NewResource<Material>("house/house.material");
object1.meshRenderer.staticMesh = Resource.NewResource<StaticMesh>("house/house.mesh0");
object1.AddComponent<House>();
}
}

[Q] PhoneGap and Ajax with database?

Hi all,
I recently finished learning how to create an APK using PhoneGap with code written using HTML5, CSS3 and Javascript.
Now, I would like to create a simple database app but I am not sure how to proceed. From what I learned about PhoneGap, everything can only be written in HTML5, CSS and Javascript coding. How do I get information from a database(flat-file or MySQL), display the data and edit it similar to how one would do using Ajax(I currently don't know how to code in ajax)? Is this possible with PhoneGap? How? Do I need a framework like JQuery Mobile to do this?
There would only be one page/view:
- displaying what is in the table
- and editing/adding new data to the table
Thank you.
using frameworks such as jquery mobile is a better option. u can use ajax calls to server to populate data. create a server side code that responds to ajax calls from app and fetch data from my sql and sends back the data either as json or xml
Falen said:
Hi all,
I recently finished learning how to create an APK using PhoneGap with code written using HTML5, CSS3 and Javascript.
Now, I would like to create a simple database app but I am not sure how to proceed. From what I learned about PhoneGap, everything can only be written in HTML5, CSS and Javascript coding. How do I get information from a database(flat-file or MySQL), display the data and edit it similar to how one would do using Ajax(I currently don't know how to code in ajax)? Is this possible with PhoneGap? How? Do I need a framework like JQuery Mobile to do this?
There would only be one page/view:
- displaying what is in the table
- and editing/adding new data to the table
Thank you.
Click to expand...
Click to collapse
If you just want your app to have a local database then HTML5 already does that for you. I've used this library in the past and had no problems with it at all...
http://html5sql.com/
I wrote an app that imported a CSV file into a database. It was a very basic app, written as proof of concept for a bigger project when I first started developing web apps for mobile. Here's a basic version of importing a CSV and using html5sql to create a table with it...
Code:
function createDatabase() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("/sdcard/external_sd/temp/PRODUCTS.CSV", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var csv = evt.target.result;
var lines = csv.split("\n");
var i = 1;
html5sql.openDatabase("com.archer.testapp.db", "Test DB", _dbSize);
html5sql.process("DROP TABLE IF EXISTS products; " +
"CREATE TABLE IF NOT EXISTS products (linecode int, description varchar(255), barcode varchar(25), price int, stock int); ", function() {
function addRow() {
var line = lines[i].split(",");
var sql = "INSERT INTO products (linecode, description, barcode, price, stock) values (" +
line[0] + ", " +
"'" + line[2] + "', " +
"'" + line[1] + "', " +
line[6] + "," +
line[13] + ")";
html5sql.process(sql);
var pd = i / lines.length * 100;
$(".progress-bar").css("width", pd + "%");
i++;
if (i < lines.length) {
setTimeout(addRow, 2);
}
}
addRow();
}, function(error, failingQuery) {
alert("Error : " + error.message + "\r\n" + failingQuery);
});
};
reader.readAsText(file);
}
There's obviously stuff in there that won't be relevant and you'll need to change. Also I had a global variable, _dbSize, that was the initial size (in bytes) of the database, and there's some stuff in there about a progress bar. Use it or delete it - it won't affect the database being created.
Also, note the use of the addRow() function that calls itself. This was to enable the function to run asynchronously, which is needed if you want to be UI friendly (nothing will update whilst doing the import if you just import everything in one go).
However, since you mention AJAX then that may not be relevant. In which case you're just looking at API calls for whatever service is holding your database.
Hi friend ! If you're new to hybrid development, I highly recommend you to take a look at Ionic. It would help you on so many levels ! http://ionicframework.com/
About your issue, you can always define a REST API using your favorite backend (I know it can be done very easily with Laravel framework in PHP using MySQL DB). I prefer using Firebase ! https://www.firebase.com/
Firebase and Ionic framework based on AngularJS are such perfect match that half your code is already done before you knows it.
Happy coding !

Categories

Resources