SUPPORT / SAMPLES & SAS NOTES
 

Support

Sample 26145: Visual Studio 2005 Visual Basic Code Snippets

DetailsDownloadsAboutRate It

IntelliSense Code Snippets provide a way for you to insert ready-made snippets of code into your projects. Microsoft is positioning snippets as a way to speed development by enabling repetitive code to be consolidated into a minimal number of keystrokes or mouse clicks. It's also a way of distributing code that demonstrates best practices, design patterns, and solutions to common tasks that can easily add to Visual Studio 2005.

SAS is providing these code snippets for the SAS® Integration Technologies Windows Client to help developers get started using the client side API's included with the IT Client.

This sample will be periodically updated with new snippets. If you have ideas for snippets, feel free to leave feedback and we'll look into adding them.

Snippets



ADONet.VB.snippet

Title: Get Data Using ADO.NET
Author: SAS Institute Inc.
Description: Uses an OleDbDataAdapter to retrieve data from SAS using the IOM Data Provider.
Code Snippet:
'Create a SAS Workspace and initialize it. 
'Insert a snippet to create a workspace.
            
'Add the SAS object to the ObjectKeeper.  If the object is not
'in the ObjectKeeper, it cannot be used by the IOM Data Provider.
Dim obObjectKeeper As New SASObjectManager.ObjectKeeper
obObjectKeeper.AddObject(1, "MyServer", obSAS)

'Get the requested data using ADO.NET
Dim selectCommandText As String = "$QueryString$"
Dim obAdapter As New System.Data.OleDb.OleDbDataAdapter(selectCommandText, _
    "provider=sas.iomprovider.1; SAS Workspace ID=" & obSAS.UniqueIdentifier)

'Copy data from the adapter into the data set
Dim obDS As New DataSet()
obAdapter.Fill(obDS, "sasdata")

obObjectKeeper.RemoveObject(obSAS)

ADODB.VB.snippet

Title: Get Data Using ADODB
Author: SAS Institute Inc.
Description: Gets data using the IOM Data Provider and ADODB through COM interop.
Code Snippet:
'Create a SAS Workspace and initialize it. 
'Insert a snippet to create a workspace.
            
'Add the SAS object to the ObjectKeeper.  If the object is not
'in the ObjectKeeper, it cannot be used by the IOM Data Provider.
Dim obObjectKeeper As New SASObjectManager.ObjectKeeper
obObjectKeeper.AddObject(1, "MyServer", obSAS)

'Get the formatted data using ADODB.
Dim adoConnection As ADODB.Connection = New ADODB.Connection()
Dim adoRecordset As ADODB.Recordset = New ADODB.Recordset
Dim adoCommand As ADODB.Command = New ADODB.Command

adoConnection.Open("provider=SAS.IOMProvider.1; SAS Workspace ID=" & _
     obSAS.UniqueIdentifier, "", "", 0)

adoCommand.ActiveConnection = adoConnection
adoCommand.CommandText = "$QueryString$"
adoCommand.CommandType = ADODB.CommandTypeEnum.adCmdUnknown
adoCommand.Properties("SAS Formats").Value = "_ALL_"
adoRecordset.Open(adoCommand, System.Reflection.Missing.Value, _
ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockReadOnly, 1)

'Fill an ADO.NET DataSet using the ADODB Recordset
Dim obAdapter As New System.Data.OleDb.OleDbDataAdapter
Dim sasdata As New System.Data.DataSet
obAdapter.Fill(sasdata, adoRecordset, "sasdata")

obObjectKeeper.RemoveObject(obSAS)

CreateOMRConfFile.VB.snippet

Title: Create Metadata Config File
Author: SAS Institute Inc.
Description: Inserts code to call WriteConfigFile, which creates a metadata config file.
Code Snippet:
Dim obObjectFactory As New SASObjectManager.ObjectFactory
Dim serverdef As New SASObjectManager.ServerDef
Dim logindef As New SASObjectManager.LoginDef

' ************************************************
' TODO:  Configure where files will be saved by setting the 
' following boolean statements.
' ************************************************
Dim bSaveLoginForAllUsers As Boolean = True
Dim bSaveServerForAllUsers As Boolean = True

Dim strAllUsersFilePath As String = Environment.GetFolderPath( _
    Environment.SpecialFolder.CommonApplicationData) & _
    "\SAS\MetadataServer\oms_serverinfo.xml"
Dim strCurrentUserFilePath As String = Environment.GetFolderPath( _
    Environment.SpecialFolder.ApplicationData) & _
    "\SAS\MetadataServer\oms_serverinfo.xml"
Dim strCurrentUserLoginFilePath As String = Environment.GetFolderPath( _
    Environment.SpecialFolder.ApplicationData) & _
    "\SAS\MetadataServer\oms_userinfo.xml"

' ************************************************
' Configure the SAS® Metadata Server information.
' TODO:  Modify these values for your SAS Metadata Server.
' ************************************************
serverdef.BridgeEncryptionAlgorithm = "SASProprietary"
serverdef.BridgeEncryptionLevel = SASObjectManager.EncryptionLevels.EncryptUserAndPassword
serverdef.ClassIdentifier = "2887E7D7-4780-11D4-879F-00C04F38F0DB"
serverdef.Name = "SAS Metadata Server"
serverdef.Port = $ServerDef.Port$
serverdef.MachineDNSName = $ServerDef.MachineDNSName$
serverdef.Protocol = SASObjectManager.Protocols.ProtocolBridge
serverdef.DomainName = $ServerDef.Domain$
Dim strRepository As String = $Repository$

' ************************************************
' Configure the SAS Metadata Server login information.
' TODO:  Modify these values for your SAS Metadata Server.
' ************************************************
logindef.DomainName = serverDef.DomainName
logindef.LoginName = $LoginDef.LoginName$
logindef.Name = loginDef.LoginName
logindef.Password = $LoginDef.Password$

If (bSaveServerForAllUsers AndAlso bSaveLoginForAllUsers) Then

    ' ************************************************
    ' Save server and login information for all users.
    ' ************************************************
    obObjectFactory.WriteConfigFile( _
        strAllUsersFilePath, _
        serverdef, _
        logindef, _
        SASObjectManager.RepositoryTypes.RepositoryOMR, _
        strRepository)

ElseIf (bSaveServerForAllUsers) Then

    ' ************************************************
    ' Save server information for all users and login 
    '  information for the current user.
    ' ************************************************
    obObjectFactory.WriteConfigFile( _
       strAllUsersFilePath, _
       serverdef, _
       Nothing, _
       SASObjectManager.RepositoryTypes.RepositoryOMR, _
       strRepository)

    obObjectFactory.WriteConfigFile( _
       strCurrentUserLoginFilePath, _
       Nothing, _
       logindef, _
       SASObjectManager.RepositoryTypes.RepositoryNone, _
       Nothing)

Else

    ' ************************************************
    ' Save server and login information for current users.
    ' ************************************************
    obObjectFactory.WriteConfigFile( _
        strCurrentUserFilePath, _
        serverdef, _
        logindef, _
        SASObjectManager.RepositoryTypes.RepositoryOMR, _
        strRepository)

    ' It's a good idea to clean up conflicting login 
    ' information to ensure that your configuration is using 
    ' the correct username and password.
    Dim fiCurrentUserLoginFile As System.IO.FileInfo = New _
        System.IO.FileInfo(strCurrentUserLoginFilePath)

    If (fiCurrentUserLoginFile.Exists) Then _
        fiCurrentUserLoginFile.Delete()
End If

COM_DCOMConnection.VB.snippet

Title: Create COM or DCOM Connection
Author: SAS Institute Inc.
Description: Creates a COM or DCOM connection to a SAS Workspace Server.
Code Snippet:
Dim obObjectFactory As New SASObjectManager.ObjectFactory
Dim obServerDef as New SASObjectManager.ServerDef
Dim obSAS As SAS.Workspace

'************************************************
' Configure the server information.  
' TODO:  Modify these options as appropriate.
' ************************************************
obServerDef.Protocol = SASObjectManager.Protocols.ProtocolCom
obServerDef.MachineDNSName = $MachineDNSName$

' ************************************************
' Create the connection.
' ************************************************
obSAS = obObjectFactory.CreateObjectByServer("MyServer", True, obServerDef, "", "")

IOMBridgeConnection.VB.snippet

Title: Create IOM Bridge Connection
Author: SAS Institute Inc.
Description: Creates an IOM Bridge connection to a SAS Workspace Server.
Code Snippet:
Dim obObjectFactory As New SASObjectManager.ObjectFactory
Dim obServerDef as New SASObjectManager.ServerDef
Dim obSAS As SAS.Workspace

'************************************************
' Configure the server information.  
' TODO:  Modify these options as appropriate.
' ************************************************
obServerDef.MachineDNSName = $MachineDNSName$
obServerDef.BridgeEncryptionAlgorithm = "SASProprietary"
obServerDef.BridgeEncryptionLevel = SASObjectManager.EncryptionLevels.EncryptUserAndPassword
obServerDef.Port = $Port$
obServerDef.Protocol = SASObjectManager.Protocols.ProtocolBridge  

' ************************************************
' Create the connection.
' ************************************************
obSAS = obObjectFactory.CreateObjectByServer("MyServer", True, obServerDef, $UserName$, $Password$)

ConnectionByLogicalName.VB.snippet

Title: Create Connection by Logical Name
Author: SAS Institute Inc.
Description: Creates a connection to a SAS IOM Server, such as the SAS Metadata Server, that is defined in metadata .
Code Snippet:
Dim obObjectFactory As New SASObjectManager.ObjectFactory
Dim obSAS As SAS.Workspace

' ************************************************
' Create the connection.
' This assumes that your metadata configuration files are in the default
' location or that the location of your configuration files is stored
' in the registry. If this is not the case, then you should call...
' obObjectFactory.SetMetadataFile systemFile, userFile, false
' ************************************************
obSAS = Nothing
Set obSAS = obObjectFactory.CreateObjectByLogicalName("MyServer", True, $LogicalName$, "")

CreatePool.VB.snippet

Title: Create A Connection Pool
Author: SAS Institute Inc.
Description: Creates a connection pool of workspaces for use in an application that needs to make frequent use of a workspaces with minimal wait time.
Code Snippet:
Dim obObjectFactory As New SASObjectManager.ObjectFactory
Dim obServerDef as New SASObjectManager.ServerDef
Dim obLoginDef as New SASObjectManager.LoginDef
Dim objectPool As SASObjectManager.ObjectPool = Nothing

Dim strPoolName As String = "$PoolName$"

Try
'Check to be sure that the pool is not already running.
objectPool = obObjectFactory.ObjectPools.Item(strPoolName)

If Not objectPool Is Nothing Then
   Return
End If

Catch ex As Exception
   Trace.Write( _
   "Pool not created yet, creating pool." & _
   "Exception message:  " & _
    ex.Message)
End Try

Try

' ************************************************
' Configure the server information.  
' TODO:  Modify these options as appropriate.
' ************************************************
obServerDef.MachineDNSName = $MachineDNSName$
obServerDef.Protocol = SASObjectManager.Protocols.ProtocolBridge
obServerDef.Port = $Port$
obServerDef.BridgeEncryptionAlgorithm = "SASProprietary"
obServerDef.BridgeEncryptionLevel = SASObjectManager.EncryptionLevels.EncryptUserAndPassword
obServerDef.ShutdownAfter = 30
obServerDef.RunForever = False
obServerDef.RecycleActivationLimit = 30
obServerDef.MaxPerObjectPool = 5

' ************************************************
' Configure the login information and pooling parameters.
' TODO:  Modify these options as appropriate.
' ************************************************
obLoginDef.LoginName = $UserName$
obLoginDef.Password = $Password$
obLoginDef.MinSize = 2
obLoginDef.MinAvail = 0

' ************************************************
' Create the ObjectPool.
' ************************************************
objectPool = obObjectFactory.ObjectPools.CreatePoolByServer(strPoolName, obServerDef, obLoginDef)

Catch ex As Exception
    Trace.Write("Exception while creating object pool:  " & ex.Message)
    Throw
End Try

' *********************************************
' The following code demonstrates how to create
' a pooled object and return the object back to 
' the pool when the application is done with it.
.

' Dim obpooledworkspace As New SASObjectManager.PooledObject
' obpooledworkspace = objectPool.GetPooledObject("", "", 10000)
' Dim obSAS As SAS.Workspace
' obSAS = obpooledworkspace.SASObject

' debug.print "Pooled Workspace Running On:  " & obSAS.Utilities.HostSystem.DNSName  

' Return the object to the pool.
' obSAS = Nothing
' obPooledWorkspace.ReturnToPool()
' obpooledworkspace = Nothing
' *********************************************

SASLSEvents.VB.snippet

Title: Add SAS Language Events Listener Methods
Author: SAS Institute Inc.
Description: Adds a method to initialize the SASLanguageEvents and all of the required method signatures for the event delegates.
Code Snippet:
'Enable Events on the LanguageService object.
Public WithEvents obLS As SAS.LanguageService

'**********************************************
'Define LanguageService Event Handler Routines.
'**********************************************
Private Sub obLS_DatastepStart() Handles obLS.DatastepStart
    'Debug.Write("DatastepStart" & vbCrLf)
End Sub

Private Sub obLS_DatastepComplete() Handles obLS.DatastepComplete
    'Debug.Write("DatastepComplete" & vbCrLf)
End Sub

Private Sub obLS_ProcStart(ByVal Procname As String) Handles obLS.ProcStart
    'Debug.Write("Proc Start:  " + Procname & vbCrLf)
End Sub

Private Sub obLS_ProcComplete(ByVal Procname As String) Handles obLS.ProcComplete
    'Debug.Write("Proc Complete:  " + Procname & vbCrLf)
End Sub

Private Sub obLS_SubmitComplete(ByVal Sasrc As Integer) Handles obLS.SubmitComplete
    'Debug.Write("Submit Complete:  " + Sasrc & vbCrLf)
End Sub

Private Sub obLS_StepError() Handles obLS.StepError
    'Debug.Write("Error in SAS" & vbCrLf)
End Sub

SASFileService.VB.snippet

Title: Download a Temporary File Using FileService
Author: SAS Institute Inc.
Description: Creates a temporary fileref and uses it to download output generated by SAS back to the client as a byte array. This action requires a connection to already be established.
Code Snippet:
' ************************************************
' Define instances of interfaces used.
' ************************************************
Dim obFS As SAS.FileService
Dim obFref As SAS.Fileref
Dim outstring As String
Dim obLS As SAS.LanguageService

' ************************************************
' Create a temporary fileref to store dynamically 
' generated output. 
' ************************************************
obFS = $sasWorkspace$.FileService
outstring = ""
obFref = obFS.AssignFileref("out", "TEMP", "", "", outstring)

' ************************************************
' TODO:  Replace with your own logic to generate
' output in SAS that needs to be downloaded.
' ************************************************
obLS = $sasWorkspace$.LanguageService
Dim sascode As String

' Example:
' sascode = "goptions reset=all gsfname=out gsfmode=replace dev=pdf; proc gchart data=sashelp.class;vbar age / discrete;run;quit;"

' ************************************************
' Submit the sample code to generate output.
' ************************************************
obLS.Submit(sascode)

' ************************************************
' Stream back the output file from SAS.
' ************************************************
Dim obStreamHelper As New SCRIPTOLib.StreamHelper
Dim obBinaryStream As SAS.BinaryStream
Dim PDFGraph As Byte()
obBinaryStream = obFref.OpenBinaryStream(SAS.StreamOpenMode.StreamOpenModeForReading)
obStreamHelper = CreateObject("SASScripto.StreamHelper")
PDFGraph = obStreamHelper.ReadBinaryArray(obBinaryStream, 0)
obBinaryStream.Close()

' ************************************************
' Here is an example of writing the byte array to
' a file you could add to your code. 
' ************************************************
'Dim fs As New System.IO.FileStream("c:\sample.pdf", IO.FileMode.Create, IO.FileAccess.Write)
'fs.Write(PDFGraph, 0, PDFGraph.Length)




These sample files and code examples are provided by SAS Institute Inc. "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. Recipients acknowledge and agree that SAS Institute shall not be liable for any damages whatsoever arising out of their use of this material. In addition, SAS Institute will provide no support for the materials contained herein.