programming guidelines 08-01-2013

Upload: md-rahman

Post on 16-Oct-2015

14 views

Category:

Documents


0 download

DESCRIPTION

d

TRANSCRIPT

  • 1

    Contents Coding Best Practices .................................................................................................................................... 3

    General Guidelines .................................................................................................................................... 3

    Creating an Application ............................................................................................................................. 4

    Overview ............................................................................................................................................... 4

    Step 1 Create the project ................................................................................................................... 4

    Step 2 Prepare Project For Use With OnRamp .................................................................................. 4

    Step 3 Adding the application to OnRamp IDE .................................................................................. 5

    Using modCommon Functions .................................................................................................................. 6

    Overview ............................................................................................................................................... 6

    Quick DB Query Functions .................................................................................................................... 6

    Other modCommon Functions ............................................................................................................. 7

    SQL ............................................................................................................................................................ 8

    Overview ............................................................................................................................................... 8

    SQL Writing Rules .................................................................................................................................. 8

    SQL Code Rules ..................................................................................................................................... 9

    Dynamic SQL Writing Rules ................................................................................................................... 9

    Database Connections From Code ........................................................................................................ 9

    Record sets .......................................................................................................................................... 10

    No NULLS in DB ................................................................................................................................... 12

    SQL Code Example: ............................................................................................................................. 14

    Using Temp Tables .............................................................................................................................. 15

    OnRamp IDE ................................................................................................................................................ 16

    Code Groups ........................................................................................................................................... 16

    Overview ............................................................................................................................................. 16

    Codes - System/Local .......................................................................................................................... 16

    Business Info ....................................................................................................................................... 16

    Components ............................................................................................................................................ 16

    Tables & Fields .................................................................................................................................... 16

  • 2

    .NET Coding Differences ............................................................................................................................. 17

  • 3

    Coding Best Practices

    General Guidelines

    Comment all of your code so the next programmer can look at it, and pick up on the theory faster.

    ALWAYS use Option Explicit declaration for all modules.

    Make sure the code in your database is compiled. In the Module window, click Compile And Save All

    Modules on the Debug Menu.

    Make sure to recompile your code after you rename a database file. Renaming a database

    decompiles the code in the database.

    Always explicitly declare variables. You can require that variables be explicitly declared before they

    are used in a procedure by setting the Require Variable Declaration option on the Module tab of the

    Options dialog box.

    Use the most specific type possible when you declare variables. For example, declare a variable that

    will be used to represent a form as type Form rather than as type Object or Variant.

    Use variables to refer to properties, controls and data access objects. If you refer more than once to

    the value of a property or control on a form, or to a data access object or its property, create object

    variables and refer to the variables rather than using full identifiers.

    Use the llf function judiciously. Avoid using the llf function if either of the return expressions takes a

    long time to evaluate.

    Use the Me keyword for form references within an event procedure.

    Use string functions when appropriate. Use the $ functions (for example, the Str$ function) when

    working with strings and the non $ functions when working with Variant or other data types.

    Use the Integer and Long data type for math when possible.

    Use dynamic arrays and the Erase or ReDim statement to reclaim memory.

    Use constants whenever possible.

    Use bookmarks for fast relocation. Use bookmarks instead of the FindNext method or some other

    means to return to a particular record.

    Use the FindRecord and FindNext methods on indexed fields. These methods are much more

    efficient when used on a field that is indexed.

    Organize your modules. Visual Basic loads modules on demand, that is, it loads a module into

    memory only when your code calls one of the [procedures in that module. Placing related

    procedures in the same module causes Visual Basic to load additional modules only as needed.

    Eliminate dead code and unused variables. As you develop and modify your applications, you may

    leave behind procedures that aren't called from anywhere in your code or declared variables that

    are no longer used. Consider reviewing your code to find and remove unused procedures and

    variables.

  • 4

    Creating an Application

    Overview

    The OnRamp engine and IDE are capable of a lot of the functions necessary for creating many business

    logic solutions. There are times however, where more complicated tasks are required, like iterating

    through recordsets, and other more complex logic. For this we create standard EXE applications that are

    called from OnRamp through command line arguments.

    Every application can be called from OnRamps IDE through multiple processes, and varying command

    line arguments.

    Step 1 Create the project

    Open Microsoft Visual SourceSafe 6.0 - now referred to as SS

    o Our SS contains two main root directories

    Apps

    This is where we will create and store our unique application

    Common

    This is where all of the common modules are stored such as modCommon

    and modPrint. Items that are referenced by multiple applications.

    o To add a new app to the root Apps folder, right click the Apps folder and hit Create

    Project

    Look for the latest AXXXX created, and name your app the next number iteration

    Naming convention: AXXXX ApplicationDesc

    o Now right-click your created application folder and Get latest version

    This adds the folder to your local working directory

    Open Microsoft Visual Basic 6.0 - now referred to as VB6

    o Create new Standard EXE project and remove the default created Form1 from project

    o Add new module to the project, and name it something useful to your applications function

    o Save the project to the newly created Working Folder AXXXX ApplicationDesc

    Do not Add to source Safe when prompted - close VB6

    o To easily add to sourcesafe

    Drag the files from your working folder directly to the folder in SS

    o The application is now readily available to the entire OnRamp team, and requires

    checkin/checkout protocol to modify

    Step 2 Prepare Project For Use With OnRamp

    Check out the application in SS

    Add the following references to the project

    o Microsoft ActiveX Data Objects 2.8 Library

    o Microsoft ADO Ext. 2.8 for DDL and Security

    o Microsoft Scripting Runtime

    Now add the following common modules to the project

    o Go back to SS and get the latest ModCommon v2 and ModEnumeration

  • 5

    These two are NECESSARY for any OnRamp App to run

    o Add these two modules to the project from your working Common folder

    Add Option Explicit to the module

    Add the following code to the module

    Check in the project to SS

    Step 3 Adding the application to OnRamp IDE

    Add application to Application Master used for compiling/releasing the App

    o AppID/AppName should be the AXXXX that you created in SS

    o Enter in the .vbp project file name you created

    o Enter in the test.exe name that will be released when compiling the App

    o Set Target Release/Action

    o Enter in description

    o Enter in App Path (SS Path) $/Apps/AXXXX ApplicationDesc

    o Hit - Compile and Release to SIT

    Add application to Program Master used for reference by Process Master

    o Add a new program referencing the created:

    AXXXX as the ProgramID and test.exe as the Exe File

    Option Explicit

    Sub Main()

    'OnRamp Apps are called from the command line, use the following modCommon function

    to parse the CL args into an array.

    Call GetVars(Command)

    'access the array of CL Args with Pvar(i) Array

    Dim first_command_line_arg As String

    first_command_line_arg = N2S(pvar(0))

    'OnRamp uses a common file to pass messages between apps and the engine at runtime

    Call SetMessagingType(ChannelType.FILE_NEW)

    Call setup_messaging(False, svar(SystemParams.workingFolder))

    'This is how we send messages to OnRamp's message box

    Call send_message("Starting...", , MessageType.AppStart)

    End Sub

  • 6

    o Add a Description, and Target Release/Action

    o Hit Sync Selected;

    o Program Master allows us to specify multiple Command Line Call Cases for a given .exe

    The Options added for a given Program (.exe file) will be the first CL Arg - Pvar(0)

    Add an Option to the Created Program called TESTCASE1 with a description

    Add a new ProcessID to Process Master used for reference when calling from a Screen/Report

    o There will be a new ProcessID created for each Program Option you have created.

    o The process ID should use the naming convention of: AXXXX_TESTCASE1

    o Add a description, and set Type = PROG

    o Set ProgramID = AXXXX that you created in Program Master

    o Select the specific Program Option that we created TESTCASE1

    o Set Target Release/Action

    o Hit Sync Process

    Compile the Application from within OnRamp

    o This method compiles the .exe with an automated error handling routine.

    The application is now ready to be called from any Screen or Report using the Processes created.

    Using modCommon Functions

    Overview

    Quick DB Query Functions

    Function GetCurrencyRate

    o Returns the currency rate for a particular currency as of a specified date

    Function BusinessInfo

    o Returns the value of a particular business info factor

    Function GetNumberNew

    modCommon.GetCurrencyRate(

    DateEff as Date [enter as of date you need],

    CurrCode as String [enter currency code (ex: CDN/USD)]) as Double

    modCommon.BusinessInfo (

    strFactor as String [enter bus info factor to retrieve value ]) as String

  • 7

    o No AutoIDs are generated in OnRamps DB for any PK values (if they exist, its because

    there is no PK FK relationship. It is simply used to add an index to the table)

    o When inserting a new record into a table that requires an auto-generated PK ID, this

    function returns the next available integer for the code you want

    Quick DB Functions Code Example

    Other modCommon Functions

    Sending Mail

    To send email from the OnRamp IDE, create a new process call to the A1234 SendMail App.

    Handle a new case within the Main Procedure, for your needs.

    Function SetupEmail

    modCommon.GetNumberNew (

    strCode as String [Number Assign Code to retrieve next available ID],

    Optional qty as Integer = 1 [Deprecated dont use],

    Optional letter_flag as Boolean [whether to include prefix and suffix to ID],

    Optional dbNum as Long = 0 [the DB Conn to use as specified in db_config])

    OpenDB(0)

    Dim strSQL as string

    strSQL = SELECT fk_primkey, fk_business, fk_curr, fk_currRate _

    & FROM fk_fake WHERE 1 = 0

    runquery(strSQL, 0)

    manipulate record set

    With rstData(0)

    Add new Row

    .AddNew

    !fk_primkey = GetnumberNew(NUMBER_ASSIGN_CODE)

    !fk_business = BusinessInfo(CURRENT_FISCAL_MONTH)

    !fk_currRate = GetCurrencyRate(N2S(!fk_curr), Date())

    .Update

    End With

  • 8

    Function AddAttatchment

    SQL

    Overview

    Model the data in Access

    Test and create queries in Access to prove design. The Base SQL language is Access as the queries will be converted into SQL or Oracle or MySQL etc

    in the apps and OnRamp Engine

    SQL Writing Rules Because of this conversion, follow these rules for SQL writing Update statement should just update one table

    o If updating a table using JOIN, make sure the name of the updated table papers first in the JOIN clause for readability.

    Use bit instead of boolean o We use bit because it is easier to test for 1 or 0, than true or false, as true or false uses

    different integer objects in VB vs SQL vs .NET etc; just test for 1 or 0 The concatenations function should happen between two strings only. Strong type an int!

    o Ex: if we want to concatenate Hello and 2 to get Hello2 Hello & CSTR(2)

    Avoid using double quotes () in queries; use single quotes () When using date function in access, do not put any space between the closing # and the operator

    o Ex: #12/8/2009#+5 Do not use fully qualified wildcard char

    o Ex: USE DELETE * FROM emp_encrypt DO NOT USE - DELETE emp_encrypt.* FROM emp_encrypt

    Do not use NOT as part of an update query: o Ex:

    Private Function SetupEmail(

    strOpt As String[Who to send to VEND or CUST],

    strID As String[The ID of the vendor or customer you are sending to],

    strField As String[The field in peop_mstr that specifies the type of

    email youre sending],

    Optional subject As String[subject of email],

    Optional body As String[body of email],

    Optional priority As Integer[priority of email],

    Optional EmployeeCode As String[MailListType Code Group Optn]) As Boolean

    Public Sub AddAttachment(

    fileName As String [Filename to add to email])

  • 9

    USE UPDATE SET fld_field1 = Non Submit DO NOT USE - UPDATE SET fld_field1 = Not Submit

    Do not use nested selects within SQL Functions Do not use nested SELECTS within the WHERE clause of a cross tab query

    SQL Code Rules

    Do not use the same record set number for different rstType of record sets as it slows down code. In SQL Server, addition of records in record set is ~ 1000/second In Access, with type 3 rstType is ~50,000/second

    Dynamic SQL Writing Rules

    For readability and debugging, create a line break for SQL Keywords and CAPITLIZE them

    Limit SELECT fields to 3 per line, then concatenate

    Ensure INSERT fields match with SELECT fields per line.

    Database Connections From Code

    DB Config File (must be named db_config.txt)

    o .txt file containing connection strings to DBs you want to connect to

    o Must reside in Local App Folder for testing locally.

    Example of config file:

    Sub OpenDB:

    o Opens connection to specified DB

    INSERT INTO table_1 _

    & (aa, bb, cc, _

    & dd, ee, ff) _

    SELECT a, b, c, _

    & d, e, f

    FROM table_2

    0,SQL,ONRAMPDEV,OnrampData_SIT,sa,ou81to

    1,ACCESS,\\spnewfs\SPNEWFS\OnRampSystem\OR_SIT\System\Data\OnRampSetup.mdb,,,

    2,SQL,ONRAMPDEV,OnrampData_SIT_Archive,sa,ou81to

    3,SQL,ONRAMPDEV,OnrampData_SIT_Backup,sa,ou81to

  • 10

    Record sets

    Record sets are held in variable rstData(rsnum) array held in ModCommon where rsnum = 0-1000

    o Reserved rsnums

    20-40 = reserved for modCommon

    300-400 = reserved for modLabel

    Function RunQuery:

    o Opens up a record set within rstData array, at the specified position, with specified DBConn

    Returns 0 or 1. 0 = Records exist, moves cursor to first record / 1 = No records exist

    o rstType

    0, 1

    Utility, Fastest Read/Update/Add Functionality without overhead of

    Dynamic RSTs, good support for record changes

    2

    Read Only, Forward Only - For looping through record sets with no updates

    or moves, no locking

    3

    Engine RST - Dynamic Cursor supports all extra features, fastest locking

    available

    4

    Batch Updates - for adding/updating large amounts of records

    Requires a .Update/.CancelBatch once finished

    Function ExecuteQuery

    o Executes an UPDATE/INSERT/DELETE query on specified DB Connection

    modCommon.OpenDB(

    optional dbnum = 0 [number reference to DB Number in config file] )

    modCommon.RunQuery(

    q, [SELECT query string]

    num [rstData number (0-1000)],

    Optional dbnum = 0 [db connection string number],

    Optional rstType = 0 [rstType],

    Optional errorcode = 0 [error code])

  • 11

    o Returns 0 or err.description (set in function args)

    Use WHERE 1=0 when using a recordset to ONLY add new rows

    o When all we want to do is add records to a table using a recordset, we use the WHERE

    CLAUSE of WHERE 1=0 so that we return no existing rows improves speed

    Recordset Basic Manipulation

    Adding records to tables

    Unless adding 1000s of records to a table, the INSERT INTO Table statement should not be used

    in applications; instead, the .AddNew > .Update recordset method should be used

    o This helps with readability when debugging

    In the case of INSERT INTO Table (col1, col2) VALUE (val1, val2) a recordset .Addnew >.Update

    should always be used.

    o Often times when using this method, we are using variables from another recordset, so

    this helps with DataType compatibility

    modCommon.ExecuteQuery(

    q [Execute query string (INSERT)] ,

    Optional dbnum = 0 [db connection string],

    Optional rstError = 0 [0 = Return Nothing, 1 = Return err.description if error])

    as Integer

    With rstData(0)

    .Edit edit the current record

    !Column1Value = Set Column1 to this text

    .Update Updates row to live DB

    .AddNew Add a record to the recordset

    !Column1Value = Set Column1 value to this text for new record

    .Update Adds new record to Live DB

    .MoveFirst Moves the recordset cursor to the first record

    .MovLast Moves the cursor to the last record

    .Move Next Moves the cursor one position forward

    End With

  • 12

    o For Example:

    Recordsets Differences in .NET

    In .Net, recordset objects are not considered to have a default property.

    No NULLS in DB

    There are no NULLS in the OnRamp Database apart from DateTime fields

    To ensure this we use the following modCommon functions in our apps.

    Function N2S

    o Returns string, or empty string if NULL

    Function N2D

    o Returns double, or empty string if NULL

    Function N2Date

    o Returns date, or #1/1/1900# if not date or null

    With rstData(59)

    .AddNew

    !crm_cust = rstData(60).Fields("edicr_our_inv_to").Value

    !crm_ref_no = rstData(60).Fields("edicr_ref").Value

    .Update

    End With

    rstData(0)!Column1 = asdf VB6

    rstData(0).Column1.Value = asdf .NET - .Value property must be explicitly stated.

    modCommon.N2S(

    s [String to convert null string, to empty string]) as String

    modCommon.N2D(

    d [Double to convert null double, to empty string]) as String

  • 13

    modCommon.N2Date(

    d [Date to convert null date, to #1/1/1900#]) as Date

  • 14

    SQL Code Example:

    open connection

    OpenDB(0)

    use this for query function returns

    Dim a as integer

    set query string

    Dim strSQL as string

    strSQL = SELECT pt_part, pt_count_cf, pt_count_cap, _

    & pt_rev, pt_desc FROM pt_mstr

    open record set with strSQL command, into the 0-position of rstData

    a = runquery(strSQL, 0)

    If a = 1 then goto error: check rows exist

    manipulate record set

    Do Until (rstData(0).EOF = True)

    With rstData(0)

    do something with record set row

    Dim part as String

    Part = N2S(!pt_part) Ensures empty string is returned if NULL in DB

    .MoveNext

    End With

    Loop

    execute a query

    strSQL = DELETE FROM pt_mstr WHERE pt_part = 'asdf'

    a = ExecuteQuery(strSQL, 0, 1) execute query on DBNum 0, and return err.desc if err

    if a 0 then goto error: exec query returned error

    error:

    handle

  • 15

    Using Temp Tables

    Overview

    If a temptable is required in either an App or directly from the OnRamp IDE, the table temp_univ must

    be used.

    When using temp_univ, a unique userkey must be used to differentiate the temporary records, and you

    must ensure that these records are deleted upon completion of the process used.

    Naming convention for the userkey is Screen/ReportID & OnRampUser ex: S1234ccurran

    Temp_univ contains multiple columns, and datatypes that can be used in most scenarios.

    Temp_univ Table Definition

    Column Data Type

    tempu_auto int

    tempu_userkey nvarchar(255)

    tempu_s1 nvarchar(255)

    tempu_s2 nvarchar(255)

    tempu_s3 nvarchar(255)

    tempu_s4 nvarchar(255)

    tempu_s5 nvarchar(255)

    tempu_v1 float

    tempu_v2 float

    tempu_v3 float

    tempu_v4 float

    tempu_v5 float

    tempu_d1 datetime

    tempu_d2 datetime

    tempu_d3 datetime

    tempu_d4 datetime

    tempu_d5 datetime

    tempu_b1 tinyint

    tempu_b2 tinyint

    tempu_b3 tinyint

    tempu_b4 tinyint

    tempu_b5 tinyint

  • 16

    OnRamp IDE

    Code Groups

    Overview

    Code Groups are static info fields used by both the local business and system logic

    Codes - System/Local

    System Codes

    o These codes are used by the system in Look Up Queries - cannot be modified by

    production user.

    o Example:

    CodeGroup: BLOOD

    Lists the Blood Types including A, AB, B, O etc

    As these values will always be fixed, and dont differ from business to business,

    they are a SYSTEM Code

    Local Codes

    o Also used by Screen Detail Look Up Queries, however these can be manipulated by

    each business

    o Example:

    CodeGroup: INSPECTOR

    Allows the business to specify different Inspectors used in RMA returns,

    Quality Assurance etc as it will differ from plant to plant

    Business Info

    These differ from Local and System codes, in that they are always a one one relationship

    They include all of the info for a business including Address, Accounting Dates, Email, Phone etc.

    They are all set in the local business environment, not Mission Control

    Components

    Tables & Fields

    No two tables have the same field name, we ensure this with a unique prefix assigned to every

    table. OnRamp builds the table column names with this prefix. This prevents ambiguous column

    names in queries.

    Primary Key

    o All tables in OnRamp must contain a PK consisting of one or more columns

    o If the table has an AutoIncrement Type, it must be set as the PK with no other columns

    This is important as MySQL does not allow a PK to be anything but the autoID field.

    Procedure to add field

    o Pick Database, and table name from top frame

    o Click fields frame

    Add your field/column and set all key properties

  • 17

    Name/Key/Type

    Remember to Set Target Rel and Action of A for add

    o Click Tables frame and set build to Yes

    o Go back to menu, pick Rebuild Database To Sit.

    o Find your table, and click Rebuild SIT

    o The field is now in the SIT DB, and set to be released to customer environments on the

    package you assigned it to.

    .NET Coding Differences Variable Declaration

    In VB6 you are required to instantiate a variable object and then assign a value on a separate

    line.

    In .NET you can instantiate, and assign a value all on the same line.

    Integer Types

    VB6 System Type INT 16 INT 32 INT 64

    OBJECT Integer Long N/A

    Max Value 32,767 2,147,483,647 N/A

    .NET System Type INT 16 INT 32 INT 64

    OBJECT Short Integer Long

    Max Value 32,767 2,147,483,647 9,223,372,036,854,770,000

    VB6

    Dim s as String

    S = asdf

    .NET

    Dim s as String = asdf