CF Creazione di un database

L’esempio di codice qui riportato, illustra una tecnica di come creare una database in ambiente windows Mobile.
Dopo aver aggiunto i riferimenti (dal menu progetti,selezionare aggiungi riferimenti) System.data.Sqlce e System.data , aggiungere i namespace per la gestione dei database.
Di seguito si riportano i namaspace.

VB.Net

Imports System.IO

Imports System.Data.SqlServerCe

Imports System.Data

C#

using System.Data.SqlServerCe;

La creazione del database, avviene nell’evento click di un pulsante inserito precedentemente.

VB.Net

 

  Private Sub BtnCreaDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCreaDB.Click

 

        Dim conDati As SqlCeConnection

        Try

            ‘elimino eventualmente il db creato

            System.IO.File.Delete(“\My Documents\Miodb.sdf”)

 

            Dim SQLEngine As New SqlCeEngine(“data source=\My Documents\Miodb.sdf”)

            SQLEngine.CreateDatabase()

 

            ‘ mi connetto al db

            conDati = New SqlCeConnection(“Data Source=\My Documents\Miodb.sdf”)

            conDati.Open()

 

            ‘Creazione di un tabella

            Dim SQL As [String] = “CREATE TABLE MiaTabella (ID int Primary Key “ + “NOT NULL,Nome nvarchar(50) NOT NULL)”

            Dim cmdDati As New SqlCeCommand(SQL, conDati)

            cmdDati.CommandType = CommandType.Text

            cmdDati.ExecuteNonQuery()

            SQL = “”

 

            ‘Inserisco i dati

            SQL = “INSERT INTO MiaTabella (ID, Nome) VALUES “ + “(’0′,’Emanuele’)”

            cmdDati.CommandText = SQL

            cmdDati.ExecuteNonQuery()

 

            SQL = “”

            SQL = “INSERT INTO MiaTabella (ID, Nome) VALUES “ + “(’1′,’Emanuele2′)”

            cmdDati.CommandText = SQL

            cmdDati.ExecuteNonQuery()

 

            SQL = “”

            SQL = “Select * from  MiaTabella “

            cmdDati.CommandText = SQL

            Dim rdrDati As SqlCeDataReader = cmdDati.ExecuteReader()

            While rdrDati.Read()

                MessageBox.Show(rdrDati.GetString(1))

            End While

 

 

        Catch ex As SqlCeException

            MessageBox.Show(ex.Message)

        Finally

            conDati.Close()

        End Try

 

C#

private void btnCreaDB_Click(object sender, EventArgs e)

        {

            SqlCeConnection conDati = null;

            try

            {

                //elimino eventualmente il db creato

                System.IO.File.Delete(@”\My Documents\Miodb.sdf”);

 

                SqlCeEngine SQLEngine = new SqlCeEngine(“data source=” + @”\My Documents\Miodb.sdf”);

                SQLEngine.CreateDatabase();

 

                // mi connetto al db

                conDati = new SqlCeConnection(“Data Source=” + @”\My Documents\Miodb.sdf”);

                conDati.Open();

 

                //Creazione di un tabella

                string SQL = “CREATE TABLE MiaTabella (ID int Primary Key “ + “NOT NULL,Nome nvarchar(50) NOT NULL)”;

                SqlCeCommand cmdDati = new SqlCeCommand(SQL, conDati);

                cmdDati.CommandType = CommandType.Text;

                cmdDati.ExecuteNonQuery();

                SQL = “”;

 

                //Inserisco i dati

                SQL = “INSERT INTO MiaTabella (ID, Nome) VALUES “ + “(’0′,’Emanuele’)”;

                cmdDati.CommandText = SQL;

                cmdDati.ExecuteNonQuery();

 

                SQL = “”;

                SQL = “INSERT INTO MiaTabella (ID, Nome) VALUES “ + “(’1′,’Emanuele2′)”;

                cmdDati.CommandText = SQL;

                cmdDati.ExecuteNonQuery();

 

                SQL = “”;

                SQL = “Select * from  MiaTabella “;

                cmdDati.CommandText = SQL;

                SqlCeDataReader rdrDati = cmdDati.ExecuteReader();

                while (rdrDati.Read())

                {

                    MessageBox.Show(rdrDati.GetString(1));

                }

 
            }

 

            catch (SqlCeException ex)

            {

                MessageBox.Show(ex.Message);

 

            }

            finally

            {

                conDati.Close();

 

            }

 

        }

Tramite la parola Download, è possibile scaricare il file di esempio
Download

CF utilizzare le api di Windows Mobile, per effettuare le telefonate o rilevare informazioni alla SIM tramite C#

Questo esempio di codice, illustra come utilizzare le api di Windows Mobile, per effettuare delle telefonate e rilevare informazioni della SIM.

Effettuare una telefonata:

Namespace:

 

using

 

System.Runtime.InteropServices;

A livello di classe creare la seguente struttura e i due campi.

 

 

 

 

 

private static long PMCF_DEFAULT = 0×00000001;private static long PMCF_PROMPTBEFORECALLING = 0×00000002;private struct PhoneMakeCallInfo{

 

 

 

 

 

 

}

 

public IntPtr cbSize;public IntPtr dwFlags;public IntPtr pszDestAddress;public IntPtr pszAppName;public IntPtr pszCalledParty;public IntPtr pszComment;

Dichiarazione di api per effettuare la telefonata

 

[

 

 

DllImport("phone.dll")]private static extern IntPtr PhoneMakeCall(ref PhoneMakeCallInfo ppmci);

Funzione che effettua la chiamata

 

unsafe

{

 

 

 

 

private void Telefona(string numero)bool avvisa = true;IntPtr res;//numero += ”; 

 

{

 

info.cbSize = (

info.pszDestAddress = (

 

{

info.dwFlags = (

}

 

 

char[] cPhoneNumber = numero.ToCharArray();fixed (char* pAddr = cPhoneNumber)PhoneMakeCallInfo info = new PhoneMakeCallInfo();IntPtr)Marshal.SizeOf(info);IntPtr)pAddr;if (avvisa)IntPtr)PMCF_PROMPTBEFORECALLING;else{

info.dwFlags = (

}

res = PhoneMakeCall(

}

}

 

IntPtr)PMCF_DEFAULT;ref info);

Eseguire la funzione per effettuare la chiamata

 

 

{

Telefona(

}

 

private void btnChiama_Click(object sender, EventArgs e)“4250010001″);

 

Rilevare il numero di telefono, individuare gli sms che si possono ricevere ed il numeri di quelli ricevuti.

Dichiarazione a livello di classe

 

//Identificazione numero

 

 

 

public enum AddressType{

 

 

Unknown,

 

 

International,

 

 

National,

 

 

NetworkSpecific,

 

 

Subscriber,

 

 

Alphanumeric,

 

 

Abbreviated

}

 

 

//informazioni numero 

 

public struct PhoneAddress{

 

 

/// <summary>The address type.</summary> 

 

 

public AddressType AddressType;/// <summary>The phone number in string format.</summary> 

}

 

[

 

 

public String Address;private static long SERVICE_PROVIDER = 0x00006F46;StructLayout(LayoutKind.Sequential)]private struct SimRecord{

 

 

 

 

 

}

 

public IntPtr cbSize;public IntPtr dwParams;public IntPtr dwRecordType;public IntPtr dwItemCount;public IntPtr dwSize;Dichiarazione api

 

[

 

[DllImport("cellcore.dll")]

public static extern int SimInitialize(uint dwFlags, int lpfnCallBack, uint dwParam, ref int lphSim);

//private static extern IntPtr SimInitialize(IntPtr dwFlags, IntPtr lpfnCallBack, IntPtr dwParam, out IntPtr lphSim);[DllImport("cellcore.dll")]

private static extern IntPtr SimGetRecordInfo(IntPtr hSim, IntPtr dwAddress, ref SimRecord lpSimRecordInfo);

[DllImport("cellcore.dll")]

private static extern IntPtr SimReadRecord(IntPtr hSim, IntPtr dwAddress, IntPtr dwRecordType, IntPtr dwIndex, byte[] lpData, IntPtr dwBufferSize, ref IntPtr lpdwBytesRead);

[DllImport("cellcore.dll")]

private static extern IntPtr SimDeinitialize(IntPtr hSim);

[DllImport("cellcore.dll")]

public static extern int SimGetSmsStorageStatus(int hSim, uint dwStorage, ref uint lpdwUsed, ref uint lpdwTotal);

 

 

DllImport(“sms.dll”)]private static extern IntPtr SmsGetPhoneNumber(IntPtr psmsaAddress);Funzione che rileva il numero del telefono e tipo

 

unsafe private PhoneAddress GetPhoneNumber()

{

PhoneAddress phoneaddr = new PhoneAddress();

Byte[] buffer = new Byte[516];

fixed (byte* pAddr = buffer)

{

IntPtr res = SmsGetPhoneNumber((IntPtr)pAddr);

if (res != IntPtr.Zero)

throw new Exception(“Could not get phone number from SIM”);

byte* pCurrent = pAddr;

phoneaddr.AddressType = (AddressType)Marshal.ReadInt32((IntPtr)pCurrent);

pCurrent += Marshal.SizeOf(phoneaddr.AddressType);

phoneaddr.Address = Marshal.PtrToStringUni((IntPtr)pCurrent);

}

return phoneaddr;

}

 

Richiamare la funzione da un evento click del pulsante (numero telefono e tipo)

 

private void btnnumero_Click(object sender, EventArgs e)

{

string informazioni = “Numero: “ + GetPhoneNumber().Address + ” Tipo: “ + GetPhoneNumber().AddressType;

MessageBox.Show(informazioni);

}

 

Richiamare la funzione da un evento click di un pulsante per la gestione degli sms (totali e ricevuti)

 

private

{

 

 

 

 

SimInitialize(0, 0, 0,

SimGetSmsStorageStatus(hSim, SIM_SMSSTORAGE_SIM,

 

 

}

 

void btnSms_Click(object sender, EventArgs e)int hSim = 0;uint smsUsed = 0;uint smsTotal = 0;uint SIM_SMSSTORAGE_SIM = 0×2;ref hSim);ref smsUsed, ref smsTotal);MessageBox.Show(“Sms Usati: “ + smsUsed.ToString());MessageBox.Show(“Sms Totali: “ + smsTotal.ToString());Tramite la parola download è possibile scaricare il file di esempio

Download

       

CF avviare un processo

In questo esempio di codice, vedremo come utilizzare le api di Windows Mobile, per avviare un programma eseguibile.
In alternativa al metodo start della classe process (il cf 1.1 non ne dispone) per avviare i vari processi, si può ricorrere alla dichiarazione di api (CreateProcess) per avviare un determinato programma.
Di seguito si riporta un esempio di codice.

Dichiarazione di Api e struttura

 

VB.Net

Declare Function CreateProcess Lib “coredll.dll” (ByVal imageName As String, ByVal cmdLine As String, ByVal lpProcessAttributes As IntPtr, ByVal lpThreadAttributes As IntPtr, ByVal boolInheritHandles As Int32, ByVal dwCreationFlags As Int32, ByVal lpEnvironment As IntPtr, ByVal lpszCurrentDir As IntPtr, ByVal si As Byte(), ByVal pi As ProcessInfo) As Integer

Public Class ProcessInfo

Public hProcess As IntPtr

Public hThread As IntPtr

Public ProcessId As Int32

Public ThreadId As Int32

End Class

C#

[DllImport("coredll.dll", SetLastError = true)]

static extern bool CreateProcess(String imageName,

String cmdLine,

IntPtr lpProcessAttributes,

IntPtr lpThreadAttributes,

bool boolInheritHandles,

Int32 dwCreationFlags,

IntPtr lpEnvironment,

IntPtr lpszCurrentDir,

byte[] si,

ProcessInfo pi);

public class ProcessInfo

{

public IntPtr hProcess;

public IntPtr hThread;

public Int32 ProcessId;

public Int32 ThreadId;

}

Codice da inserire in un evento click di un pulsante

VB.Net

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

 

Dim pi As New ProcessInfo

Dim si(128) As Byte

Dim resultato As Int32

 

resultato = CreateProcess(“calc.exe”, “”, IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, si, pi)

 

 

 

End Sub

C#

private void button1_Click(object sender, EventArgs e)

{

ProcessInfo pi = new ProcessInfo();

byte[] si = new byte[128];

bool resultato = CreateProcess(“calc.exe”, ” “, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, IntPtr.Zero, si, pi);

 

}

Tramite la parola download è possibile scaricare il file di esempio.

Download esempio

Iscriviti

Get every new post delivered to your Inbox.