Building a Network Service Object

Building a Network Service Object

bjects you build don’t always have to be related to a database entity. In fact, some of the best objects are pure service objects that know how to talk to the registry, or other Windows service. This article will show you the code to build a network service object that knows how to:

1. Get network user name.
2. Connect a network drive.
3. Disconnect a network drive.

Each one of these features will be a public subroutine or function. The object will take care of error handling from the API calls by raising errors to the calling routine. While the sample code will have a basic error handler, you can expand it to check each of the error codes that the API calls might return. These error codes are documented in the MSDN library (both online and on CD-ROM), and the error code constants are defined in the API viewer. Just add them to your application and you’ll be ready to go.

The first routine will be called AddConnection. The code for this routine is shown here:

Public Sub AddConnection(strLocalPath As String,         _strNetworkPath As String, _   Optional strUserName As String = "",         _Optional strPassword As String = "")      Dim typNet As NETRESOURCE   Dim lngReturn As Long   With typNet      .dwType = RESOURCETYPE_DISK      .lpLocalName = strLocalPath      .lpRemoteName = strNetworkPath      .lpProvider = ""   End With   lngReturn = WNetAddConnection2(typNet,         _strPassword, strUserName, 0)   If lngReturn <> 0 Then      Err.Raise vbObjectError, 	       _"NetworkServices.AddConnection", 		        _"Error #" & lngReturn & " occurred		      _during connection."   End If   End Sub

The routine is designed to accept a local path and a network path, and optionally, a user name and/or password to make the connection. As is required by the API call, we fill the NETRESOURCE structure with the information needed to make the connection. The constant used here is defined in the API Viewer. The error handler here is pretty basic, but could be expanded to provide text descriptions of all the errors that can occur from this API call. For now, we just raise the error and return.

The zero in the API call is a flag indicating whether the network connection should be remembered and reconnected during the next reboot. If you have a need to make a permanent connection, you can add another parameter to the method call to allow the caller to choose to save or not. The constant used here to save the connection is CONNECT_UPDATE_PROFILE.

The counterpart to this routine is DropConnection, which is somewhat simpler.

Public Sub DropConnection(strLocalPath As String,         _Optional blnForce As Boolean = False)   Dim lngReturn As Long   lngReturn = WNetCancelConnection2        _(strLocalPath, 0, blnForce)   If lngReturn <> 0 Then      Err.Raise vbObjectError, 	       _"NetworkServices.DropConnection", _         "Error #" & lngReturn & " occurred during 		      _connection drop."   End IfEnd Sub

The blnForce parameter indicates whether Windows should force the connection closed if files are open. Be careful setting this parameter to True as it can cause most applications to go haywire if the file suddenly becomes unavailable. Other than that, the function is basically the same structure as before.

The third method allows you to retrieve the current network user name for the system, as well as any network resource.

Public Function UserName(Optional strLocalPath As String = "")   Dim strBuffer As String * 255   Dim lngReturn As Long   lngReturn = WNetGetUser(strLocalPath, strBuffer, 255)   UserName = Trim(strBuffer)   If lngReturn <> 0 Then      Err.Raise vbObjectError, "NetworkServices.UserName", _         "Error #" & lngReturn & " occurred during request."   End If   

End Function

By setting the local path parameter, you can request the user name used to connect a given resource. If this is empty (the default), the current network user name is returned.

Calling any of the methods is done like so:

Dim objNet As NetworkServicesSet objNet = New NetworkServicesobjNet.AddConnection "F:", "\ServerC$"MsgBox objNet.UserNameobjNet.DropConnection "F:"

You can expand this object with other related functions, such as those used in the Common Dialog control (open file, save file, etc.). All the API calls are declared in the API Viewer and documented in the MSDN library.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as