Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / New Users / January 2006

Tip: Looking for answers? Try searching our database.

Help!! Creating a RAS _VPN Network connection class - Problem

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
den 2005 - 01 Dec 2005 08:12 GMT
Hi everybody,
  I found this code but unable to make it work. I like to create a Remote
access service using VPN Network connection in order I could interact with
remote database. I like to created a fixed link to a remote server with
default username and password.  With this code, still unable to connect to
remote server as verified if internet connection is ok. Is there anyone who
can help me fixed thia problem? I need help. Thanks.

This inside main class
[code]
public void Dial()
{
   if(_Handle!=IntPtr.Zero)
  {
       RASCONNSTATUS status=new RASCONNSTATUS();
       uint res=RasAPI.RasGetConnectStatus(_Handle,status);
     
       if(res==ERROR_INVALID_HANDLE) //res=ERROR_INVALID_HANDLE
          _Handle=IntPtr.Zero;
       else
           return;
   }
   try
   {
          this._Params.szPhoneNumber = "<server ip>";
          this._Params.szUserName = "<username>";
          this._Params.szPassword = "dennispt200508";
         
RasAPI.RasCheck(RasAPI.RasDial(null,_Phonebook,_Params,1,_DialNotifyDelegate,ref _Handle));
         
RasAPI.RasConnectionNotification(_Handle,this._DisconnEvent.Handle,RASNOTIFICATION.RASCN_Disconnection);
               
          RasAPI.RasDial(null,@"C:\Documents and Settings\All
Users\Application
Data\Microsoft\Network\Connections\Pbk\rasphone.pbk",_Params,1,_DialNotifyDelegate,ref _Handle);

           StartWatch();

           if (ConnectionState.IsModemConnected())
               this.statusSend("Connected to 203.201.133.64");
           else
    this.statusSend("Unable to connect.");
    }
    catch(Exception e)
   {
               
   }
}

private void StartWatch()
{
     StopWatch();
    this._WatchThread=new Thread(new ThreadStart(RunWatch));
    this._WatchThread.Start();
}

private void StopWatch()
{
     if(this._WatchThread==null)
    return;
     if(this._WatchThread.IsAlive)
     {
    this._StopEvent.Set();
    this._WatchThread.Join();
      }
     this._WatchThread=null;
}

private void RunWatch()
{
      WaitHandle[] handles=new
WaitHandle[]{this._StopEvent,this._DisconnEvent};
      int ret;
      this._StopEvent.Reset();
      this._DisconnEvent.Reset();
      while(true)
     {
    ret=WaitHandle.WaitAny(handles);
    if(ret==0)
       break;
    if(ret==1)
    {
         this.OnDisconnected();
          System.Diagnostics.Debug.WriteLine("Dis connected");
             break;
    }
      }
}

private void OnConnected()
{
     if(this.Connected==null)
         return;
    EventArgs args=new EventArgs();
    if(this.SynchronizingObject!=null &&
this.SynchronizingObject.InvokeRequired)
   {
         this.SynchronizingObject.Invoke(Connected,new object[]{this,args});
    }
    else
    {
           Connected(this,args);
     }
}

private void OnDisconnected()
{
       if(this.Disconnected==null)
          return;
       EventArgs args=new EventArgs();
       if(this.SynchronizingObject!=null &&
this.SynchronizingObject.InvokeRequired)
       {
    this.SynchronizingObject.Invoke(Disconnected,new object[]{this,args});
        }
         else
         {
    Disconnected(this,args);
         }
}

private void OnDialNotify1(IntPtr hrasconn,uint unMsg,RASCONNSTATE
rascs,uint dwError,uint dwExtendedError)
{
        if(this.DialNotify1==null)
    return;
        string msg="";
        if(dwError>0)
        {
//    msg=RasException.Code2RasErrorMessage(dwError);
         }
         else
         {
//    msg=RasConnection.GetRasConnStateMessage(rascs);
             msg = this.GetRasConnStateMessage(rascs);
         }
        RasDialNotify1EventArgs args=new
RasDialNotify1EventArgs(hrasconn,unMsg,rascs,dwError,dwExtendedError,msg);
       
        if(this.SynchronizingObject!=null &&
this.SynchronizingObject.InvokeRequired)
        {
    this.SynchronizingObject.Invoke(DialNotify1,new object[]{this,args});
        }
        else
        {
    DialNotify1(this,args);
         }
         if(args.ConnectionState==RASCONNSTATE.RASCS_Connected)
    OnConnected();
}

private string GetRasConnStateMessage(RASCONNSTATE state)
{
       string ret="";
       if(_Res!=null)
    ret=(string)_Res.GetObject(state.ToString().Trim());
        return ret;
}

[Browsable(false),Description("get or set SynchronizingObject")]
public ISynchronizeInvoke SynchronizingObject
{
  get
 {
         if(_SynchronizingObject==null)
          {
    if(this.DesignMode)
    {
         IDesignerHost dh=this.GetService(typeof(IDesignerHost)) as
IDesignerHost;
         if(dh!=null)
         {
        _SynchronizingObject=dh.RootComponent as ISynchronizeInvoke;
          }
    }
           }
          return _SynchronizingObject;
    }
    set
    {
           _SynchronizingObject=value;
    }
}
[/code]

Inside another class
[code]
internal sealed class RasAPI
    {
        private RasAPI(){}

        [DllImport("rasapi32.dll",CharSet=CharSet.Auto)]       
        public extern static uint RasDial(
            [In]RASDIALEXTENSIONS lpRasDialExtensions,
            // pointer to function extensions data
            [In]string lpszPhonebook,  // pointer to full path and file
            //  name of phone-book file
            [In]RASDIALPARAMS lpRasDialParams,
            // pointer to calling parameters data
            uint dwNotifierType,   // specifies type of RasDial event handler
            Delegate lpvNotifier,     // specifies a handler for RasDial events
            ref IntPtr lphRasConn   // pointer to variable to receive
            //  connection handle
            );

        [DllImport("rasapi32.dll",CharSet=CharSet.Auto)]
        public extern static uint RasGetConnectStatus(
            IntPtr hrasconn,  // handle to RAS connection of interest
            [In,Out]RASCONNSTATUS lprasconnstatus
            // buffer to receive status data
            );

        [DllImport("rasapi32.dll",CharSet=CharSet.Auto)]
        public extern static uint RasGetErrorString(
            uint uErrorValue,        // error to get string for
            StringBuilder lpszErrorString,  // buffer to hold error string
            [In]int cBufSize           // size, in characters, of buffer
            );

        [DllImport("rasapi32.dll",CharSet=CharSet.Auto)]
        public extern static uint RasConnectionNotification(
            IntPtr hrasconn,  // handle to a RAS connection
            IntPtr hEvent,      // handle to an event object
            RASNOTIFICATION dwFlags       // type of event to receive notifications for
            );

        public static void RasCheck(uint errorCode)
        {
            if(errorCode!=(uint)RasError.SUCCESS)
            {   
                //                throw new RasException(errorCode);
                StringBuilder sb=new StringBuilder(512);
                if(RasAPI.RasGetErrorString(errorCode,sb,sb.Capacity)>0)
                    throw new Exception("Unknow RAS exception.");
                //                string ret=sb.ToString();
            }
        }
    }
[/code]

Inside class checking internet connection

[code]
public class ConnectionState
    {

        private enum ConnectionStateEnum
        {
            //Local system has a valid connection to the Internet, but it might or
might not be currently connected.
            ConnectionConfigured = 64,
            //Local system uses a local area network to connect to the Internet.
            ConnectionLan = 2,
            //Local system uses a modem to connect to the Internet.
            ConnectionModem = 1,
            //No longer used.
            ConnectionModemBusy = 8,
            //Local system is in offline mode.
            ConnectionOffline = 32,
            //Local system uses a proxy server to connect to the Internet.
            ConnectionProxy = 4,
            //Local system has RAS installed.
            RasInstalled = 16

        }

        class Win32
        {
            [DllImport("Wininet.dll", CharSet=CharSet.Auto)]
            public static extern int InternetGetConnectedState(out int Flag, int
Reserved);
        }

        private static int GetConnectionFlag()
        {
            int Flag;
            Win32.InternetGetConnectedState(out Flag,0);
            return Flag;
        }

        public static bool IsModemConnected()
        {
            return ((GetConnectionFlag() &
(int)ConnectionStateEnum.ConnectionModem)==0) ?
            false : true;
        }
    }
[/code]

denpsia

Signature

MCP Year 2005, Philippines

Floyd Burger - 04 Dec 2005 00:55 GMT
I don't see where you're checking the return value of the different RAS
method calls.  The return value will most likely tell you why the connectoid
is failing.

Signature

Floyd

> Hi everybody,
>   I found this code but unable to make it work. I like to create a Remote
[quoted text clipped - 292 lines]
>
> denpsia
Dennis Sia - 09 Jan 2006 02:30 GMT
I am using RasGetConnectSttaus to check for status of ras connection but not
sure how to use this.

Causing a result of 632 even the connection is created.

[code]
private void btnRasConnect_Click(object sender, System.EventArgs e)
{
. ..  ..
    if (this.CheckRasConnection(this.IDConnexionRAS) == false)
        this.OpeningConnection();
.. ....
}

private void OpeningConnection()
{
  this.IDConnexionRAS = 0;
  string connectName = this.txtIpAddress.Text;
  string user = this.txtUsername.Text;
  string pass = this.txtPassword.Text;
               
  this.OpenConnection(connectName,user,pass,"");
}

public bool OpenConnection(string pNomConnection,string pUser,string
pPassword,string pDomain)
{

 int i;
 int j;

 #region [ RASDIALPARAMS ]
// The size of the table of bytes representing structure RASDIALPARAMS is of
1464 bytes
 TabParams = new byte[1464];
 BitConverter.GetBytes(1464).CopyTo(TabParams,0);
 i = 4;
 j = i;
 foreach (char Carac in pNomConnection)
 {
    BitConverter.GetBytes(Carac).CopyTo(TabParams, j);
    j += 2;
 }
 i += (42 + 258 + 98);

 j = i;
 foreach (char Carac in pUser)
 {
    BitConverter.GetBytes(Carac).CopyTo(TabParams, j);
    j += 2;
 }
 i += 514;
 j = i;
 foreach (char Carac in pPassword)
 {
    BitConverter.GetBytes(Carac).CopyTo(TabParams, j);
    j += 2;
 }
 i += 514;

 #endregion

 uint res = RasDial(0,null,TabParams,0,0,ref IDConnexionRAS);
       
 if (res == 0)
 {
    this.connectStatus = true;
    if (this.IDConnexionRAS > 0)
      this.IDDisconnectRAS = this.IDConnexionRAS;
   
    status.rasconnstate = RASCONNSTATE.RASCS_Connected;
       RasAPI.RasConnectionNotification(IDConnexionRAS,this._DisconnEvent.
Handle ,(int)RASNOTIFICATION.RASCN_Connection);
    Console.WriteLine ("RAS TRUE");
    this.lblConStat.Text = "Connected";
               
    return true;
 }
 . .. .
}

public bool GetRasConnectStatus(int idConn)
{
  status = new RASCONNSTATUS();
  status.dwSize = Marshal.SizeOf(typeof(RASCONNSTATUS));
  //uint res = 1;
  res = RasAPI.RasGetConnectStatus(idConn, ref status);
 
  if (res == 0 && status.rasconnstate == RASCONNSTATE.RASCS_Connected)
  {
    this.IsRasConnected = true;
    return true;
  }
  else
  {
    this.IsRasConnected = false;
    return false;
  }
}

[/code]

dennis

>Hi everybody,
>   I found this code but unable to make it work. I like to create a Remote
[quoted text clipped - 287 lines]
>
>denpsia

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.