I am presently writing a RegEdit program to run on my PC and allow editing of the registry on the connected PPC. I have got to the point where I can read the entire registry and I am now implementing function to update the registry i.e. insert new key, delete key, add new Key Values etc...
The problem I have at the moment is trying to add a new value to an existing key. The function I have written so far to do this is as follows, but the call to CeRegSetValueEx(...) returns an error code 5!
Code:
//-----------------------------------------------------------------------------------
// Adds a new key value into the registry.
// // TO DO - add the data
int CRegEditDoc::AddNewKeyValue(HTREEITEM hParent, HKEY hRoot, LPTSTR lpszKey, LPTSTR lpszValueName, DWORD dwType)
{
USES_CONVERSION;
int nItem, rc;
HKEY hKey;
LPWSTR lpwszKey = T2W(lpszKey);
LPWSTR lpwszValueName = T2W(lpszValueName);
try
{
if (lstrlen (lpszKey))
{
if (m_rapi.CeRegOpenKeyEx (hRoot, lpwszKey, 0, 0, &hKey) != ERROR_SUCCESS)
{
return 0;
}
}
else
{
hKey = hRoot;
}
CString strValue = "my data";
LPWSTR lpwszData = T2W(strValue);
DWORD length = dim(lpwszData);
nItem = m_pRightView->GetListCtrl().GetItemCount();
if (m_rapi.CeRegSetValueEx(hKey, lpwszValueName, 0, dwType, (LPBYTE)lpwszData, length*2) != ERROR_SUCCESS) // last 2 lpData, szie in bytes of data.
{
HRESULT hResult = m_rapi.CeRapiGetError();
DWORD dwError = m_rapi.CeGetLastError();
return 0;
}
}
catch (CException* e)
{
TCHAR szCause[255];
e->GetErrorMessage(szCause, 255);
CString errorMsg = _T("Error in: CRegEditDoc::AddNewKeyValue: ");
errorMsg += szCause;
AfxMessageBox(errorMsg);
e->Delete();
}
return 1;
}
I would appreciate a little advise on the matter, as this is the first time I have used the RAPI.
Thanks.
Hi VZ800!
The error you're getting is 'access denied'. In WM5 many RAPI functions (including writing to registry) are blocked for security reasons. Your only choice is to use a dll with CeRapiInvoke functions, but it needs to be deployed through a special cab.
You can read about this on msdn.
By the way, the app you're writing already exists, and it has the same problem.
Good luck!
Thanks for the advice. Since my post I have found that my code works for the HKEY_LOCAL_MACHINE, "/Software".
I will investigate the issue you have pointed me to.
Actually, your code should work for the entire HKEY_CLASSES_ROOT as well. MS decided to block only certain 'sensitive' parts of the registry so they can not be corrupted from the outside by malicious software.
If you noticed, MS's own remote registry editor works through DLLs (a ton of them).
Any way, I skimped on words in my first post, since I was writing it on a bus, and while I love my Jamin, writing long text on it is not very enjoyable.
Let me elaborate on CeRapiInvoke:
It's a function you call on the PC side that receives a DLL name and a function name (in that DLL) as parameters and calls that function on the device. It also lets you transfer buffers of data to and from the called function.
It's a great way to communicate with a PPC device without using sockets. You can write the device side DLL to do what ever you wont (like access protected registry) and report back to the PC.
The only drawback is in WM5 this DLL has to be registered and have a 'system' file attribute set. That's why you have to deploy it by cab.
Like I said before it's all in the MSDN.
Hope this helps.
Thanks. I have read the articles (and printed them) about RAPI Restricted Mode Security etc... http://msdn.microsoft.com/library/d...5/html/wce51conRAPIRestrictedModeSecurity.asp and will write a DLL to go on the PPC which will be installed via CAB etc...
I updated the function to add a new value anyway. Rather than calling the RAPI functions for the registry CeRapi... I will call my own functions in my authorised DLL.
Code:
//-----------------------------------------------------------------------------------
// Adds a new key value into the registry.
//
int CRegEditDoc::AddNewKeyValue(HTREEITEM hParent, HKEY hRoot, LPTSTR lpszKey,
LPTSTR lpszValName, DWORD dwDType, LPBYTE lpData)
{
USES_CONVERSION;
HKEY hKey;
LPWSTR lpwszKey = T2W(lpszKey);
LPWSTR lpwszValName = T2W(lpszValName);
DWORD dwDSize = sizeof(lpData);
try
{
if (lstrlen(lpszKey))
{
if (m_rapi.CeRegOpenKeyEx (hRoot, lpwszKey, 0, 0, &hKey) != ERROR_SUCCESS)
{
return 0;
}
}
else
{
hKey = hRoot;
}
// Check if valuename already exists. Should never happen, but just in case.
if (m_rapi.CeRegQueryValueEx(hKey, lpwszValName, 0, &dwDType, NULL, &dwDSize) == ERROR_SUCCESS)
{
AfxMessageBox(_T("Value of this name already exists!"));
return 0;
}
if (m_rapi.CeRegSetValueEx(hKey, lpwszValName, 0, dwDType, lpData, dwDSize) != ERROR_SUCCESS)
{
HRESULT hResult = m_rapi.CeRapiGetError();
DWORD dwError = m_rapi.CeGetLastError();
AfxMessageBox(_T("Unable to create new value for this key!\nPlease check access rights."));
return 0;
}
}
catch (CException* e)
{
TCHAR szCause[255];
e->GetErrorMessage(szCause, 255);
CString errorMsg = _T("Error in: CRegEditDoc::AddNewKeyValue: ");
errorMsg += szCause;
AfxMessageBox(errorMsg);
e->Delete();
}
return 1;
}
A question on using the CeRapiInvoke function. Obviously my function that I will be invoking in my DLL will need to conform to the following footprint:
Code:
LPCWSTR, LPCWSTR, DWORD, BYTE*, DWORD*, BYTE**, IRAPIStream**, DWORD
What I would like to know is this: If I want my function to be a wrapper to say the
Code:
CeRegQueryValueEx(HKEY, LPWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD)
function, how do I parse the function args? Please suggest how I would pack them into a BYTE* for the pInput parameter.
Actually, you got it a bit wrong:
Code:
FuncName(DWORD cbInput, BYTE *pInput, DWORD *pcbOutput, BYTE **ppOutput, IRAPIStream *ppIRAPIStream);
The prototype you specified is for the PC side (the first two strings are DLL name and function name);
I use the following parsing method:
Code:
BYTE* curInputPos = pInput;
memcpy((BYTE*)&hKey, curInputPos, sizeof(HKEY));
curInputPos += sizeof(HKEY);
memcpy((BYTE*)&dwIndex, curInputPos, sizeof(DWORD));
curInputPos += sizeof(DWORD);
memcpy((BYTE*)&Reserved, curInputPos, sizeof(DWORD));
curInputPos += sizeof(DWORD);
It works fine both ways.
Just don't forget to use LocalAlloc for inBuffer and LocalFree for outBuffer.
Thanks. I'll let you know how I get on.
So if I were to parse an HKEY and an LPTSTR accross I would do the following to put the data into a BYTE array:
Code:
DWORD dwIn, dwOut;
LPBYTE pInput;
PDWORD pOut;
dwIn = sizeof(HKEY) + (strlen(lpszKey)*sizeof(TCHAR));
pInput = (BYTE*)(LocalAlloc(LPTR, dwIn));
memcpy(pInput, (BYTE*)&hKey, sizeof(HKEY));
pInput += sizeof(HKEY);
memcpy(pInput, (BYTE*)&lpszKey, strlen(lpszKey)*sizeof(TCHAR));
// move pointer back to begining.
pInput -= sizeof(HKEY);
Basically, yes but with two reservations:
1) I recommend using a different pointer for the current position in buffer, to avoid errors.
2) you need to put the string length in the byte array before the string, otherwise you won't know it's length on the device side. Alternatively, you have to add 1 to the length so the 0 byte at the end gets packed and you can use strlen on the device.
Also keep in mined that unless you define the PC side project to work with UNICODE libraries, THCHAR will be defined as char, while on the device it's always WCHAR.
I really apreciate your help. I still can't get my DLL function to work I keep getting error 1064!
This is my code for the DLL named REditSvr.dll:
Code:
#include <windows.h>
#ifdef __cplusplus
extern "C"
{
#endif
__declspec (dllexport) INT RegEditDeleteValue (DWORD cbInput, BYTE* pInput, DWORD* pcbOutput, BYTE** ppOutput, PVOID reserved);
#ifdef __cplusplus
}
#endif
BOOL WINAPI DllMain (HANDLE hinstDLL, DWORD dwReason, LPVOID lpvReserved)
{
return TRUE;
}
INT RegEditDeleteValue (DWORD cbInput, BYTE* pInput, DWORD* pcbOutput, BYTE** ppOutput, PVOID reserved)
{
INT rc = 0;
BYTE* curInputPos = pInput;
HKEY hKey;
DWORD dwLength;
// Copy args out of input buffer.
memcpy((BYTE*)&hKey, curInputPos, sizeof(HKEY));
curInputPos += sizeof(HKEY);
memcpy((BYTE*)&dwLength, curInputPos, sizeof(DWORD));
curInputPos += sizeof(DWORD);
// Allocate enough memory for local wchar.
LPWSTR lpszValueName = (WCHAR*)malloc(dwLength);
memcpy((BYTE*)&lpszValueName, curInputPos, sizeof(dwLength));
curInputPos += sizeof(dwLength);
// Do the registry delete.
rc = RegDeleteValue(hKey, lpszValueName);
// Allocate memory for the return buffer.
BYTE* pOutput = (BYTE*)LocalAlloc(LPTR, sizeof(long));
memcpy(pOutput, (BYTE*)rc, sizeof(long));
*ppOutput = pOutput;
*pcbOutput = sizeof(long);
// Free input buffer.
LocalFree(pInput);
// Free WCHAR
free(lpszValueName);
return GetLastError();
}
and this is the code in my PC application which invokes the above function (or I would hope it did):
Code:
//-----------------------------------------------------------------------------------
// Deletes the key value from the registry.
//
int CRegEditDoc::DeleteKeyValue(HKEY hRoot, LPCTSTR lpszKey, LPCTSTR lpszValName)
{
USES_CONVERSION;
HKEY hKey;
LPWSTR lpwszKey = T2W(lpszKey);
LPWSTR lpwszValName = T2W(lpszValName);
try
{
if (lstrlen(lpszKey))
{
if (m_rapi.CeRegOpenKeyEx (hRoot, lpwszKey, 0, 0, &hKey) != ERROR_SUCCESS)
{
return 0;
}
}
else
{
hKey = hRoot;
}
/* if (m_rapi.CeRegDeleteValue(hKey, lpwszValName) != ERROR_SUCCESS)
{
HRESULT hResult = m_rapi.CeRapiGetError();
DWORD dwError = m_rapi.CeGetLastError();
AfxMessageBox(_T("Unable to delete value for this key!\nPlease check access rights."));
return 0;
}
*/
// Testing remote registry value deletion.
DWORD dwIn, dwOut;
LPBYTE pInput, pCurInputPos;
PDWORD pOut;
DWORD dwLength = wcslen(lpwszValName)*sizeof(WCHAR);
dwIn = sizeof(HKEY) + dwLength;
pInput = (BYTE*)(LocalAlloc(LPTR, dwIn));
pCurInputPos = pInput;
memcpy(pCurInputPos, (BYTE*)&hKey, sizeof(HKEY));
pCurInputPos += sizeof(HKEY);
// Store the length of the string
memcpy(pCurInputPos, (BYTE*)&dwLength, sizeof(DWORD));
pCurInputPos += sizeof(DWORD);
memcpy(pCurInputPos, (BYTE*)&lpwszValName, dwLength);
HRESULT hr = m_rapi.CeRapiInvoke(L"REditSvr", L"RegEditDeleteValue", dwIn,
pInput, &dwOut, (PBYTE*)&pOut, NULL, 0);
HRESULT hResult = m_rapi.CeRapiGetError();
DWORD dwError = m_rapi.CeGetLastError();
LocalFree(pOut);
if (hKey != hRoot)
{
m_rapi.CeRegCloseKey(hKey);
}
}
catch (CException* e)
{
TCHAR szCause[255];
e->GetErrorMessage(szCause, 255);
CString errorMsg = _T("Error in: CRegEditDoc::DeleteKeyValue: ");
errorMsg += szCause;
AfxMessageBox(errorMsg);
e->Delete();
}
return 1;
}
The DLL has been deployed to the PPC \Windows folder by eVC4. My PPC runs WM5 (is this the problem, although I have written programs with eVC4 ok for it).
I would again appreciate your help/advice on why this isn't working. At present I have unlocked my PPC and I am able to edit any part of the registry etc...
Hi VZ800!
I noticed a couple of errors in your code (which you may have corrected yourself by now) but the biggest problem, I think is that you don't register the dll.
Here is the part you missed from MSDN:
(full link: http://msdn.microsoft.com/library/d...en-us/mobilesdk5/html/mob5lrfcerapiinvoke.asp)
To satisfy the requirements of the Remote Access Security Policy
1. Create a provisioning XML document that adds the new node "RAPI" to the metabase. This node must include the absolute path to the *.DLL file. For more information, see Metabase Settings. The following code example shows the contents of a typical provisioning XML file.
<wap-provisioningdoc>
<characteristic type="Metabase">
<characteristic type="RAPI\Program Files\Green Sky\recaller.dll\*">
<parm name="rw-access" value="3"/>
<parm name="access-role" value="152"/>
</characteristic>
</characteristic>
</wap-provisioningdoc>
2. Pass the file name of the provisioning XML document to the CAB wizard using the /postxml command line option. The CAB wizard will append the XML to the _setup.xml file it places in the CAB. For more information on creating CAB files, see CAB Wizard.
3. Set the System attribute on the *.DLL file.
Only the Manager security role provides the required permissions for modifying the metabase. The ideal way to get this security role is to have your application signed with a privileged certificate.
Note Since Pocket PC implements a one-tier security model, the CAB install process will automatically have the Manager security role.
Click to expand...
Click to collapse
Here's my advice:
Create a simple function that doesn't receive parameters, but pops up a message on the device. When you see that calling it works, try adding the rest of the code.
Hi
As I understand the DLL does not require code to self- register. Anyway, I can call the DLL function and did as you suggested and put a MessageBox in the function. This displayed fine. My code for the DLL is as follows now:
Code:
#include <windows.h>
#ifdef __cplusplus
extern "C"
{
#endif
__declspec (dllexport) INT RegEditDeleteValue (DWORD cbInput, BYTE* pInput, DWORD* pcbOutput, BYTE** ppOutput, PVOID reserved);
#ifdef __cplusplus
}
#endif
BOOL WINAPI DllMain (HANDLE hinstDLL, DWORD dwReason, LPVOID lpvReserved)
{
return TRUE;
}
INT RegEditDeleteValue (DWORD cbInput, BYTE* pInput, DWORD* pcbOutput, BYTE** ppOutput, PVOID reserved)
{
DWORD rc = 0;
BYTE* curInputPos = pInput;
LPCWSTR lpszValueName;
HKEY hKey;
int len;
// Copy args out of input buffer.
memcpy((BYTE*)&hKey, curInputPos, sizeof(HKEY));
curInputPos += sizeof(HKEY);
// Size of value name string.
memcpy((BYTE*)&len, curInputPos, sizeof(int));
curInputPos += sizeof(int);
// Value name string.
memcpy((BYTE*)&lpszValueName, curInputPos, sizeof(len));
curInputPos += sizeof(len);
// Do the registry delete.
rc = RegDeleteValue(hKey, lpszValueName);
// Allocate memory for the return buffer.
*ppOutput = (BYTE*)LocalAlloc(LPTR, rc);
memcpy(*ppOutput, (BYTE*)&rc, sizeof(DWORD));
*pcbOutput = sizeof(DWORD);
// Free input buffer.
if (pInput)
LocalFree(pInput);
return GetLastError();
}
and this is the code from which I am calling it:
Code:
//-----------------------------------------------------------------------------------
// Deletes the key value from the registry.
//
int CRegEditDoc::DeleteKeyValue(HKEY hRoot, LPCTSTR lpszKey, LPCTSTR lpszValName)
{
USES_CONVERSION;
HKEY hKey;
LPWSTR lpwszKey = T2W(lpszKey);
LPCWSTR lpwszValName = T2W(lpszValName);
try
{
if (lstrlen(lpszKey))
{
if (m_rapi.CeRegOpenKeyEx (hRoot, lpwszKey, 0, 0, &hKey) != ERROR_SUCCESS)
{
return 0;
}
}
else
{
hKey = hRoot;
}
/* if (m_rapi.CeRegDeleteValue(hKey, lpwszValName) != ERROR_SUCCESS)
{
HRESULT hResult = m_rapi.CeRapiGetError();
DWORD dwError = m_rapi.CeGetLastError();
AfxMessageBox(_T("Unable to delete value for this key!\nPlease check access rights."));
return 0;
}
*/
// Testing remote registry value deletion.
DWORD dwIn, dwOut;
LPBYTE pInput, pCurInputPos;
PDWORD pOut, rc;
int len = wcslen(lpwszValName)*sizeof(WCHAR);
dwIn = sizeof(HKEY) + len;
pInput = (BYTE*)(LocalAlloc(LPTR, dwIn));
pCurInputPos = pInput;
// Store the hKey value in the output buffer.
memcpy(pCurInputPos, (BYTE*)&hKey, sizeof(HKEY));
pCurInputPos += sizeof(HKEY);
// Store the length of the string in the output buffer.
memcpy(pCurInputPos, (BYTE*)&len, sizeof(int));
pCurInputPos += sizeof(int);
// Store the value name string in the output buffer.
memcpy(pCurInputPos, (BYTE*)&lpwszValName, len);
HRESULT hr = m_rapi.CeRapiInvoke(L"REditSvr", L"RegEditDeleteValue", dwIn,
pInput, &dwOut, (PBYTE*)&pOut, NULL, 0);
// HRESULT hr = RapiFuncTest(dwIn, pInput, &dwOut, (PBYTE*)&pOut, NULL);
HRESULT hResult = m_rapi.CeRapiGetError();
DWORD dwError = m_rapi.CeGetLastError();
if (dwOut)
{
memcpy((BYTE*)&rc, pOut, sizeof(DWORD));
}
if (pOut)
{
LocalFree(pOut);
}
if (hKey != hRoot)
{
m_rapi.CeRegCloseKey(hKey);
}
}
catch (CException* e)
{
TCHAR szCause[255];
e->GetErrorMessage(szCause, 255);
CString errorMsg = _T("Error in: CRegEditDoc::DeleteKeyValue: ");
errorMsg += szCause;
AfxMessageBox(errorMsg);
e->Delete();
}
return 1;
}
As you can see in the DeleteKeyValue(...) function I called a test-function just to check that I was retrieving the data out of the pInput buffer ok, which I am.
I signed the DLL with the SDKSamplePrivDeveloper.pfx, added the /postxml via the /postxml switch in the cabwiz and successfully created a CAB file which installs the DLL into the \Windows folder on the PPC. The .inf file is as follows:
Code:
[CEStrings]
InstallDir=%CE2%
AppName="REditSvr"
[Strings]
CompanyName="AHartley"
[Version]
Signature="$Chicago$"
CESignature="$Windows CE$"
Provider=%CompanyName%
[SourceDisksNames.Arm]
1=,"arm files",,C:\eMDevelopment\PPCRegEdit\REditSvr\REL
[SourceDisksFiles.Arm]
REditSvr.dll=1
[Files.ARM]
REditSvr.dll
[DestinationDirs]
Files.Arm=,%InstallDir%
[DefaultInstall.Arm]
CopyFiles=Files.Arm
My PC side code invokes the DLL function return 0 as error code. But the error code returned in the ppOutput buffer is 0x00000057 Dec 87. Which equates to the error message "The parameter is incorrect."! Which must be a param of the RegDeleteValue(...) function, as if I comment this out I don't get any error return values!!
Any odeas?
This is all academic now as I won't be finishing the PPCRegEdit program coz of the Remote Registry Editor tool available in the eVC4 IDE, which I hadn't noticed before, duh. But I would like to know why the function isn't working as required.
You were writing this as a tool? :shock:
If you just asked, people would have told you about the existing reg edit and CeRegEdit witch works through RAPI directly.
Still, it is a nice exercise in coding which I done my self once (for other purposes)
Any way, your error is simple:
Code:
// Value name string.
memcpy((BYTE*)&lpszValueName, curInputPos, sizeof(len));
curInputPos += sizeof(len);
You are parsing it incorrectly.
This is how it should look:
Code:
// Value name string.
memcpy((BYTE*)lpszValueName, curInputPos, len);
curInputPos += len;
and on the PC side:
Code:
memcpy(pCurInputPos, (BYTE*)&lpwszValName, len);
should be:
Code:
memcpy(pCurInputPos, (BYTE*)lpwszValName, len);
once again, no offence but if you just read your code more carefully and use debug prints to check parameters, you won't need anyone's help.
Good luck in future projects.
(whoops, made an error my self while correcting another)
Yes, it is just an exercise.
Thanks for all your help. Sorry for the silly errors, I will try and take more care in future.
Related
Does anybody know how to get Device Information on XDA(Wallaby, Himalaya and Blue Angel) from within C++?
I would like to get the RomVersions(ROM,Radio etc.) and Dates.
And also Modell Number, IMEI.
Nearly the same as you can see under Start->Settings>System: Device Information.
I read somethimg about a "disk on chip" document, but it is linked under wiki, and it seems to me that everything und wiki(sourceodes, documents etc.) is dead.
Ok, i have some of these things.
I get the Model-Nr, Platform String, IMEI, and the OS Version.
With this Information i can say what XDA Device i´m running on.
But i don´t know how to get the ROM Informations.
Does anybody know where to find them? On XDA3 i found Versiosn in Registry, but they are not avaible on XDA1, and not all avaible on XDA2.
Maybe i have to Get the FileVersions and Dates...
Device Information
Hi I'm new in PDA and I'm looking for c++ code to reed information about device serial number or IMEI (for MDA 2 or MDA 3). Could You help me.
Thanks for any information
Tom.
To retrieve the IMEI:
//Function GetIMEI
CString GetIMEI()
{
CString strTemp;
WCHAR szString[MAX_PATH] = L"\0";
LINEGENERALINFO *LPLineGeneralInfo = NULL;
LPLineGeneralInfo = (LINEGENERALINFO*)malloc(sizeof (LINEGENERALINFO));
LPLineGeneralInfo->dwTotalSize = sizeof(LINEGENERALINFO);
LONG lTapiReturn;
DWORD NewSize;
DWORD dwNumDevs;
DWORD dwAPIVersion = TAPI_API_HIGH_VERSION;
LINEINITIALIZEEXPARAMS liep;
HLINEAPP hLineApp = 0;
HLINE hLine = 0;
DWORD dwExtVersion;
BOOL bRetVal = FALSE;
LPBYTE pLineGeneralInfoBytes = NULL;
DWORD dwTAPILineDeviceID;
const DWORD dwMediaMode = LINEMEDIAMODE_DATAMODEM | LINEMEDIAMODE_INTERACTIVEVOICE;
// Initialisiern
liep.dwTotalSize = sizeof(liep);
liep.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT;
lineInitializeEx(&hLineApp, 0, 0, L"MDAC", &dwNumDevs, &dwAPIVersion, &liep);
// Device ID holen
dwTAPILineDeviceID = GetTSPLineDeviceID(hLineApp, dwNumDevs, TAPI_API_LOW_VERSION, TAPI_API_HIGH_VERSION, CELLTSP_LINENAME_STRING);
// Line öffnen
lineOpen(hLineApp, dwTAPILineDeviceID, &hLine, dwAPIVersion, 0, 0, LINECALLPRIVILEGE_OWNER, dwMediaMode, 0);
// ExTAPI Version aushandeln
lineNegotiateExtVersion(hLineApp, dwTAPILineDeviceID, dwAPIVersion, EXT_API_LOW_VERSION, EXT_API_HIGH_VERSION, &dwExtVersion);
lTapiReturn = lineGetGeneralInfo(hLine, LPLineGeneralInfo);
//If the LineGeneralInfo buffer was too small then make it bigger and ask again
if ((lTapiReturn == 0) && (LPLineGeneralInfo->dwNeededSize > LPLineGeneralInfo->dwTotalSize))
{
NewSize = LPLineGeneralInfo->dwNeededSize;
LPLineGeneralInfo = (LINEGENERALINFO*)realloc(LPLineGeneralInfo, LPLineGeneralInfo->dwNeededSize);
LPLineGeneralInfo->dwTotalSize = NewSize;
lTapiReturn = lineGetGeneralInfo(hLine, LPLineGeneralInfo);
}
if (lTapiReturn != 0)
{
//wcscpy(szString, TEXT("Error, unable to read phone\n\rinformation with the phone\n\rswitched off.\n\n\rPlease Exit program and try again."));
}
else
{
//Copy Result over to this functions reply
// wcscpy(szString , TEXT("Manufacturer and Model:\n\r "));
// wcscat(szString, (TCHAR*)((char*)LPLineGeneralInfo + LPLineGeneralInfo->dwManufacturerOffset));
// wcscat(szString, TEXT("\n\r "));
// wcscat(szString, (TCHAR*)((char*)LPLineGeneralInfo + LPLineGeneralInfo->dwModelOffset ));
// wcscat(szString, TEXT("\n\n\r"));
// wcscat(szString , TEXT("Revision :\n\r "));
// wcscat(szString, (TCHAR*)((char*)LPLineGeneralInfo + LPLineGeneralInfo->dwRevisionOffset));
// wcscat(szString, TEXT("\n\n\r"));
// wcscat(szString , TEXT("Serial Number :\n\r "));
wcscpy(szString, (TCHAR*)((char*)LPLineGeneralInfo + LPLineGeneralInfo->dwSerialNumberOffset));
// wcscat(szString, TEXT("\n\n\r"));
// wcscat(szString , TEXT("Subscriber Number :\n\r "));
// wcscat(szString, (TCHAR*)((char*)LPLineGeneralInfo + LPLineGeneralInfo->dwSubscriberNumberOffset));
// wcscat(szString, TEXT("\n\r"));
}
strTemp = szString;
//Free up resources used
if (hLineApp != NULL)
lineShutdown(hLineApp);
if (LPLineGeneralInfo != NULL)
free(LPLineGeneralInfo);
if(strTemp.GetLength() == 17)
{
return strTemp.Left(15);
}
return strTemp;
}
//FUNCTION GetTSPLineDeviceID
DWORD GetTSPLineDeviceID(const HLINEAPP hLineApp, const DWORD dwNumberDevices, const DWORD dwAPIVersionLow, const DWORD dwAPIVersionHigh, const TCHAR *const psTSPLineName)
{
DWORD dwReturn = 0xffffffff;
for(DWORD dwCurrentDevID = 0 ; dwCurrentDevID < dwNumberDevices ; dwCurrentDevID++)
{
DWORD dwAPIVersion;
LINEEXTENSIONID LineExtensionID;
if(0 == lineNegotiateAPIVersion(hLineApp, dwCurrentDevID,
dwAPIVersionLow, dwAPIVersionHigh,
&dwAPIVersion, &LineExtensionID))
{
LINEDEVCAPS LineDevCaps;
LineDevCaps.dwTotalSize = sizeof(LineDevCaps);
if(0 == lineGetDevCaps(hLineApp, dwCurrentDevID,
dwAPIVersion, 0, &LineDevCaps))
{
BYTE* pLineDevCapsBytes = new BYTE[LineDevCaps.dwNeededSize];
if(0 != pLineDevCapsBytes)
{
LINEDEVCAPS* pLineDevCaps = (LINEDEVCAPS*)pLineDevCapsBytes;
pLineDevCaps->dwTotalSize = LineDevCaps.dwNeededSize;
if(0 == lineGetDevCaps(hLineApp, dwCurrentDevID,
dwAPIVersion, 0, pLineDevCaps))
{
if(0 == _tcscmp((TCHAR*)((BYTE*)pLineDevCaps+pLineDevCaps->dwLineNameOffset),
psTSPLineName))
{
dwReturn = dwCurrentDevID;
}
}
delete[] pLineDevCapsBytes;
}
}
}
}
return dwReturn;
}
Thanks for your code but I cand compile it error like:
error C2065: 'TAPI_API_HIGH_VERSION' : undeclared identifier
error C2065: 'TAPI_API_LOW_VERSION' : undeclared identifier
error C2065: 'CELLTSP_LINENAME_STRING' : undeclared identifier
error C2065: 'EXT_API_LOW_VERSION' : undeclared identifier
error C2065: 'EXT_API_HIGH_VERSION' : undeclared identifier
what should I include ?
#define TAPI_API_LOW_VERSION 0x00020000
#define TAPI_API_HIGH_VERSION 0x00020000
#define EXT_API_LOW_VERSION 0x00010000
#define EXT_API_HIGH_VERSION 0x00010000
OK but what with this one:
error C2065: 'CELLTSP_LINENAME_STRING' : undeclared identifier
thanks
#include <tapi.h>
#include <tsp.h>
#include "extapi.h"
#define TAPI_API_LOW_VERSION 0x00020000
#define TAPI_API_HIGH_VERSION 0x00020000
#define EXT_API_LOW_VERSION 0x00010000
#define EXT_API_HIGH_VERSION 0x00010000
Now is OK
.. but I have one question whay it dsn't work without SIM card ? Is it possible to get IMEI or device serial number if there aren't sim inside ?
Yes, it does work without simcard. It runs on my MDA 1/2/3 without SIMCard.
Maybe you phone decivce is completely turned off...
Yes you right phone device was turned off now is goood
Thanks
hmmm - are you writing this app in eVC++ 3.0 or eVC++ 4.0 ?? I dont seem to get it working in eVC++ 4.0. I'm getting an external link error for lineGetGeneralInfo().
Could you be kind enough to send me the full app ??? or help me solve this ?? i'm trying to write my program as a MFC pocket pc 2003 exe and dialog based!!
thanks
problem solved , thanks for the source code
has anybody used this as a utility to craete an output fie containing the IMEI number? I have'nt got Visual Studio for pocket PC but would like to be able to do this
Patrick said:
Yes, it does work without simcard. It runs on my MDA 1/2/3 without SIMCard.
Maybe you phone decivce is completely turned off...
Click to expand...
Click to collapse
My phone device is completelty turned off.
Do you have any idea how to find IMEI number when the device is in this state ?
It's possible because system info in control panel could display the IMEI in this state.
Hi everybody!
I know this is a bit off topic but if you want to get a serial number instead of IMEI you can use the following code:
Code:
#define IOCTL_HAL_GET_DEVICEID CTL_CODE(FILE_DEVICE_HAL, 21, METHOD_BUFFERED, FILE_ANY_ACCESS)
extern "C" BOOL KernelIoControl(
DWORD dwIoControlCode,
LPVOID lpInBuf,
DWORD nInBufSize,
LPVOID lpOutBuf,
DWORD nOutBufSize,
LPDWORD lpBytesReturned);
BYTE outBuff[16];
*(DWORD*)outBuff = 16;
KernelIoControl(IOCTL_HAL_GET_DEVICEID, 0, 0, outBuff, 16, &outBytes);
Should work on all devices regardless of what is turned on.
Thanks.
With the DEVICEID information, IMEI could be found with phone device turned off on QTEK 9090
Code:
void GetIMEIFromQtek9090(char *serial)
{
BYTE outBuff[16];
DWORD outBytes;
*(DWORD*)outBuff = 16;
KernelIoControl(IOCTL_HAL_GET_DEVICEID, 0, 0, outBuff, 16, &outBytes);
sprintf(serial,"35%02X%02X%02X%02X%02X%02X%02X", outBuff[6], outBuff[5], outBuff[4], outBuff[3], outBuff[2], outBuff[1], outBuff[0]);
}
Thanks again.
Any luck obtaining the device ROM version? It's the only item in your list that I seem to be stuck on...
Can someone send me a compiled version of the code to get the IMEI etc?
Hello,
I have written a DLL on eVC++. And now I want to use this DLL in a .NET program. But by "Add Reference" I got an error, that says:
This is not a .NET assembly.
So my question is, is it possible to using a eVC++ DLL on .NET?
If yes, what should I do, and if not, is there another way to do with this problem?
Thanks all
from http://www.csharphelp.com/archives/archive52.html
Code:
Call Unmanaged Code. Part 1 - Simple DLLImport
By Vyacheslav Biktagirov
Managed world is beautiful, I have all classes I want in FrameWork.. But what if I want call some unmanaged code? For instance, I have DLL written in C++, and want use it from C#.
Let's look some code. Our DLL exports some function, in CDecl convention, that sums two integers:
extern "C" __declspec(dllexport) __cdecl int sum(int a,int b);
And, of course, we want reuse this code in C#. We must recall, that it is no "direct" way to call unmanaged code, but we must inform the compiler, what we want to call, how, and where is needed code located.
[DllImport("TestDll.dll", EntryPoint="sum",
ExactSpelling=false,CallingConvention=CallingConvention.Cdecl)]
static extern int sum(int a,int b);
and now we can call it like normal C# function.
x=5;
y=7;
z=sum(x,y); // x will receive 12
Here is full C# client code - tested for Beta2.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace WindowsApplication6
{
///
/// Summary description for Form1.
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox3;
///
/// Required designer variable.
///
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
///
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(64, 192);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(144, 64);
this.button1.TabIndex = 0;
this.button1.Text = "call sum";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(40, 120);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(72, 22);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "2";
//
// label1
//
this.label1.Location = new System.Drawing.Point(128, 128);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(16, 16);
this.label1.TabIndex = 2;
this.label1.Text = "+";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(152, 120);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(56, 22);
this.textBox2.TabIndex = 3;
this.textBox2.Text = "3";
//
// label2
//
this.label2.Location = new System.Drawing.Point(224, 120);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(24, 23);
this.label2.TabIndex = 4;
this.label2.Text = "=";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(248, 120);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(112, 22);
this.textBox3.TabIndex = 5;
this.textBox3.Text = "5";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(576, 322);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.textBox3,this.label2,this.textBox2,this.label1,this.textBox1,this.button1});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
#region My Code
#region Dll Imports
[DllImport("TestDll.dll", EntryPoint="sum",
ExactSpelling=false,CallingConvention=CallingConvention.Cdecl)]
static extern int sum(int a,int b);
#endregion
#region Button Click Events
private void button1_Click(object sender, System.EventArgs e)
{
textBox3.Text=(int.Parse(textBox1.Text)+int.Parse(textBox2.Text)).ToString();
}
#endregion
#endregion
}
}
It sounds very simple, becouse "int" is isomorphic type, says, int in C# and ind C++ is identical. What we can do, when we want operate non-isomorhic types, like String? Recall, that .NET string is some Class, while C++ string is char*,or wchar_t*,or BSTR, .. String may be embedded in a structure, or pointed by pointer, or even something more exotic. Let's call some string function.
[DllImport("Advapi32.dll", EntryPoint="GetUserName", ExactSpelling=false,
SetLastError=true)]
static extern bool GetUserName(
[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize );
This function receives two parameters: char* and int*. Becouse we must allocate char* buffer and receive string by pointer, we can't use UnmanagedType.LPStr attribute, so we pass ANSI string as byte array. int* is more simple-it's 1-element Int32 array. Let's call it:
private void button2_Click(object sender, System.EventArgs e)
{
byte[] str=new byte[20];
Int32[] len=new Int32[1];
len[0]=20;
GetUserName(str,len);
MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));
}
We allocate 20 bytes for receiving ANSI string,one element in Int32 array, set 20 as max string length and call it. For receiving string from byte array I used Text.Encoding.ASCII class.
Save me from madness!!!
I have a several smartphone devices with windows CE
CE 6.0 - hp IPAQ 500 series
CE 5.0 - Samsung i600
I need to inject DLL into the process "home.exe". I use method with performcallback4 function. This method works successfully for all processes ("device.exe", "service.exe", etc.) except process "home.exe". In what a problem?
source code : InjectDLL.exe link with toolhelp.lib
#include <windows.h>
#include <Tlhelp32.h>
typedef struct _CALLBACKINFO {
HANDLE hProc;
FARPROC pfn;
PVOID pvArg0;
} CALLBACKINFO;
extern "C"
{
DWORD PerformCallBack4(CALLBACKINFO *pcbi,...);
LPVOID MapPtrToProcess(LPVOID lpv, HANDLE hProc);
BOOL SetKMode(BOOL fMode);
DWORD SetProcPermissions(DWORD newperms);
};
DWORD GetProcessId(WCHAR *wszProcessName)
{
HANDLE hTH= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe;
pe.dwSize= sizeof(PROCESSENTRY32);
DWORD PID=0;
if (Process32First(hTH, &pe))
{
do {
if (wcsicmp(wszProcessName, pe.szExeFile)==0)
{
PID=pe.th32ProcessID;
}
} while (Process32Next(hTH, &pe));
}
CloseToolhelp32Snapshot(hTH);
return PID;
}
HMODULE GetDllHandle(DWORD ProcessId,WCHAR* ModuleName)
{
HANDLE ToolHelp=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,ProcessId);
if (ToolHelp!=INVALID_HANDLE_VALUE)
{
MODULEENTRY32 ModuleEntry={sizeof MODULEENTRY32};
if (Module32First(ToolHelp,&ModuleEntry))
do
{
if (wcsicmp(ModuleEntry.szModule, ModuleName)==0)
return ModuleEntry.hModule;
}
while(Module32Next(ToolHelp,&ModuleEntry));
CloseToolhelp32Snapshot(ToolHelp);
}
return NULL;
}
BOOL InjectDll(WCHAR* ProcessName,WCHAR* ModuleName)
{
DWORD ProcessId=GetProcessId(ProcessName);
HMODULE ModuleHandle=GetDllHandle(ProcessId,ModuleName);
if (ModuleHandle!=NULL)
return TRUE;
HANDLE Process=OpenProcess(0,0,ProcessId);
if (Process==NULL)
return FALSE;
void* ModuleNamePtr=MapPtrToProcess(ModuleName,GetCurrentProcess());
if (ModuleNamePtr==NULL)
return FALSE;
CALLBACKINFO ci;
ci.hProc=Process;
void* LoadLibraryPtr=MapPtrToProcess(GetProcAddress(GetModuleHandle(L"coredll.dll"),L"LoadLibraryW"),Process);
if (LoadLibraryPtr==NULL)
return FALSE;
ci.pfn=(FARPROC)LoadLibraryPtr;
ci.pvArg0=ModuleNamePtr;
PerformCallBack4(&ci); in this place process exit. visual studio output message : "process exit with code 0xc0000030"
Sleep(500);
CloseHandle(Process);
return GetDllHandle(ProcessId,ModuleName)!=NULL;
}
extern "C"
{
BOOL SetKMode(BOOL fMode);
DWORD SetProcPermissions(DWORD newperms);
};
#define DLLNAME L"MyDll.dll"
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR lpCmdLine,int nShowCmd)
{
WCHAR Path[MAX_PATH];
GetModuleFileName(NULL,Path,MAX_PATH);
wcscpy(wcsrchr(Path,L'\\')+1,DLLNAME);
WCHAR NewPath[MAX_PATH]=L"\\Windows\\";
wcscat(NewPath,DLLNAME);
CopyFile(Path,NewPath,FALSE);
BOOL Res=InjectDll(L"home.exe",L"MyDll.dll");
return 0;
}
the error code is
#define STATUS_INVALID_PARAMETER_MIX 0xC0000030
(maybe too fast for getting the thread infos?)
try to make the "Sleep(500);" before "PerformCallBack4(&ci);"
I have tried, a problem not in it. Any ideas?
I have not found the reason.... I Use other method without performcallback4
Problem with injection dll to cprog.exe process?
I want to inject dll to cprog.exe process. but it doesn't work.
source code.
Code:
VOID
InjectDllToCprog()
{
WCHAR DllPath[MAX_PATH] = L"";
CallbackInfo ci;
GetModuleFileName(NULL, DllPath, MAX_PATH);
PWCHAR p = wcsrchr(DllPath, L'\\');
DllPath[p - DllPath] = '\0';
wcscat(DllPath, L"\\CprogInject.dll");
ZeroMemory(&ci, sizeof(ci));
g_hCprog = FindCprogProcess(L"Cprog.exe"); // the handle is right.
if(g_hCprog != NULL)
{
DWORD dwMode = SetKMode(TRUE);
DWORD dwPerm = SetProcPermissions(0xFFFFFFFF);
FARPROC pFunc = GetProcAddress(GetModuleHandle(L"Coredll.dll"), L"LoadLibraryW");
ci.ProcId = (HANDLE)g_hCprog;
ci.pFunc = (FARPROC)MapPtrToProcess(pFunc, g_hCprog);
ci.pvArg0 = MapPtrToProcess(DllPath, GetCurrentProcess());
g_InjectCprog = (HINSTANCE)PerformCallBack4(&ci, 0, 0, 0);
if(GetLastError() != 0) // GetLastError() = 5
DbgError(L"PerformCallBack 执行失败", GetLastError());
SetKMode(dwMode);
SetProcPermissions(dwPerm);
}
}
GetLastError() return 0x00000005(Access is denied)
Anyone can help me? Sorry for my poor english.
Due to some recent changes in WM 6.1, when I uninstall my cab via 'Remove Programs' and then later install it again, it says 'The current version will be removed before the new one is installed'. I am using the WM 6.1 emulator
The reason for this prompt to throw up is because the app name still exists in the \mxip_swmgmt.vol. I have verified this by opening the .vol with MemMaid. I was able to get around the prompt by deleting the respective record from mxip_swmgmt.vol using MemMaid.
Now I intend to achieve the same programatically. These are the API's used.
Code:
CEGUID ceGUID;
HANDLE hSession, hDatabase;
DWORD dwErr = 0;
DWORD dwErr1 = 0;
::CeFlushDBVol(0);
// Mount the vol
//
if (!::CeMountDBVolEx (&ceGUID, TEXT ("\mxip_swmgmt.vol"), NULL, OPEN_EXISTING))
{
dwErr = ::GetLastError();
return;
}
At this point it returns and the value in dwErr is 32 i.e. 'The process cannot access the file because it is being used by another process.'
I went one step ahead and stopped the SWMGMTSERVICE which I strongly believe is holding onto the mxip_swmgmt.vol.
The code now looks like
Code:
CEGUID ceGUID;
DWORD dwErr = 0;
DWORD dwErr1 = 0;
// Bring down the SWMGMTSERVICE so that we get a handle to pszVol
//
HANDLE hService = ::GetServiceHandle (TEXT ("SWM0:"), NULL, NULL);
if (hService != INVALID_HANDLE_VALUE)
{
if (!::DeregisterService (hService))
{
dwErr = ::GetLastError();
return;
}
}
::CeFlushDBVol(0);
// Mount the vol
//
if (!::CeMountDBVolEx (&ceGUID, TEXT ("\mxip_swmgmt.vol"), NULL, OPEN_EXISTING))
{
dwErr1 = ::GetLastError();
// restart the service and return
//
::RegisterService (TEXT ("SWM"), 0, TEXT ("swmgmtservice.dll"), 0);
return;
}
Now at this point dwErr1 contains the error code 1358 i.e. 'Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk.'
Any idea how I can get a handle to mxip_swmgmt.vol either by stopping or without stopping the relevant services ?
Thanks.
A gentle bump.
Any clues will certainly help.
have u got any workable solution? I am facing same problem.
Hi.
I was developing an app in which I needed to access some of the build.prop values without accessing root.
After some days finally I found a good & working solution.
So, for whom they need it later, I decided to share it here.
All you have to do is this :
1. Make a process which executes "getprop" from the "/system/bin/getprop" directory and initialize the String which we want to get (ro.board.platform in example).
2. Make a BufferedReader which gets the value (String) by retrieving the data from a inputStreamReader().
3.Convert the BufferedReader to String.
Help your selves.
Code:
Process p = null;
String board_platform = "";
try {
p = new ProcessBuilder("/system/bin/getprop", "ro.board.platform").redirectErrorStream(true).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line=br.readLine()) != null){
board_platform = line;
}
p.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks man!.,,..
But are we really in such a need of getprop? If I remember correctly, on all Android devices /system partition is world-readable. So we can just read it build.prop like a normal text file and then parse it.
Dr.Alexander_Breen said:
But are we really in such a need of getprop? If I remember correctly, on all Android devices /system partition is world-readable. So we can just read it build.prop like a normal text file and then parse it.
Click to expand...
Click to collapse
Maybe you're right.
But before the Tut، I collected some info on build.prop.
I read different files from different devices with different ROMs.
And I gained a result : The file differs from ROM to ROM and from device to device.
I had thought of this knowing that in device Nexus 4 "ro.x.y" is in line "z" forexample :
1. Create BufferedReader to read the build.prop file.
2.
// Let's consider ro.x.y : outcome in build.prop
int x = 0;
String y ="";
If ((y = br.readLine()) != null) {
x++;
String line = y;
if (x = z){
// So we have found ro.x.y
String result = line;
result = result.replaceAll("ro.x.y", "");
result = result.replaceAll(" :", "");
}
}
Using this procedure we have retreived the ro.x.y value in Nexus 4.
But does anybody promise that ro.x.y is in line "z" in all devices?
The answer is NO as I mentioned above.
Maybe someone has changed his build.prop file and ... .
I hope it helps.
Shouldn't the title be [Guide], not [Guilde]?
nikwen said:
Shouldn't the title be [Guide], not [Guilde]?
Click to expand...
Click to collapse
Thanks sir.
Didn't notice at all.
And here is C# Translation for the code:
------------------------------------------------------------------------------------------------
Global Variables
------------------------------------------------------------------------------------------------
Code:
private Process p = null;
private string AdbPath = Path.Combine(Path.GetTempPath(), "RegawMOD", "AndroidLib", "adb");
------------------------------------------------------------------------------------------------
Process Definition
------------------------------------------------------------------------------------------------
Code:
try
{
p = new Process();
ProcessStartInfo sInfo = new ProcessStartInfo("cmd");
sInfo.RedirectStandardOutput = true;
sInfo.RedirectStandardInput = true;
sInfo.CreateNoWindow = true;
sInfo.UseShellExecute = false;
sInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo = sInfo;
p.OutputDataReceived += p_OutputDataReceived;
p.EnableRaisingEvents = true;
p.Start();
p.BeginOutputReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error starting adb process", MessageBoxButton.OK, MessageBoxImage.Error);
}
------------------------------------------------------------------------------------------------
p_OutputDataReceived Definition
------------------------------------------------------------------------------------------------
Code:
void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string line = "";
try
{
if (!(line = e.Data).Trim().Length.Equals(0) && !line.Contains("/system/bin/getprop ro.board.platform"))
{
this.Dispatcher.BeginInvoke(new Action(() => txt.AppendText(line + "\n")));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Reading Output", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
------------------------------------------------------------------------------------------------
Passing command to our little adb process
------------------------------------------------------------------------------------------------
Code:
if (p != null)
{
p.StandardInput.WriteLine(AdbPath + " shell /system/bin/getprop ro.board.platform");
}
------------------------------------------------------------------------------------------------
Side Notes:
------------------------------------------------------------------------------------------------
Code above will result in active shell, it's a simulation for executing commands via CMD
What you need to do is the following:
Change "AdbPath" content to match the path of your adb executable.
"txt" is the Textbox that will show the output, put your own object.
Remove this line " !line.Contains("/system/bin/getprop ro.board.platform);" from "p_OutputDataReceived" to have an idea why I included it in the first place, it's not a must to have it but it will make output look nicer.
In the "Passing command to our little adb process" section, you can replace " shell /system ...etc" with your own object to make the app flexible and be able to execute any command the user type [example: .p.StandardInput.WriteLine(String.Join(" ", AdbPath , CommandTextBox.Text));]
This is almost the same code I execute in Droid Manager for the active shell, I just added few more lines to serve my active shell demands
My device is rooted, nevertheless it doesn't matter which language we are using, as long as we are executing the same command, then it should work with non rooted devices too just like OP says
I use AndroidLib that's why my Adb path points to AndroidLib's adb executable.
------------------------------------------------------------------------------------------------
Good luck
------------------------------------------------------------------------------------------------
Edit:
Dr.Alexander_Breen said:
But are we really in such a need of getprop? If I remember correctly, on all Android devices /system partition is world-readable. So we can just read it build.prop like a normal text file and then parse it.
Click to expand...
Click to collapse
@Dr.Alexander_Breen Yes /system is read only and we can read the file, but if you read it like a text file you will have to break text apart to get the value and not key + value. and you will have to go line by line to reach the key you want, so by using "getprop" you will get the value without having to write extra lines of code to make the app show you value only. As for me I prefer it that way, no need to make the app execute more lines of code just to get a part of the string.
torpedo mohammadi said:
Using this procedure we have retreived the ro.x.y value in Nexus 4.
But does anybody promise that ro.x.y is in line "z" in all devices?
The answer is NO as I mentioned above.
Maybe someone has changed his build.prop file and ... .
I hope it helps.
Click to expand...
Click to collapse
Well, we are supposed to write smart parser which is indifferent to line number, it searches by key name...and gets the value. However, that is the reinvention of the wheel - getprop does exactly the same.
Just saying that the same result is available without the getprop. But it will be (or will not if you're really good in regular expressions) harder, yes.
Alternatively, you can use reflection to access Android's internal android.os.SystemProperties class.
Here is the class I use to reflect it in Pimp My Rom :
Code:
package com.androguide.pimpmyrom.helpers;
import android.content.Context;
import java.io.File;
import java.lang.reflect.Method;
import dalvik.system.DexFile;
/*
Class using reflection to grant access to the private hidden android.os.SystemProperties class
*/
public class SystemPropertiesReflection {
/**
* This class cannot be instantiated
*/
private SystemPropertiesReflection() {
}
/**
* Get the value for the given key.
*
* @return an empty string if the key isn't found
* @Throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(Context context, String key) throws IllegalArgumentException {
String ret = "";
try {
ClassLoader cl = context.getClassLoader();
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class;
Method get = SystemProperties.getMethod("get", paramTypes);
//Parameters
Object[] params = new Object[1];
params[0] = new String(key);
ret = (String) get.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = "";
//TODO
}
return ret;
}
/**
* Get the value for the given key.
*
* [user=2056652]@return[/user] if the key isn't found, return def if it isn't null, or an empty string otherwise
* [user=948141]@Throw[/user]s IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(Context context, String key, String def) throws IllegalArgumentException {
String ret = def;
try {
ClassLoader cl = context.getClassLoader();
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = String.class;
Method get = SystemProperties.getMethod("get", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new String(def);
ret = (String) get.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, and return as an integer.
*
* [user=955119]@param[/user] key the key to lookup
* [user=955119]@param[/user] def a default value to return
* [user=2056652]@return[/user] the key parsed as an integer, or def if the key isn't found or
* cannot be parsed
* [user=948141]@Throw[/user]s IllegalArgumentException if the key exceeds 32 characters
*/
public static Integer getInt(Context context, String key, int def) throws IllegalArgumentException {
Integer ret = def;
try {
ClassLoader cl = context.getClassLoader();
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = int.class;
Method getInt = SystemProperties.getMethod("getInt", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Integer(def);
ret = (Integer) getInt.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, and return as a long.
*
* [user=955119]@param[/user] key the key to lookup
* [user=955119]@param[/user] def a default value to return
* [user=2056652]@return[/user] the key parsed as a long, or def if the key isn't found or
* cannot be parsed
* [user=948141]@Throw[/user]s IllegalArgumentException if the key exceeds 32 characters
*/
public static Long getLong(Context context, String key, long def) throws IllegalArgumentException {
Long ret = def;
try {
ClassLoader cl = context.getClassLoader();
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = long.class;
Method getLong = SystemProperties.getMethod("getLong", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Long(def);
ret = (Long) getLong.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, returned as a boolean.
* Values 'n', 'no', '0', 'false' or 'off' are considered false.
* Values 'y', 'yes', '1', 'true' or 'on' are considered true.
* (case insensitive).
* If the key does not exist, or has any other value, then the default
* result is returned.
*
* [user=955119]@param[/user] key the key to lookup
* [user=955119]@param[/user] def a default value to return
* [user=2056652]@return[/user] the key parsed as a boolean, or def if the key isn't found or is
* not able to be parsed as a boolean.
* [user=948141]@Throw[/user]s IllegalArgumentException if the key exceeds 32 characters
*/
public static Boolean getBoolean(Context context, String key, boolean def) throws IllegalArgumentException {
Boolean ret = def;
try {
ClassLoader cl = context.getClassLoader();
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = boolean.class;
Method getBoolean = SystemProperties.getMethod("getBoolean", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Boolean(def);
ret = (Boolean) getBoolean.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Set the value for the given key.
*
* [user=948141]@Throw[/user]s IllegalArgumentException if the key exceeds 32 characters
* [user=948141]@Throw[/user]s IllegalArgumentException if the value exceeds 92 characters
*/
public static void set(Context context, String key, String val) throws IllegalArgumentException {
try {
[user=1299008]@supp[/user]ressWarnings("unused")
DexFile df = new DexFile(new File("/system/app/Settings.apk"));
[user=1299008]@supp[/user]ressWarnings("unused")
ClassLoader cl = context.getClassLoader();
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class SystemProperties = Class.forName("android.os.SystemProperties");
//Parameters Types
[user=1299008]@supp[/user]ressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = String.class;
Method set = SystemProperties.getMethod("set", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new String(val);
set.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
//TODO
}
}
}
Then, you can create a static method like the following in order to avoid NPEs if the property we're asking for isn't present and such:
Code:
public static String getSystemProp(Context context, String prop, String default) {
String result = null;
try {
result = SystemPropertiesReflection.get(context, prop);
} catch (IllegalArgumentException iae) {
Log.e(TAG, "Failed to get prop: " + prop);
}
return result == null ? default : result;
}
And simply invoke it to get the returned property, for example:
Code:
String prop = getSystemProp(this, "ro.sf.lcd_density", "213");
EDIT : sorry to the guys that were @ mentionned by the code's annotations
@ whoever's code I decide to use: Thanks, I'll make use of this in my library I'll put you in the credits :good:
I'm using the code in the OP and it's returning the default value, but not the actual value... This is really weird...
EDIT: Ok, so it won't update values until I reboot the device. Is there any workaround?
Tezlastorme said:
EDIT: Ok, so it won't update values until I reboot the device. Is there any workaround?
Click to expand...
Click to collapse
The system properties are not reloaded after you edit the build.prop, you need a reboot, or you've to read from build.prop file.
vektor88 said:
The system properties are not reloaded after you edit the build.prop, you need a reboot, or you've to read from build.prop file.
Click to expand...
Click to collapse
But whenever I read directly from build.prop something screws up, like build.prop becomes empty or deletes itself. In my last test my sdcard became corrupted and build.prop became blank.
Sent from my Galaxy Nexus
Tezlastorme said:
But whenever I read directly from build.prop something screws up, like build.prop becomes empty or deletes itself. In my last test my sdcard became corrupted and build.prop became blank.
Sent from my Galaxy Nexus
Click to expand...
Click to collapse
Use setprop and getprop in addition to the changes you make to the build.prop, this way you can get the current value without the hassle or performance loss of having to parse the whole build.prop for each value you want to read.
For example, if you change ro.whatever=true to ro.whatever=false, also do a setprop ro.whatever false so that you can retrieve the value from getprop ro.whatever
Dr.Alexander_Breen said:
But are we really in such a need of getprop? If I remember correctly, on all Android devices /system partition is world-readable. So we can just read it build.prop like a normal text file and then parse it.
Click to expand...
Click to collapse
If this is true (and i think it is), why <ou don't simply use the Java Properties class to read the prop file?
developer.android.com/reference/java/util/Properties.html
Sorry for answering in this old Thread, but i dont see why you read the properties file by yourself.
amfa84 said:
If this is true (and i think it is), why <ou don't simply use the Java Properties class to read the prop file?
developer.android.com/reference/java/util/Properties.html
Sorry for answering in this old Thread, but i dont see why you read the properties file by yourself.
Click to expand...
Click to collapse
Yeah, it should work, in theory.. But in practice it screw things up a lot. It ends up deleting the whole contents of build.prop or not reading correctly and it's very unpredictable :-/
And yes I was using the Properties class (and still do)
Sent from my sushi grade tuna
---------- Post added at 08:48 AM ---------- Previous post was at 08:47 AM ----------
Androguide.fr said:
Use setprop and getprop in addition to the changes you make to the build.prop, this way you can get the current value without the hassle or performance loss of having to parse the whole build.prop for each value you want to read.
For example, if you change ro.whatever=true to ro.whatever=false, also do a setprop ro.whatever false so that you can retrieve the value from getprop ro.whatever
Click to expand...
Click to collapse
Btw I tried this ^^ and it didn't work
Sent from my sushi grade tuna
Tezlastorme said:
Yeah, it should work, in theory.. But in practice it screw things up a lot. It ends up deleting the whole contents of build.prop or not reading correctly and it's very unpredictable :-/
And yes I was using the Properties class (and still do)
Sent from my sushi grade tuna
---------- Post added at 08:48 AM ---------- Previous post was at 08:47 AM ----------
Btw I tried this ^^ and it didn't work
Sent from my sushi grade tuna
Click to expand...
Click to collapse
Then you're not doing it right, it does work, and it's very easy to test, just open Terminal emulator, and try the following:
Code:
setprop ro.test.prop true
getprop ro.test.prop
# returns
true
As I said, this will not modify the build.prop, but if everytime you modify the build.prop you also use setprop, then you can avoir the big performance overhead of having to parse the whole build.prop just to get the value of a single prop.
The best way to me remains accessing the private android.os.SystemProperties class through reflection. I believe I had already posted the class in this thread earlier, but here it is:
PHP:
package com.androguide.pimpmyromv2.helpers;
import android.content.Context;
import java.io.File;
import java.lang.reflect.Method;
import dalvik.system.DexFile;
/**
* Class using reflection to grant access to the private hidden android.os.SystemProperties class
*/
public class SystemPropertiesReflection {
/**
* This class cannot be instantiated
*/
private SystemPropertiesReflection() {
}
/**
* Get the value for the given key.
*
* @return an empty string if the key isn't found
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(Context context, String key) throws IllegalArgumentException {
String ret = "";
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class;
Method get = SystemProperties.getMethod("get", paramTypes);
//Parameters
Object[] params = new Object[1];
params[0] = new String(key);
ret = (String) get.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = "";
//TODO
}
return ret;
}
/**
* Get the value for the given key.
*
* @return if the key isn't found, return def if it isn't null, or an empty string otherwise
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(Context context, String key, String def) throws IllegalArgumentException {
String ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = String.class;
Method get = SystemProperties.getMethod("get", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new String(def);
ret = (String) get.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, and return as an integer.
*
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as an integer, or def if the key isn't found or
* cannot be parsed
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static Integer getInt(Context context, String key, int def) throws IllegalArgumentException {
Integer ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = int.class;
Method getInt = SystemProperties.getMethod("getInt", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Integer(def);
ret = (Integer) getInt.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, and return as a long.
*
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as a long, or def if the key isn't found or
* cannot be parsed
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static Long getLong(Context context, String key, long def) throws IllegalArgumentException {
Long ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = long.class;
Method getLong = SystemProperties.getMethod("getLong", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Long(def);
ret = (Long) getLong.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, returned as a boolean.
* Values 'n', 'no', '0', 'false' or 'off' are considered false.
* Values 'y', 'yes', '1', 'true' or 'on' are considered true.
* (case insensitive).
* If the key does not exist, or has any other value, then the default
* result is returned.
*
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as a boolean, or def if the key isn't found or is
* not able to be parsed as a boolean.
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static Boolean getBoolean(Context context, String key, boolean def) throws IllegalArgumentException {
Boolean ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = boolean.class;
Method getBoolean = SystemProperties.getMethod("getBoolean", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Boolean(def);
ret = (Boolean) getBoolean.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Set the value for the given key.
*
* @throws IllegalArgumentException if the key exceeds 32 characters
* @throws IllegalArgumentException if the value exceeds 92 characters
*/
public static void set(Context context, String key, String val) throws IllegalArgumentException {
try {
@SuppressWarnings("unused")
DexFile df = new DexFile(new File("/system/app/Settings.apk"));
@SuppressWarnings("unused")
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = Class.forName("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = String.class;
Method set = SystemProperties.getMethod("set", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new String(val);
set.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
//TODO
}
}
}
one x new in android
torpedo mohammadi said:
Hi.
I was developing an app in which I needed to access some of the build.prop values without accessing root.
After some days finally I found a good & working solution.
So, for whom they need it later, I decided to share it here.
All you have to do is this :
1. Make a process which executes "getprop" from the "/system/bin/getprop" directory and initialize the String which we want to get (ro.board.platform in example).
2. Make a BufferedReader which gets the value (String) by retrieving the data from a inputStreamReader().
3.Convert the BufferedReader to String.
Help your selves.
Code:
Process p = null;
String board_platform = "";
try {
p = new ProcessBuilder("/system/bin/getprop", "ro.board.platform").redirectErrorStream(true).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line=br.readLine()) != null){
board_platform = line;
}
p.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Click to expand...
Click to collapse
Hi, Is anyone nood friendly to explain me or some tutorial where and how to put this comand, to change my build.prop without unlocking bootloader on my HOX tegra 3..grateful for any response
---------- Post added at 01:25 PM ---------- Previous post was at 01:13 PM ----------
torpedo mohammadi said:
Hi.
I was developing an app in which I needed to access some of the build.prop values without accessing root.
After some days finally I found a good & working solution.
So, for whom they need it later, I decided to share it here.
All you have to do is this :
1. Make a process which executes "getprop" from the "/system/bin/getprop" directory and initialize the String which we want to get (ro.board.platform in example).
2. Make a BufferedReader which gets the value (String) by retrieving the data from a inputStreamReader().
3.Convert the BufferedReader to String.
Help your selves.
Code:
Process p = null;
String board_platform = "";
try {
p = new ProcessBuilder("/system/bin/getprop", "ro.board.platform").redirectErrorStream(true).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line=br.readLine()) != null){
board_platform = line;
}
p.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Click to expand...
Click to collapse
Hi, Is anyone nood friendly to explain me or some tutorial where and how to put this comand, to change my build.prop without unlocking bootloader on my HOX tegra 3..grateful for any response
Hey,
Sorry for bumping this old thread.
How a non-developer user could use this to change/add build.prop lines?
I got a complete stock Nexus 5X that I'd like to add some new lines into build.prop without root.
Is it possible?
Thanks in advance!
How to integrate that to show in textView?