Hi there!
I am trying to send AT commands to the built-in GSM modem of my PDA, in order to get the signal quality (AT+CSQ). I am using the Himalaya Qtek2020.
It is important to implement it with C# using the .NET compact framework. By now, i am using the following code to connect to the modem, but the received data is useless (i.e. p?x??04? ...):
Code:
private void ConnectGPRS()
{
try
{
serialport.CommPort = cboGPRS.SelectedIndex+1;
serialport.BitRate = 9600;
serialport.DataBits = 8;
serialport.RTSEnable = false;
serialport.DTREnable = true;
serialport.StopBits = 1;
serialport.EnableOnComm = true;
serialport.PortOpen = true;
//serialport.Timeout = 5;
//An Port schicken:
ASCIIEncoding enc = new ASCIIEncoding();
byte[] Buffer = enc.GetBytes(txtAT.Text+"\r\n"); //Text in byte-Array
serialport.Output(Buffer); //An Port schicken
}
catch (Exception ex)
{
MessageBox.Show (ex.Message+"\n"+ex.InnerException);
}
}
//Eventhandler
private void DataReceived()
{
byte[] buffer = new byte[128];
//use ASCII encoding to work with string and byte
ASCIIEncoding enc = new ASCIIEncoding();
// read input text
buffer = serialport.InputArray(); //Byte-Array vom Port auslesen
MessageBox.Show(enc.GetString(buffer,0,buffer.Length-1));
}
Can i communicate with the modem using the serial COM ports, or do i have to use the RIL ports?
I have found a lot of C++ sample code, but i am looking for a C# solution.
Can someone help me please?
Thanks,
C.J.
Related
Hi !
I testing make Out of procces server on XDA II (MDA II) in eVc++4. I have problems
with this. If i called in client this :
IComMDA m_ComMda;
COleException m_Error;
if (m_ComMda.CreateDispatch(_T("ComMDA.Document"),&m_Error))
{
AfxMessageBox(_T("CreateDispatch - TRUE"),MB_OK,0);
return TRUE;
}
else
{
AfxMessageBox(_T("CreateDispatch - FALSE"),MB_OK,0);
return FALSE;
}
the error occur
==> CreateDispatch returning scode = severity: SEVERITY_ERROR, facility:
FACILITY_WIN32 ($800700C1).
IComMDA is class created from typelibrary :
class IComMDA : public COleDispatchDriver
{
public:
IComMDA() {} // Calls COleDispatchDriver default constructor
IComMDA(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
IComMDA(const IComMDA& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Attributes
public:
// Operations
public:
BOOL InitInterface();
};
interface is declared :
[ uuid(713B5595-EF1F-4961-A179-E374E0C82903), version(1.0) ]
library ComMDA
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
// Primary dispatch interface for CComMDADoc
[ uuid(901AD61B-9974-448a-9E79-7898E0C80FFE) ]
dispinterface IComMDA
{
properties:
// NOTE - ClassWizard will maintain property information here.
// Use extreme caution when editing this section.
//{{AFX_ODL_PROP(CComMDADoc)
//}}AFX_ODL_PROP
methods:
// NOTE - ClassWizard will maintain method information here.
// Use extreme caution when editing this section.
//{{AFX_ODL_METHOD(CComMDADoc)
[id(1)] boolean InitInterface();
//}}AFX_ODL_METHOD
};
// Class information for CComMDADoc
[ uuid(E523187A-FFB7-46e9-AA64-A6CB1BEAF9BB) ]
coclass Document
{
[default] dispinterface IComMDA;
};
//{{AFX_APPEND_ODL}}
//}}AFX_APPEND_ODL}}
};
Class is registered as :
CString strServerName;
CString strLocalServerName;
CString strLocalShortName;
CString strLocalFilterName;
CString strLocalFilterExt;
if (!m_pDocTemplate->GetDocString(strServerName,
CDocTemplate::regFileTypeId) || strServerName.IsEmpty())
{
return;
}
if (!m_pDocTemplate->GetDocString(strLocalServerName,
CDocTemplate::regFileTypeName))
strLocalServerName = strServerName; // use non-localized name
if (!m_pDocTemplate->GetDocString(strLocalShortName,
CDocTemplate::fileNewName))
strLocalShortName = strLocalServerName; // use long name
if (!m_pDocTemplate->GetDocString(strLocalFilterName,
CDocTemplate::filterName))
ASSERT(nAppType != OAT_DOC_OBJECT_SERVER);
if (!m_pDocTemplate->GetDocString(strLocalFilterExt,
CDocTemplate::filterExt))
ASSERT(nAppType != OAT_DOC_OBJECT_SERVER);
ASSERT(strServerName.Find(' ') == -1); // no spaces allowed
int nIconIndex = 0;
POSITION pos = AfxGetApp()->GetFirstDocTemplatePosition();
for (int nIndex = 1; pos != NULL; nIndex++)
{
CDocTemplate* pTemplate = AfxGetApp()->GetNextDocTemplate(pos);
if (pTemplate == m_pDocTemplate)
{
nIconIndex = nIndex;
pos = NULL; // set exit condition
}
}
BOOL bResult = FALSE;
if (TRUE)
{
// call global helper to modify system registry
// progid, shortname, and long name are all equal in this case
if (!(bResult = AfxOleRegisterServerClass(m_clsid, strServerName,
strLocalShortName, strLocalServerName, nAppType,
rglpszRegister, rglpszOverwrite, nIconIndex,
strLocalFilterName, strLocalFilterExt)))
{
// not fatal (don't fail just warn)
AfxMessageBox(AFX_IDP_FAILED_TO_AUTO_REGISTER);
}
}
else
{
bResult = AfxOleUnregisterServerClass(m_clsid, m_lpszProgID, m_lpszProgID,
m_lpszProgID, OAT_DISPATCH_OBJECT);
}
return;
------------------------------------------------
type library is registered as AfxOleRegisterTypeLib(AfxGetInstanceHandle(),
clsid);
where >// {713B5595-EF1F-4961-A179-E374E0C82903}
static const GUID clsid =
{ 0x713b5595, 0xef1f, 0x4961, { 0xa1, 0x79, 0xe3, 0x74, 0xe0, 0xc8, 0x29,
0x3 } };
Thanks for your help.
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.
Hey all
I have the following function to generate the http headers for a GET request on an image file:
Code:
byte [] headersAndImage()
{
StringBuilder s = new StringBuilder();
s.Append("HTTP/1.1 200 OK\r\n");
s.Append("Date: Tue, 17 Aug 2010 11:40:00 GMT\r\n");
s.Append("Vary: *\r\n");
s.Append("Server: Custommade\r\n");
s.Append("Content-Type: image/jpeg\r\n");
Bitmap b = new Bitmap("\\dog.jpg");
MemoryStream ms = new MemoryStream();
b.Save(ms, ImageFormat.Jpeg );
byte[] bitmapData = ms.ToArray();
ms.Close();
s.Append("Content-Length: " + bitmapData.Length + "\r\n\r\n");
byte[] headers = Encoding.ASCII.GetBytes(s.ToString());
return join(headers,bitmapData);
}
however when a browser receives this http packet the image is never displayed, usually just see the red X.
Any ideas why this won't work?
Here is the code that works for me:
Code:
public void TransmitFile(byte[] file, string fileName)
{
MemoryStream fileStream = new MemoryStream();
fileStream.Write(file, 0, file.Length);
fileStream.Position = 0;
var response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.ContentType = @"application/force-download\n";
response.AppendHeader(@"Content-Disposition",
String.Format(@"attachment;filename=""{0}""", fileName));
long bytesToGo;
int bytesRead;
Byte[] buffer = new byte[1048576]; //1 MB buffer, you may want to use whatever fits your environment
bytesToGo = fileStream.Length;
while (bytesToGo > 0)
{
if (response.IsClientConnected)
{
bytesRead = fileStream.Read(buffer, 0, 1048576);
response.OutputStream.Write(buffer, 0, bytesRead);
response.Flush();
bytesToGo -= bytesRead;
if (bytesRead == 0)
{
break; ;
}
}
else
{
bytesToGo = -1;
}
}
fileStream.Close();
response.Flush();
response.End();
}
Hello,
for my app, which needs to communicate with a HC-06 Bluetooth module, I modified the bluetooth chat example.
Then and now the process of creating sockets failes and I do not know why. I did not change anythin in that part, except for the UUID:
Code:
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID MY_UUID_INSECURE =
UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
For the ones, who do not know, what the connectThread looks like:
Code:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
secure = false;
/*Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);*/
//UUID uuid = mmDevice.getUuids()[0].getUuid();
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE );
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
} catch (Exception e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
ServerAccess.errorLog(e);
}
mmSocket = tmp;
}
Does anyone know, what to do?
I already tried to change the UUID and to reflect the Method "createRFCommSocket".
Please help me!