How to create a Network Connection class that access Remote server?

Hi everybody,
   I am having trouble finding documents or topics in internet that shows how to create a Network Connection class that access Remote server. I have created a class library that does database access and process to a remote database but it requires internet and a remote network connection which is created using Windows OS. I like to create this into a class that can be called whenever a connection to a remote server is required and the calling will be done inside the program.
   How exactly I would start this I need help. Thanks.

den2005


Answer this question

How to create a Network Connection class that access Remote server?

  • Marty McGee

    Hi Durgaprasad Gorti, 
       Tahnsks for reply. What I like to do is create a VPN connection programatically in order my class library which contains my database access, connection, and process will be able to interact with the remote server. Here is some codes I found and modified it, to have fixed ip address, username and password. It does not work. Can you or anyone help me Advanced 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]


    den2005


  • Julian Kooiker

    It will be very difficult indeed if you don't know about RAS/VPN and other stuff
    You need to definitely educate yourself by reading MSDN RAS API documentation
    Thanks and good luck.

  • hajik

    Well to start with the remote server should have the thr routing and remote access service installed. It should be configured properly to accept the remote connections. Are you sure you have a properly configured remote access server

  • Breno

    Is that a question or a statement

  • BikerRon

    You can find basic socket client examples here:
    http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpguide/html/cpconsocketcodeexamples.asp

    This should get you headed in the right direction.



  • Golfnut 1969

    Thanks Durgaprasad Gorti, I am a newbie in this ras, vpn or other remote connection, so do not know what is the wrong or where I like to connect to this remote server programatically, and not configured outside of the application that is what I like to do.

    den2005

  • Dan Stojadinovic

    Thansk for reply, Mike. I like to simualte a VPN connection.

    denpsia


  • How to create a Network Connection class that access Remote server?