22
Infor 13560 Morris Road Suite 4100 Alpharetta, Georgia 30004-8508 www.infor.com Converting WinStudio Script Code from VBA to VB.NET Infor ERP SL Version 8.00

from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

  • Upload
    lymien

  • View
    405

  • Download
    15

Embed Size (px)

Citation preview

Page 1: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Infor13560 Morris Road

Suite 4100Alpharetta, Georgia 30004-8508

www.infor.com

Converting WinStudio Script Code from VBA to VB.NET

Infor ERP SL Version 8.00

Page 2: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting WinStudio Script Code from VBA to VB.NET

Published in the USA October 2007

Copyright © 2007, Infor. All rights reserved. The word and design marks set forth herein are trademarks and/or registered trademarks of Infor and/or its affiliates and subsidiaries. All rights reserved. All other

trademarks listed herein are the property of their respective owners.

Restricted Rights Legend Use, duplication, or disclosure by the Government is subject to restrictions

as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013,

and Rights in Data-General at FAR 52.227.14, as applicable. Name of Contractor: Infor,

13560 Morris Road, Suite 4100, Alpharetta, GA 30004-8508.

Document Changes

Changes made to this document since the previous version are dated 10/19/2007.

Date Description

10/19/2007 In VB.NET, garbage collection is performed asynchronously. Page 1-5.

10/19/2007 Method names in VB.NET assemblies are case sensitive. Page 1-5.

10/19/2007 Removed chapter and appendix about APIs for strong data types. Material is in the document Modifying Infor ERP SL.

4/1/2007 New chapter on APIs for strong data type.

4/1/2007 New appendix showing sample scripts that use APIs for strong data type.

4/1/2007 New chapter showing sample code conversions. Page 2-1.

1/9/2007 Convert version 5.0 VBA parameters of the type %1 to version 6.0 parameters. Page 1-4.

1/9/2007 The VBA Long data type and the VB.NET Integer data type. Page 1-6.

1/9/2007 WinStudio variables and the Boolean data type. Page 1-9.1/9/2007 WinStudio variables and VB.NET constants. Page 1-10.1/9/2007 Detect null or empty strings in properties or WinStudio variables. Page 1-

10.1/9/2007 Use the Decimal data type with material quantities and currency amounts. Page 1-

10.

Page 3: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Contents_________________________________________Converting Code from VBA to VB.NET. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1General Considerations................................................................................................................1-1WinStudio API Considerations .....................................................................................................1-2VBA-to-VB.NET Conversion Issues .............................................................................................1-4Using the WinStudio Script Editor to Fix Compiler Errors ............................................................1-8Editing Code with the EditWinStudioScript Visual Studio Project.................................................1-8To Debug a Script Converted to VB.NET .....................................................................................1-8Miscellaneous Guidelines for Coding VB.NET in SyteLine ..........................................................1-9

Boolean Data Type ............................................................................................................... 1-9VB.NET Constants .............................................................................................................. 1-10Null and Empty String Values ............................................................................................. 1-10Data Type for Material Quantities and Currency Amounts.................................................. 1-10

Sample Code Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1SessionManager...........................................................................................................................2-1

Transaction Management ..................................................................................................... 2-1LoadCollection ...................................................................................................................... 2-1LoadListOfValues.................................................................................................................. 2-2CreateIDO, CreateInstance, and Calling IDO Methods ........................................................ 2-2Passing a Form Name to a Method ...................................................................................... 2-3UserName............................................................................................................................. 2-3

FileSystemObject .........................................................................................................................2-3GetFolder .............................................................................................................................. 2-3FileExists............................................................................................................................... 2-4DeleteFile .............................................................................................................................. 2-4Writing to a File ..................................................................................................................... 2-5Reading a File ....................................................................................................................... 2-5

Converting WinStudio Script Code from VBA to VB.NET i

Copyright © 2007, Infor. All Rights Reserved.

Page 4: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

ii Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 5: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Preface __________________________________________This document is designed to assist in upgrading to SyteLine 8 from SyteLine 7. To upgrade, it is necessary to convert any custom WinStudio script code in version 7 from Visual Basic for Applications to Visual Basic .NET.

For More InformationThe most current version of all documentation is available on the Infor support Web pages (see “Contacting Infor Support").

For the most up-to-date list of software and hardware requirements for Infor products, see the Guide to Technology. This document also lists typical system administration tasks you should be familiar with before attempting to install and administer Infor products.

Contacting Infor Support If you cannot find the answer to a question in this document or in the product’s online help, contact Infor Global Support at our support Web site http://www.infor365.com. Simply log in and select your product area. From this site, you can do the following:

• Gain easy access to critical support resources like the Knowledge Center, software updates, and release notes.

• Obtain documentation for your product.

• Log and track incidents.

• Access the tools you need to keep your software running efficiently.

• Link to additional Infor resources.

Planning Your Communication To make sure the correct analyst is assigned to your case and to expedite the resolution of your questions, please have the following information available when you call us:

• Company name and phone number

• SyteLine version release and point release

• Database software version and release, if applicable

• Platform or environment (example: Windows® 2003)

• If you received an error message, the full message text and error number

• If you are calling back on an existing case, the Case Number

Signing Up for Support If you are not currently using support and would like more information on support options, please call your customer account representative. If you are not sure who your account representative is, contact Infor Customer Service.

Converting WinStudio Script Code from VBA to VB.NET v

Copyright © 2007, Infor. All Rights Reserved.

Page 6: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

vi Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 7: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

1Converting Code from VBA to VB.NET _________

This document provides instructions for converting WinStudio script code from Visual Basic for Applications (VBA) to Visual Basic .NET (VB.NET). SyteLine version 7 used VBA in global scripts, form scripts, and in-line scripts. Beginning with version 8, SyteLine requires VB.NET. This change corresponds to changes in the Infor framework from version 5.0 to version 6.0.

Users of this document should be familiar with developing scripts in VBA and VB.NET and with the WinStudio API.

For additional guidelines on converting code from VBA to VB.NET, see

http://msdn2.microsoft.com/en-us/library/aa192490(office.11).aspx

General Considerations Include the following Option statements and Imports statements at the top of each script:

Option Explicit On Option Strict On

Imports System Imports Microsoft.VisualBasic Imports Mongoose.IDO.Protocol Imports Mongoose.Scripting

After the Option and Imports statements, wrap each script in a namespace and class name as follows:

• Global Script (where ClassName is the name of the global script) Namespace SyteLine.GlobalScripts Public class ClassName Inherits GlobalScript ...[procedure code] ...End Class End Namespace

• Form Script (where ClassName is the name of the form) Namespace SyteLine.FormScripts Public class ClassName Inherits FormScript ...[procedure code] ... End Class End Namespace

Converting WinStudio Script Code from VBA to VB.NET 1-1

Copyright © 2007, Infor. All Rights Reserved.

Page 8: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

WinStudio API Considerations Automatic Conversion of Method and Property Names

Automatic conversion of API elements shown in the following table are attempted during conversion from VBA to VB.NET. Depending on the surrounding context, some elements may be missed. There is no sophisticated expression parsing at this point. Elements not listed must be converted manually.

Object Return TypesChange of type for WinStudio objects returned by WinStudio properties and methods:

In declaration statements with VB.NET, you can specify either version 6.0 return types, such as IWSApplication, or Object type. Use of specific 6.0 types provides advantages such as IntelliSense and ease of code maintenance and readability.

Examples:

Cache/Collection

VBA

Dim oCache As CacheSet oCache = ThisForm.PrimaryCache

VB.NET

Dim oCache As IWSIDOCollectionoCache = ThisForm.PrimaryIDOCollection

Component

VBA

Dim oComponent As ObjectSet oComponent = ThisForm.Components("ComponentName")

VB.NET

Dim oComponent As IWSFormComponentoComponent = ThisForm.Components("ComponentName")

Convert VBA Name from ... To VB.NET NamePrimaryCache PrimaryIDOCollectionCurrentCache CurrentIDOCollectionGetSecondaryCache GetSecondaryIDOCollectionGetCache IDOCollectionVBANumericToDisplayNumeric OSNumericToDisplayNumericVBADateToDisplayDate OSDateToDisplayDateToVBADec ToOSDec

WinStudio Object VBA Return Type (version 5.0)

VB.NET Return Type(version 6.0)

Application Application (or Object) IWSApplicationForm Document (or Object) IWSFormComponent CompWrapper (or Object) IWSFormComponentVariables(name) n.a. IWSVariableCache Cache (or Object) IWSIDOCollection

1-2 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 9: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

Values Property with For EachWith For Each, you must use the Values property in the collection name. For example, rather than In ThisForm.Components, use In ThisForm.Components.Values. Omitting the Values property may not generate a compile-time error but can cause errors at run time. (The Values property can appear on any VB.NET IDictionary collection object. All WinStudio object collections are now represented as IDictionary collections.)

Example:

VBA

Dim oForm As ObjectFor Each oForm in Application.Forms

VB.NET

Dim oForm As IWSFormFor Each oForm in Application.Forms.Values

Likewise, with VB.NET use ThisForm.Components.Values and ThisForm.LinkedChildForms.Values.

Text Property and Component ValuesWhen referencing the value of a component, include the Text property. For example, instead of ThisForm.Components("ComponentName"), use ThisForm.Components("ComponentName").Text.

GetStringValueWith the GetStringValue method, you must specify the Application object. Example: Application.GetStringValue("StringName").

ThisFormYou must specify the ThisForm object to access the current form's properties and methods in form scripts. This specification was not required in version 5.0 of the framework.

Code that references the current form's methods or properties directly should be changed to include the ThisForm specification: ThisForm.method_or_property_name. Code without the specification causes a compile error after conversion of the script.

IDO Method CallsThe following example shows an IDO method call in VBA code to the EncryptPassword method on the UserNames IDO:

Dim EncryptedPassword As Object Dim UserNames As Variant

ReturnValue = "0"

strPassword = GetParameter(0) Application.DiagnosticsLog ("Password: " & strPassword)

Set UserNames = Application.SessionManager.CreateInstance("MGCore.UserNames")

UserNames.EncryptPassword strPassword, EncryptedPassword

Converting WinStudio Script Code from VBA to VB.NET 1-3

Copyright © 2007, Infor. All Rights Reserved.

Page 10: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

With VB.NET, use the IDOClient.Invoke method. Pass the IDO name, the method name, and all parameters. Output parameters can be passed as IDONull.Value unless you are passing in usable data on those parameters. Retrieving data into the output parameters is done in the Response.Parameters(n) method where n is a zero-based parameter number. (InvokeResponseData, IDOClient, and IDONull are new objects in the WinStudio 6.0 API.)

Dim EncryptedPassword As Object Dim Response As InvokeResponseData

ReturnValue = "0"

strPassword = GetParameter(0) Application.DiagnosticsLog ("Password: " & strPassword)

Response=IDOClient.Invoke("MGCore.UserNames", "EncryptPassword", _ strPassword, IDONull.Value )

EncryptedPassword = Response.Parameters(1)

For more information about converting IDO method calls and code that references SessionManager, see Chapter 2, “Sample Code Conversions."

Substitution ParametersIn version 6.0 of the toolset, interpreted substitution parameters are not supported in inline scripts. In version 5.0, %1 in VBA code would be replaced with the value of the first parameter, %2 with the value of the second parameter, and so forth. This substitution occurred just before the code was compiled. Support for referencing parameter values in this way was discontinued in version 6.0 for various reasons; the primary reason was that the interpretive pass on the code required that the inline script be recompiled every time it was run.

To convert VBA code to VB.NET code in version 6.0, change %1, %2,..., %n to GetParameter(0), GetParameter(1),..., GetParameter(n). If the rewritten code is too long to fit the size limit of an inline script, then the validator should be changed to call a standard global script. A global script with the appropriate code must be created.

Dates, Numbers, and InternationalizationIn version 6.0 of the framework, new APIs eliminate the need to format strings for internationalization. You can use a new set of APIs parallel to the functionality of the IDOProtocol's property and method parameter APIs. See Modifying Infor ERP SL on the support site (“Contacting Infor Support” on page v).

VBA-to-VB.NET Conversion Issues Parentheses in Method Calls

Parameters in certain method calls in VBA did not have to be enclosed in parentheses. In VB.NET, all method calls must end with enclosing parentheses whether parameters are required or not. The Visual Studio 2005 editor automatically adds parentheses around parameters in VBA code.

OptionIn VB.NET, Option statements, such as Option Explicit, must occur before the first Imports statement.

1-4 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 11: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

Let and SetLet and Set statements are not supported in VB.NET. Remove the Let or Set keyword and/or recode the line as necessary.

Variable Names and Reserved WordsSome variable names in VBA may not be allowed because they are now keywords. Example: Operator.

Case-Sensitive Method NamesMethod names in VB.NET assemblies are case sensitive. The name of a method called by an event handler and the name of the method in script code must match.

Garbage Collection and Setting an Object Equal to NothingIn VB.NET, garbage collection is performed asynchronously. Setting an object equal to Nothing simply marks the object as eligible for collection, but when the object will actually be collected is indeterminate.

With the SessionInterface object, setting the object equal to Nothing does not end a session immediately. An explicit logoff is necessary. For example, the VBA code

Set lobjSessionInterface = Nothing

should be replaced by the following in VB.NET:

lobjSessionInterface.Logoff

CreateObjectVarious uses of the VBA function CreateObject must be manually recoded.

Example:

VBA

Set fso = CreateObject("Scripting.FileSystemObject")If Not fso.FolderExists(lpath) Then

GoTo ErrorHandler End If

VB.NET

If Not Directory.Exists(lPath) Then GoTo ErrorHandler

End If

The VB.NET code requires Imports System.IO at the top of the script. For more information about converting code that references the FileSystemObject, see Chapter 2, “Sample Code Conversions."

In VBA scripts, COM objects created by CreateObject can be replaced, in some cases, with built-in .NET methods.

• MSXML2.DOMDocument. Replacement: classes in the System.XML namespace such as XMLDocument and XMLElement.

• MSComDlg.CommonDialog. Replacement to create the "file open" dialog box: the method ShowOpenFileDialog.

• WScript.Shell. Replacement to launch an application: the method System.Diagnostics.Process.Start.

Converting WinStudio Script Code from VBA to VB.NET 1-5

Copyright © 2007, Infor. All Rights Reserved.

Page 12: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

• MSMQQueueInfo and MSMQMessage. Replacement: classes in the System.Messaging namespace.

See “References to Assemblies” on page 7.

Variant Data TypeThe Variant data type is not supported in VB.NET. Use Object instead.

On initial conversion, we can change all Variant declarations to Object, but the user must evaluate each to see what the appropriate type should be.

Possible problems include changing Variant to Object for a string value and the object is referenced before anything has been assigned to it. In such a case, the declaration should probably be changed manually to a String data type.

The Visual Studio 2005 editor automatically converts the Variant data type to Object in VBA code.

Long Data TypeThe VBA Long data type is the same size as the VB.NET Integer data type.

WendWend (end of While loop) is not supported in VB.NET. Use End While instead.

Variable DeclarationVariables must be declared in VB.NET.

Declarations (Dim statements) could be omitted in VBA if Option Explicit was not specified. Option Explicit was recommended even for VBA coding but was not always used.

Function Return ValuesVBA does not require you to set a function's return value. VB.NET requires this, so return value specifications must be added. All global scripts should be Sub (not Function) procedures, so return values should not be an issue with them. For form scripts (ActiveX scripts), set the function return type to As Integer. (Currently, this change must be made manually; it may become part of the automatic conversion.)

Value Assignments RequiredIn VB.NET, you cannot use an object until it has been assigned a value. You must assign a default value or null to all objects before trying to reference them. In most cases, this is probably done in the current code. Code should check for null objects before trying to reference properties or methods of the object.

IDO property index numbers can differ in versions 5.0 and 6.0The RowPointer property is in the always-included property list in version 6.0; the property was not always included in version 5.0. Property index numbers can differ by one in the two versions. Scripts in version 5.0 that access properties by referring directly to the index may fail in version 6.0.

Example: In version 5.0, oMainCache.GetPropertyName(0) = "Job" was true. In version 6.0, "Job" occurs at index 1 rather than 0.

1-6 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 13: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

References to AssembliesWinStudio supports Imports statements (or Using statements in C#) for .NET built-in assemblies and third-party assemblies that require references to the assemblies as part of the compile and run time.

Most assemblies, such as System.XML and System.Windows.Forms, require an explicit reference to the .dll file in the framework compile parameters. System.dll and Microsoft.VisualBasic.dll do not require references.

Developers should use the special tags <Ref> and </Ref> inside a comment to specify a reference.

Syntax:

'// <Ref>assemblyname.dll</Ref>

• A reference comment starts with '// (in C# code, the comment starts with //)

• assemblyname.dll is the name of a .dll file for an Imports statement (or a Using statement in C#). A third-party assembly file should be located in the same folder as WinStudio.exe.

• Only one assembly name is allowed per line

• Only one pair of Ref tags is allowed per line

For standardization, all reference comments should immediately precede the block of VB.NET Imports statements.

The following is an example of a global script referencing the .NET System.Drawing.dll assembly to access the list of installed fonts.

Option Explicit OnOption Strict On

'// <Ref>System.Drawing.dll</Ref>Imports SystemImports System.DrawingImports System.Drawing.TextImports Microsoft.VisualBasicImports Mongoose.IDO.ProtocolImports Mongoose.Scripting

Namespace SyteLine.GlobalScripts Public Class ValidateFont Inherits GlobalScript

Sub Main() Dim FontList() As FontFamily Dim installedFontCollection As New InstalledFontCollection()

FontList = installedFontCollection.Families

'Loop through the array … etc.

End Sub End Class

Converting WinStudio Script Code from VBA to VB.NET 1-7

Copyright © 2007, Infor. All Rights Reserved.

Page 14: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

End Namespace

Using the WinStudio Script Editor to Fix Compiler Errors When you fix errors requiring the addition (or deletion) of lines of code, recompile before trying to navigate through the errors. Otherwise, all line references after the lines added or deleted will be incorrect.

Editing Code with the EditWinStudioScript Visual Studio Project

You can edit script code in the Visual Studio editor by copying a script from the WinStudio script editor and pasting it into the ScriptClass.vb file of the EditWinStudioScript project. You can then edit the code in Visual Studio with IntelliSense, keyword highlighting, VB.NET formatting, VB.NET syntax checking, and so forth. You can also run test compiles.

Since this project is standalone (not associated with WinStudio), you must copy and paste it back into the WinStudio editor to save any desired changes in the WinStudio forms database. For WinStudio to use the script, the script must be compiled in the WinStudio script editor.

When using the EditWinStudioScript project for repeated editing of various scripts, delete the current script from the ScriptClass.vb file before pasting the new one in.

To Debug a Script Converted to VB.NET To debug a script with WinStudio, you create a separate debugging session in Visual Studio 2005, attach the WinStudio process, and then call the script in WinStudio run mode. You can then debug the script in the debugging session.

The procedure described in this topic applies to form scripts, but the main steps apply equally to global scripts.

1. Open a form and enter design mode.

2. On the Edit menu, click Visual Basic Editor. The form script opens in the Visual Studio IDE.

3. Close the Visual Studio IDE.

4. In the WinStudio Editing Script in Visual Studio dialog box, select the Compile for Debug check box.

5. Click Debug. If the script compiles successfully, it is opened in another instance of Visual Studio, a debugging session.

6. Set a break point on the desired line in the script in the debugging session.

7. On the Visual Studio Debug menu in the debugging session, click Attach to Process.

8. Select an instance of the WinStudio.exe process whose Type is TSQL, Managed, x86 and whose Title is Editing Script in Visual Studio.

9. Click Attach.

Before you use Visual Studio 2005 to debug a script, see "Configure a Script Editor" in the WinStudio Help (on the Help menu, click Customizing Forms).

1-8 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 15: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

10. Minimize the Visual Studio debugging session.

11. Click OK to close the Editing Script in Visual Studio dialog box.

12. Exit WinStudio design mode.

13. Perform an action in the form that calls the script. When the script is called and the breakpoint is encountered, focus changes to the Visual Studio debugging session attached to WinStudio. From this point, you can debug the script as you would debug any VB.NET code.

14. When you are done debugging, on the Debug menu in the Visual Studio debugging session, click Stop Debugging.

15. Close Visual Studio.

16. Save the form definition.

Miscellaneous Guidelines for Coding VB.NET in SyteLineBoolean Data Type

As a general rule, store VB.NET Boolean values in WinStudio variables as the string "1" for True or the string "0" for False. Avoid expressions such as CStr(CInt(bool)) to evaluate a Boolean for storage in a variable because the expression yields -1 for True.

In this example, the VB.NET expression bool is evaluated to set the WinStudio variable Parm_SharedCust to "1":

bool = True...ThisForm.Variables("Parm_SharedCust").Value = IIf(bool, "1", "0")

Only one instance of Visual Studio can be attached for debug to WinStudio.

If you make additional changes to the code you are debugging and attempt a second Debug compile of the modified code, you will receive a compile error similar to one of the following:

•In the WinStudio script editor: "Unable to write output file 'C:\Documents and Settings\UserName\Local Settings\Application Data\Infor\WinStudio\GlobalScripts\ScriptName.dll.'"

•In the Editing Script in Visual Studio dialog box: "Compile Failed. If script compiles OK when Debug is not checked, try closing and reopening form or doing an unload global objects, and try again."

Compiling for Debug writes an assembly file (along with source and symbols) to disk. The error message indicates that the target assembly file cannot be overwritten because it is currently in use. Once an assembly is loaded into an application domain (in this case the Global script domain or the Form script domain), the only way it can be unloaded is to unload the domain.

To unload a global script, select the WinStudio menu command Form > Definition > Unload all Global Form Objects.

To unload a form script, close the form and reopen it.

Converting WinStudio Script Code from VBA to VB.NET 1-9

Copyright © 2007, Infor. All Rights Reserved.

Page 16: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Converting Code from VBA to VB.NET

A subsequent condition evaluates to True because the value of Parm_SharedCust is not "0":

If ThisForm.Variables("Parm_SharedCust").Value <> "0" Then ...End If

VB.NET ConstantsMost VB.NET constants, such as vbYes and vbNo, are integers. Store VB.NET constants in WinStudio variables as the string value of the constant. Example:

ThisForm.Variables("PromptResponse").Value = CStr(vbYes)...If ThisForm.Variables("PromptResponse").Value = CStr(vbYes) Then

...End if

Null and Empty String ValuesTo detect null or empty strings in properties or WinStudio variables, use code of this type:

IDONull.IsNull(ThisForm.Variables("variable_name").Value)

If the value of variable_name is null or an empty string, the expression evaluates to True.

The IDONull.IsNull(object) method should be used when you want to test whether an object is a null value. The method returns Boolean True if the object is determined to be null. This test covers a variety of circumstances. If the object is a string, then IsNull evaluates to True when the string object is null or when the string is an empty value (“”). It evaluates to True when the specified object itself is null. IDONull.IsNull(object) tests all the cases where the WinStudio framework considers an object to be null.

The IDONull.Value property should be used when a null value is to be passed to a parameter in an IDO method call. (See the sample code using IDONull.Value with the IDOClient.Invoke method call on page 1-4.)

Data Type for Material Quantities and Currency AmountsUse CDec to coerce values for material quantities and currency amounts to the Decimal data type.

VB.NET can yield inaccurate results when adding or subtracting values of the type Double whose result is a fractional negative number. For instance, subtracting the following two numbers (using either intrinsic casting or explicit casting) yields the result indicated below:

5.5 - 5.55 = -4.99999999999998E-02

CDbl(5.5) - CDbl(5.55) = -4.99999999999998E-02

This same calculation done with Decimal casting yields the expected exact result:

CDec(5.5) - CDec(5.55) = -0.05

See also: http://msdn2.microsoft.com/en-US/library/xkd5z2s9(VS.80).aspx.

The advantage of using Decimal variables for money values is the precision of the values. The Double data type is faster and requires less memory, but it is subject to rounding errors. The Decimal data type retains complete accuracy to 28 places if necessary.

Most values in SyteLine are material quantities and currency amounts. Data types have generally not been a source of performance problems.

1-10 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 17: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

2Sample Code Conversions

SessionManager VBA scripts may use methods and classes under Application.SessionManager. Such scripts must be modified in order to use toolset 6.0.

Transaction ManagementForm scripts or inline scripts that use transaction management via the SessionManager must be modified, as client management of transactions is not supported in toolset 6.0. Transactions are handled in the middle tier or the database.

LoadCollectionVBA code that uses the LoadCollection method of the SessionInterface object should be modfied to use LoadCollection from the IDOClient namespace.

VBA

Set oSession = CreateObject("SYMIX.SessionInterface")oSession.SessionObject = SessionManagerSet oCos = oSession.LoadCollection("SL.SLCos", "ConfigId, CfgMainConfigGid, CfgMainConfigModel", _ "CoNum = '" & ThisForm.Components("OldCoNumGrid") & "'", 1, "")

If Not oCos.EOF Then If oCos.GetProperty("ConfigId") <> "" Then ThisForm.Variables("ConfigId").Value = _ oCos.GetProperty("ConfigId") End IfEnd If

VB.NET

Dim loadResponse As LoadCollectionResponseData

loadResponse = Me.IDOClient.LoadCollection( _ "SLCos", _ "ConfigId, CfgMainConfigGid, CfgMainConfigModel", _ "CoNum = '" & ThisForm.Components("OldCoNumGrid").Text & "'",_ "", -1)

If loadResponse.Items.Count > 0 Then If Not IDONull.IsNull(loadResponse(0, "ConfigId").Value) Then ThisForm.Variables("ConfigId").Value = loadResponse(0, _ "ConfigId").Value End IfEnd If

Converting WinStudio Script Code from VBA to VB.NET 2-1

Copyright © 2007, Infor. All Rights Reserved.

Page 18: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Sample Code Conversions

LoadListOfValuesVBA code that uses LoadListOfValues can be modified to use LoadCollection instead.

VBA

Set Session = CreateObject("Symix.SessionInterface")Session.SessionObject = Application.SessionManagerSet oGeneratedTaxRecords = Session.CreateCollection()

oGeneratedTaxRecords.LoadListOfValues _ "SL.SLTTVouchers", _ "CLM_VchPrTaxDistributionSp", _ "Type, PoNum, TaxSystem, TaxCode, TaxCodeE, AmtTaxBasis, AmtTaxAmount, DerSalesTax1, DerSalesTax2", _ strPreRegister

VB.NET

Dim idoRequest As New IDORequest(RequestType.LoadCollection)Dim idoResponse As IDOResponseDim loadRequest As New LoadCollectionRequestData()

' build a LoadCollection requestloadRequest.IDOName = "<ido-name>"loadRequest.PropertyList = New PropertyList("prop1, prop2") ' add the custom load methodloadRequest.CustomLoadMethod.Name = "MyCustomLoad"loadRequest.CustomLoadMethod.Parameters.Add("parm1")loadRequest.CustomLoadMethod.Parameters.Add("parm2")

' Add payload to IDORequestidoRequest.SetRequestPayload(loadRequest)

' Post request and get responseidoResponse = Me.IDOClient.GetResponse(idoRequest)

If idoResponse.ErrorInfo Is Nothing Then Dim loadResponse As LoadCollectionResponseData loadResponse = CType(idoResponse.GetResponsePayload(), _ LoadCollectionResponseData)

' process resultsEnd If

CreateIDO, CreateInstance, and Calling IDO MethodsVBA code that uses CreateIDO or CreateInstance should be modified to use the Invoke method on the IDOClient.

VBA

Dim objSLCustdrfts As ObjectSet objSLCustdrfts = _ Application.SessionManager.CreateInstance("SL.SLCustdrfts")intRetVal = objSLCustdrfts.ARDraftRemUpdateSp(intDraftNum, _ strDraftStatus, strMessage)

2-2 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 19: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Sample Code Conversions

VB.NET

Dim objSLCustdrfts As InvokeResponseDataobjSLCustdrfts = IDOClient.Invoke("SL.SLCustdrfts", "ARDraftRemUpdateSp", strDraftNum, _strDraftStatus, strMessage)')intRetVal = CInt(objSLCustdrfts.ReturnValue)')

Passing a Form Name to a MethodIn code like

Application.SessionManager.CreateIDO("SL.SLCtps", 0, "", ThisForm.Name, ""))

you must add a parameter, as in this example:

Dim request As New InvokeRequestData()Dim response As InvokeResponseData

request.IDOName = "SLCtps"request.MethodName = "ApsGatewaySync"' Add parameters like this:' request.Parameters.Add( parmValue )

request.SetContext( ThisForm.Name )

response = Application.IDOClient.Invoke( request )

UserNameScripts that use Application.SessionManager.UserName can be modified to use IDOClient.SessionID instead.

FileSystemObjectAny instances of Scripting.FileSystemObject in VBA code must be replaced with .NET methods using the System.IO namespace.

GetFolderVBA scripts that use GetFolder must be changed to use the DirectoryInfo class. In the example below, the GetFolder method causes an error if a directory does not exist.

VBA

Dim fso As ObjectDim fld As ObjectDim lPath As String On Error GoTo ErrorHandler lPath = ThisForm.Components("EFTDirectoryEdit") Set fso = CreateObject("Scripting.FileSystemObject") Set fld = fso.GetFolder(lPath) Exit FunctionErrorHandler:

Converting WinStudio Script Code from VBA to VB.NET 2-3

Copyright © 2007, Infor. All Rights Reserved.

Page 20: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Sample Code Conversions

ThisForm.CallGlobalScript "MsgApp", "Clear", "Prompt", "SuccessFailure", "mW=NoExist1", "@sDirectory", "@sPath", lPath, "", "", "", "", "", "", "", "", "", "", "", "", ""Return Failure

VB.NET

With VB.NET, use the Exists property of the DirectoryInfo class:

Dim lPath As StringlPath = ThisForm.Components("EFTDirectoryEdit")Dim dDir As New DirectoryInfo(lPath)

If dDir.Exists Then Return SuccessElse ThisForm.CallGlobalScript "MsgApp", "Clear", "Prompt", "SuccessFailure", "mW=NoExist1", "@sDirectory", "@sPath", lPath, "", "", "", "", "", "", "", "", "", "", "", "", "" Return Failure End If

FileExistsVBA scripts that use FileExists should be changed to use the FileInfo class. In this example, FileExists returns True or False depending on the file status.

VBA

Dim fs As ObjectSet fs = CreateObject("Scripting.FileSystemObject")

If fs.FileExists(strFileName) = True Then 'Do ProcessingEnd If

VB.NET

Dim fFile As New FileInfo(strFileName) If fFile.FileExists Then 'Do ProcessingEnd If

DeleteFileVBA scripts that use DeleteFile should be changed to use the Delete method of the FileInfo class.

VBA

fs.DeleteFile(filename)

VB.NET

Dim fFile As New FileInfo(strFileName) fFile.Delete()

2-4 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.

Page 21: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Sample Code Conversions

Writing to a FileVBA scripts that write to files must be modified.

VBA

Using FileSystemObject, the following methods must be replaced.

Set fs = CreateObject("Scripting.FileSystemObject") ' Write to FileSet fCollectOut = fs.OpenTextFile(strFileName, ForAppending, True)fCollectOut.WriteLine (strText)fCollectOut.Close

VB.NET

Dim writer As StreamWriter = New StreamWriter(strFileName, TRUE)' set 2nd parameter to TRUE if file mode is append, else FALSE.

writer.WriteLine(strText)writer.Close()

To write a single variable into a new file, the following can be used:

writer.Write (strText)

Reading a FileScripts that read from files must be modified.

VBA

Set fs = CreateObject("Scripting.FileSystemObject") Set fImtrans = fs.OpenTextFile(strFileName)True)Do While fImtrans.atendofstream <> True strData = fImtrans.ReadLine ' PROCESS LINELoop

VB.NET

Dim reader As StreamReader = New StreamReader(strFileName)Do While reader.Peek <> -1 strData = reader.ReadLine() ' PROCESS LINELoop

reader.Close()

To read an entire file into a single variable, the following can be used:

strData = reader.ReadToEnd()

Converting WinStudio Script Code from VBA to VB.NET 2-5

Copyright © 2007, Infor. All Rights Reserved.

Page 22: from VBA to VB - Abbey Codeabbeycode.com/allpro/BTA/Documentation/Converting... · from VBA to VB.NET Infor ERP SL Version 8.00. Converting WinStudio Script Code from VBA to VB.NET

Sample Code Conversions

2-6 Converting WinStudio Script Code from VBA to VB.NET

Copyright © 2007, Infor. All Rights Reserved.