CSharp - Conexion Dial-up en C#

Written by lopezatienza on 12 Noviembre 2008 – 11:30 -

Primeramente crearemos una clase llamada RAS con el siguiente código:

using System;

using System.Runtime.InteropServices;

 ///

/// Descripción breve de RAS.

///

// Clase comunicaciones REMOTAS

 public class RAS

{

    [DllImport("coredll.dll", CharSet = CharSet.Unicode)]

    private static extern int RasDial(int dialExtensions, int phoneBookPath, IntPtr rasDialParam, int NotifierType, int notifier, ref int hRasConn);

 

    [DllImport("coredll.dll", CharSet = CharSet.Unicode)]

    private static extern int RasHangUp(int hRasConn);

 

    [DllImport("coredll.dll", CharSet = CharSet.Unicode)]

    private static extern int RasGetConnectStatus(int hRasConn, ref object lpRasConnStatus);

 

    [DllImport("coredll.dll", CharSet = CharSet.Unicode)]

    private static extern IntPtr LocalAlloc(int uFlags, int uBytes);

 

    [DllImport("coredll.dll", CharSet = CharSet.Unicode)]

    private static extern IntPtr LocalFree(IntPtr hMem);

 

    [DllImport("coredll.dll", CharSet = CharSet.Unicode)]

    private static extern IntPtr LocalReAlloc(int hMem, int uBytes, int fuFlags);

 

    private const int LMEM_FIXED = 0;

    private const int LMEM_MOVEABLE = 2;

    private const int LMEM_ZEROINIT = 64;

    private const int LPTR = LMEM_ZEROINIT;

 

 

    private struct rasDialParams

    {

        public int dwSize;

    }

 

    public struct VBRasDialParams

    {

        public string EntryName;

        public string PhoneNumber;

        public string CallbackNumber;

        public string UserName;

        public string Password;

        public string Domain;

        public long SubEntryIndex;

        public long RasDialFunc2CallbackId;

    }

 

    public static IntPtr AllocHLocal(int cb)

    {

        return LocalAlloc(LPTR, cb);

    }

 

    public static void FreeHLocal(IntPtr hlocal)

    {

        if (!hlocal.Equals(IntPtr.Zero))

        {

            if (!IntPtr.Zero.Equals(LocalFree(hlocal)))

            {

                throw new Exception("win error");

            }

            hlocal = IntPtr.Zero;

        }

    }

 

    public static IntPtr ReAllocHLocal(int pv, int cb)

    {

        IntPtr newMem = LocalReAlloc(pv, cb, LMEM_MOVEABLE);

        if (newMem.Equals(IntPtr.Zero))

        {

            throw new Exception("out of memory");

        }

        return newMem;

    }

 

    public static IntPtr StringtoHLocalUni(string s)

{

if(s==null)

{

return IntPtr.Zero;

}

else

{

int nc=s.Length;

int len=2*(1+nc);

IntPtr hLocal = AllocHLocal(len);

 

if(hLocal.Equals(IntPtr.Zero))

{

throw new Exception("out of memory");

}

else

{

System.Runtime.InteropServices.Marshal.Copy(s.ToCh arArray(),0,hLocal,s.Length);

return hLocal;

}

}

}

 

    public static bool Marcar(string szRasConnection, string szUserName, string szPassword, ref int hRasConnection)

{

rasDialParams p = new rasDialParams();

int dwSize;

IntPtr strPointer;

 

char[] bRasConnection = new char[szRasConnection.Length];

IntPtr offset;

int hrasconn=0;

 

char[] bUsername = new char[szUserName.Length];

char[] bPassword = new char[szPassword.Length];

int ret;

 

dwSize = Marshal.SizeOf(p);

dwSize += Marshal.SystemDefaultCharSize * 21;

dwSize+= Marshal.SystemDefaultCharSize*129;

dwSize+=Marshal.SystemDefaultCharSize*49;

dwSize+=Marshal.SystemDefaultCharSize*257;

dwSize+=Marshal.SystemDefaultCharSize*257;

dwSize+=Marshal.SystemDefaultCharSize*16;

bRasConnection = szRasConnection.ToCharArray();

bUsername = szUserName.ToCharArray();

bPassword = szPassword.ToCharArray();

strPointer = AllocHLocal(dwSize);

offset = new IntPtr(strPointer.ToInt32() + Marshal.SizeOf(p));

Marshal.Copy(bRasConnection,0,offset,szRasConnecti on.Length);

offset = new IntPtr(offset.ToInt32()+Marshal.SystemDefaultCharS ize*21);

Marshal.Copy("".ToCharArray(),0,offset,"".Length);

offset = new IntPtr(offset.ToInt32()+Marshal.SystemDefaultCharS ize*129);

Marshal.Copy("".ToCharArray(),0,offset,"".Length);

offset = new IntPtr(offset.ToInt32()+Marshal.SystemDefaultCharS ize*49);

Marshal.Copy(bUsername,0,offset,szUserName.Length) ;

offset = new IntPtr(offset.ToInt32()+Marshal.SystemDefaultCharS ize*257);

Marshal.Copy(bPassword,0,offset,szPassword.Length) ;

offset = new IntPtr(offset.ToInt32()+Marshal.SystemDefaultCharS ize*257);

Marshal.Copy("".ToCharArray(),0,offset,"".Length);

 

try

{

ret = RasDial(0,0,strPointer,0,0,ref hrasconn);

 

if(ret==0)

{

hRasConnection = hrasconn;

return true;

}

else

{

return false;

}

 

}

catch(Exception)

{

return false;

}

}

 

    public static int GetConnectStatus(int hrasconn, ref object lprasconnstatus)

    {

        return RasGetConnectStatus(hrasconn, ref lprasconnstatus);

    }

 

    public static bool Colgar(int hrasconn)

    {

        int ret;

        try

        {

            ret = RasHangUp(hrasconn);

            if (ret == 0)

            {

                return true;

            }

            else

            {

                return false;

            }

        }

        catch (Exception)

        {

            return false;

        }

    }

 

}

 

 

Para marcar la conexión hay que crear una conexión GPRS:

En Windows Mobile 5.0 es:

Start \ Settings \ Connections \ Connections

Add a new modem connection

Se introduce el nombre de la conexion, y en select a modem:


Cellular Line (GPRS)

EN access point name se pone movistar.es (si es que la tarjeta SIM que tienes es movistar, con las otras compañias habría que informarse)

le das a Next:

User name: movistar
Password: movistarmovistar
Domain: en blanco

Y se pulsa en Finish.

Ya tenemos la conexión GPRS creada.

Para probar si va se pulsa en la [G] que sale arriba, pulsar en Settings, Connections, Manage existing connections, pulsamos encima de la conexión creada durante 3 segundos, y pulsamos en Connect.

Si todo va bien al pulsar nuevamente en [G] deberia salir el nombre de la conexion creada y Connnected a la derecha.

Bien, aora pulsamos en Disconnect.

Vamos a la aplicacion, y una vez que tengas la clase RAS, al intentar llamar a RAS.Marcar() introduciremos algo asi como:

bool Resultado = RAS.Marcar("GPRS", "MOVISTAR", "MOVISTAR", ref EstadoConexionRAS);

if (Resultado)
{
//Aqui entraria si la conexión RAS ha sido satisfactoria
}

 

 

 

Ten en cuenta que cuando llamo a:

bool Resultado = RAS.Marcar("GPRS", "MOVISTAR", "MOVISTAR", ref EstadoConexionRAS);

"GPRS" --> es el nombre que le he dado yo a mi conexión GPRS.

 

 

 

Se debe crear en la aplicación una variable:

private int EstadoConexionRAS = 0;

que sera con la que se juega al hacer la llamada.

Descargar clases:

  • Clase RAS.cs (Descargar): Clase para hacer conexiones Dial-up en PPC.
  • Clase FlightMode.cs (Descargar): Clase con funcionalidades de dispositivos móviles.

Tags: , ,
Posted in CSharp, WindowsCE |

2 Comments to “CSharp - Conexion Dial-up en C#”

  1. XFulgor Says:

    Primero que nada gracias por compartir tu codigo

    ahora he tratado de implementarlo sobre un dispositivo con windowCE pero no funciona, no retorna ni un error ni nada , sabes si en compatible con win CE ?? gracias

  2. lopezatienza Says:

    Buenas XFulgor.

    Cuando llamas a la función Marcar de la clase RAS te devuelve true la variable Resultado?

    Un saludo.

Leave a Comment

RSS