DotNetFactory

本文介绍了如何使用QTP中的DotNetFactory创建和操作.NET对象,涵盖了数组、日期时间格式化、邮件发送等功能,并提供了丰富的示例代码。

DotNetFactory

QTP9.2 add a new DotNetFactory utility object which allows creating instances of .net classes in QTP.The object provide only one method,CreateInatance:

Set var_CreateInstance=DotNetFactory.CreateInstance(TypeName [,Assembly][,args])

The method takes the following parameters

TypeName : the name of class to be instantiated,

Assembly : name of Assembly

Args:parameter to be passed  to the .net object constructor, this is needed to create object instance when there is no parameter-less constructor

The DotNetFactory factory has greatly enhanced what we can achieve in QTP,that is why we has a chapter dedicated to discussing this feature in detail.

Using the DotNETFactory Object

The dotFactoryMethod only have one method CreateInstance, and this method is the default method,and we do not need to use it name explicitly when we create a new .net object

set oForm=dotNetFactory("System.Windows.Forms.Form","System.Windows.Forms")

Passing Parameters to Class Constructors

Some constructor need require passing object as parameter

Set oImageFormats=dotNetFactory("System.Drawing.Imaging.ImageFormat","System.Windows.Forms")      

 

Attempt to execute to execute this code will throws the following erroring:

When we inspect the constructor for the imageFormat class in .net documentation , it mentions:

Public Sub New(ByVal guid,guid as Guid)

This constructor take a Guid structure object,the problem of passing a GUID object to the above function is that GUID is .net Structure and not a class,we can only create .net classes and not the structure with the dotNetFactory,now we can pass a dummy parameter equal to “nothing”

set oImageFormats=dotNetFactory("System.Drawing.Imaging.ImageFormat","System.Windows.Forms",nothing)

 

Passing Parameters to .net Objects

set oTextBox=dotNetFactory("System.Windows.Forms.TextBox","System.Windows.Forms")

oTextBox.PasswordChar="*"

set oTextBox=nothing

Attempting to execute this code will produces the following error

The error occurs because the PasswordChar property excepts a .net Character parameter and we are passing a vbscript string parameter,there are two possible workarounds for this issue.

                    

method1

set oTextBox=dotNetFactory("System.Windows.Forms.TextBox","System.Windows.Forms")

oTextBox.PasswordChar=CBYTE(ASC("*"))

set oTextBox=nothing

'method2

set oTextBox=dotNetFactory("System.Windows.Forms.TextBox","System.Windows.Forms")

set convert=dotNetFactory("System.Convert","System")

oTextBox.PasswordChar=convert.ToChar("*")

set oTextBox=nothing

Passing Enums

The following code in .net module displays a .net form on the center of the screen

Dim oForm as System.Windows.Forms.Form=new oForm

oForm.StartPosition=FormStartPosition.CenterScreen

But we can’t use this code in QTP , because we don’t have the access to the FormStartPosition.centerScreen constant, to develop a solution we need to see how the Enums FormStartPosition is defined in .net

Public Enum FormStartPosition

‘fileds

CenterParent=4

CenterScreen=1

Manual=0

WindowDefaultBounds=3

WindowDefaultLocation=2

End Enum

So we can try to execute the following code in QTP to assign the StartPosition:

Set oForm=DotNetFactory("System.Windows.Forms.Form")

Const CenterScreen=1

oForm.startPosition=centerScreen

But attempt to execute the above code throw the following exception:

This exception occurs because in .net everything is a object, and includes enmu values, so when we attempt to assign a numeric value ,the conversion from numeric to enum object does not occur and hence we get a exception,but we can use a workaround here:

Set oForm=DotNetFactory("System.Windows.Forms.Form")

set StartPosition=oForm.startPosition

oForm.startPosition=StartPosition.CenterScreen

In the second line we get the startPosition object,which is of  type (具有/..类型) System.Windows.Forms.FormStartPosition.so whenerver we pass a .Net enum object to a function,we need to find a property that is a child of another object which returns the required data type

Working with .net Arrays

.net arrays are not similar to QTP arrays,and therefore we can’t use functions like UBound and LBound with them,They also do not support ‘for each’ iteration construct either

Set Screen=DotNetFactory.CreateInstance("System.Windows.Forms.Screen")

Set allScreens=Screen.AllScreens

print "total available screen -"&allScreens.length

'error,returns a empty value

screen1=allScreens(0)

'causes object required: 'allScreen(...)'

Set screen1=allScreens(0)

The last two statements,which is fail to access array values demonstrate that we cannot enumerate the .net arrays in the typical maner in QTP,to successfully access .net array element,we need to use the array’s .net enumerator object as follows:

Set Screen=DotNetFactory.CreateInstance("System.Windows.Forms.Screen")

'get a array of all the screens connected to the system

Set allScreens=Screen.AllScreens

Set enmuScreen=allScreens.GetEnumerator()

While enmuScreen.MoveNext

Set oScreen=enmuScreen.current

print "device name"+oScreen.DeviceName

print "Bounds-"+ oScreen.Bounds.ToString()

print "type-"+oScreen.getType().ToString()

print "Working area-"+oScreen.WorkingArea.ToString()

print "Primary Acreen-"+oScreen.Primary.ToString()

print vbNewLine

Wend

The code mentioned above produces the following output on my mechine:

device name\\.\DISPLAY1

Bounds-{X=0,Y=0,Width=1280,Height=800}

type-System.Windows.Forms.Screen

Working area-{X=0,Y=0,Width=1280,Height=770}

Primary Acreen-True

So far we have discussed solutions for some of the commonly faced issues when DotNetFactory is used,Now we will look at some additional examples and explore various .net classes

Playing a Wav File

Set obj=DotNetFactory("Microsoft.VisualBasic.Devices.Audio","Microsoft.VisualBasic")

obj.play "D:\SoundLog.wav"

set obj=nothing

Working with the Clipboard

Set obj=DotNetFactory("Microsoft.VisualBasic.Devices.Computer","Microsoft.VisualBasic")

 Print "Clipboard Text-"&obj.Clipboard.GetText()

obj.Clipboard.clear()

obj.Clipboard.SetText "this is a test"

 Print "Clipboard Text-"&obj.Clipboard.GetText()

set obj=nothing

Getting Computer Information

'Get the .NET Computer object

Set Obj = DotNetFactory("Microsoft.VisualBasic.Devices.Computer","Microsoft.VisualBasic")

'Get the computer info object

 

Set compInfo = Obj.Info

'Print details about system

Print "AvailablePhysicalMemory - " & compInfo.AvailablePhysicalMemory

Print "AvailableVirtualMemory - " &  compInfo.AvailableVirtualMemory

Print "OSFullName - " &  compInfo.OSFullName

Print "OSPlatform - " &  compInfo.OSPlatform

Print "OSVersion - " &  compInfo.OSVersion

Print "TotalPhysicalMemory - " &  compInfo.TotalPhysicalMemory

Print "TotalVirtualMemory - " &  compInfo.TotalVirtualMemory

 

'Destroy the object

Set Obj = Nothing

Accessing the Registry

'Get the .NET Computer object

Set Obj = DotNetFactory("Microsoft.VisualBasic.Devices.Computer","Microsoft.VisualBasic")

 

Set Registry = obj.Registry

IEPathKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\IEXPLORE.EXE"

 

'Get the path of iexplore.exe from registry

Print "Internet explore location - " & Registry.GetValue(IEPathKey, "","")

 

'Set a value in registry

Registry.SetValue "HKEY_CURRENT_USER\Software\MyApp", "Path", "C:\Test.exe"

Ping an IP Address

Before discussing the code to ping an ip address,let’s first explore the IFF function which reduces the lines of code

 

'------------------------------------------------------------------------------------------

'Function IIf. Returns TrueValue if Condition is True

'Else returns false value

Public Function IIf(condition, TrueValue, FalseValue)

  If Condition Then

    IIf = TrueValue

  Else

    IIf = FalseValue

  End If

End Function

 

 

'------------------------------------------------------------------------------------------

'Create a .NET network object

Set obj = DotNetFactory("Microsoft.VisualBasic.Devices.Network","Microsoft.VisualBasic")

 

pingSuccess = obj.Ping ("127.0.0.1")

 

Print IIf(pingSuccess, "Ping was Successful", "Ping was UnSuccessful")

 

'Max wait for 10 sec for ping

pingSuccess = obj.Ping ("127.0.0.1" ,10000) 

 

Set obj = Nothing

Evaluateing KeyBoard Control key Status

'Create the .NET object keyboard

Set obj = DotNetFactory("Microsoft.VisualBasic.Devices.Keyboard","Microsoft.VisualBasic")

 

'Check the status of various control keys

Print IIf(obj.AltKeyDown ,"Alt Key is down", "Alt key is NOT down")

Print IIf(obj.CapsLock, "Caps lock is ON", "Caps lock is OFF")

Print IIf(obj.CtrlKeyDown ,"CTRL Key is down", "CTRL key is NOT down")

Print IIf(obj.NumLock, "Num lock is ON", "Num lock is OFF")

Print IIf(obj.ScrollLock,"Scroll Lock is ON", "Scroll Lock is OFF")

Print IIf(obj.ShiftKeyDown, "Shift key is down", "Shift key is not down")

 

Set obj = Nothing

The code given above checks the status of various keyboard Control keys

.net Arrays Revisited

Working with .net ArrayList

'Instantiate an Array List

Set arrArray = DotNetFactory("System.Collections.ArrayList","System")

 

With arrArray

  'Add few elements

  .Add "e"

  .Add "b"

  .Add "c"

  .Add "a"

  .Add "d"

 

  'Get the Index of A

  Print "Index of A - " & .IndexOf("a")

 

  .Sort

  Print "Index of A after Sorting array - " & .IndexOf("a")

 

  .Reverse

  Print "Index of A after reversing array - " & .IndexOf("a")

 

  Print "Value at index 1 - " & .Item(1)

End With

 

Set arrArray = Nothing

The code mentioned above produces the following output

Index of A - 3

Index of A after Sorting array - 0

Index of A after reversing array - 4

Value at index 1 - d

Working with .net stacks

 

'Instantiate a Stack object

Set Stack = DotNetFactory("System.Collections.Stack","System")

 

'Add objects to Queue

Stack.Push "Tarun"

Stack.Push "Varun"

 

x = Stack.Pop

'Prints Varun

Print x

 

x = Stack.Peek

'Prints Tarun

Print x

 

x = Stack.Pop

'Prints Tarun

Print x

 

Set Stack = Nothing

The code mentioned above produces the following output

Varu

Tarun

Tarun

Working with .net Queus

 

'Instantiate a Queue object

Set Queue = DotNetFactory("System.Collections.Queue","System")

 

'Add objects to Queue

Queue.Enqueue "Tarun"

Queue.Enqueue 1

 

x = Queue.Dequeue

'Prints Tarun

Print x

 

x = Queue.Peek

'Prints 1

Print x

 

x = Queue.Dequeue

'Prints 1

Print x

 

Set Queue = Nothing

The code mentioned above produces the following output

Tarun

1

1

Working with .net Date and Time Formating

Create the DateTime object

Set DateTime = DotNetFactory ("System.DateTime")

 

'GMTTime

Print "GMT Time (MM/dd/yyyy hh:mm tt) - " & DateTime.Now.ToUniversalTime.toString("MM/dd/yyyy hh:mm tt")

 

'Current Time

Print "Date (dd-MMM-yyyy) - " & DateTime.Now.toString("dd-MMM-yyyy")

Print "Date (dddd, dd-MMMM-yyyy) - " & DateTime.Now.toString("dddd, dd-MMMM-yyyy")

Print "DateTime (dd-MMM-yyyy hh:mm:ss tt) - " & DateTime.Now.toString("dd-MMM-yyyy hh:mm:ss tt")

 

Set DateTime = Nothing

The code mentioned above produces the following output

GMT Time (MM/dd/yyyy hh:mm tt) - 07-29-2012 11:11 上午

Date (dd-MMM-yyyy) - 29-七月-2012

Date (dddd, dd-MMMM-yyyy) - 星期日, 29-七月-2012

DateTime (dd-MMM-yyyy hh:mm:ss tt) - 29-七月-2012 07:11:31 下午

Sending Emails using .Net

'Create a .NET MailMessage object

Set oMailMessage = DotNetFactory("System.Net.Mail.MailMessage")

 

'Set the From mail address with a display name also

Set oMailMessage.From = DotNetFactory("System.Net.Mail.MailAddress","System","nobody@nowhere.com", "No Where Dot Com")

 

'Add a recipient to TO list with email address only

oMailMessage.To.Add DotNetFactory("System.Net.Mail.MailAddress","System","noone@nowhere.com")

 

'Add a recipient to CC list with mail address and display name

oMailMessage.CC.Add DotNetFactory("System.Net.Mail.MailAddress","System","someone@nowhere.com","I am someone")

 

'Add a recipient to BCC list

oMailMessage.BCC.Add DotNetFactory("System.Net.Mail.MailAddress","System","hidden@nowhere.com")

 

'Subject line of the email

oMailMessage.Subject = "Test Mail from QTP"

 

'Body of the email

oMailMessage.Body = "<h1>Test E - Mail from QTP"

 

'Mark the body as a HTML type

oMailMessage.isBodyHTML = True

 

'Add and attachment to the email

oMailMessage.Attachments.Add DotNetFactory("System.Net.Mail.Attachment","System","C:\TestAttachment.txt")

Once the MailMessage object has been constructed, we can send the message use a smptClient object as show in the following code:

Set oSmptClient=DotNetFactory.CreateInstance("System.Net.Mail.SmptClient","System")

oSmptClient.host="smpt.nowhere.com"

oSmptClient.Port=25

oSmptClient.send  oMailMessage

We can also use a simpler and shorter technique to send a single recipient a plain text email message using the following code:

oSmptClient.send  "from@nowwhere.com","to@nowwhere.com","Test Subject", "Test Body"

Convert images to other File Formats

'Convert image from one format to the another format

Public Function ConvertImage(ByVal fromFile, ByVal toFile)

  Dim oImageLib ' as System.Drawing.Image

 

  'Create the .NET image object

  Set oImageLib = DotNetFactory.CreateInstance("System.Drawing.Image")

 

  Dim oImage

 

  'Get the Image from file

  Set oImage =  oImageLib.FromFile(fromFile)

 

  'Convert the file

  oImage.Save toFile, GetImageFormat(toFile)

 

  'Destroy the image

  oImage.Dispose

 

  'Clean up objects

  Set oImage = Nothing

  Set oImageLib = Nothing

  Set oImageFormats = Nothing

End Function

 

 

 

Public Function GetImageFormat(byVal fileName)

  'Get the file extension from the destination file name

  'Pass a dummy Nothing parameter to the constructor in place of Guid

  Set oImageFormats = DotNetFactory.CreateInstance ("System.Drawing.Imaging.ImageFormat","System.Drawing", Nothing)

 

  newFileExtension = GetFileExtension(lcase(fileName))

 

  'Get the image format based on the file name

  Select Case newFileExtension

    Case "jpg", "jpeg"

      Set oNewImgFormat = oImageFormats.Jpeg

    Case "gif"

      Set oNewImgFormat = oImageFormats.gif

    Case "tiff"

      Set oNewImgFormat = oImageFormats.Tiff

    Case "wmf"

      Set oNewImgFormat = oImageFormats.wmf

    Case "emf"

      Set oNewImgFormat = oImageFormats.emf

    Case "exif"

      Set oNewImgFormat = oImageFormats.Exif

    Case "bmp"

      Set oNewImgFormat = oImageFormats.Bmp

    Case "png"

      Set oNewImgFormat = oImageFormats.Png

    Case Else

      Set oNewImgFormat = oImageFormats.Png

  End Select

 

  Set GetImageFormat = oNewImgFormat

 

  Set oImageFormats = Nothing

End Function

 

'Get the file extenstion of a given file name

Public Function GetFileExtension(ByVal FileName)

  lastDot = InStrRev(FileName,".")

  If lastDot Then

    GetFileExtension = Mid(FileName, lastDot + 1)

  Else

    GetFileExtension = ""

  End If

End Function

 

 

Desktop.CaptureBitmap "D:\testing.bmp",True

ConvertImage "D:\testing.bmp", "D:\testing.jpg"

ConvertImage "D:\testing.bmp", "D:\testing.gif"

ConvertImage "D:\testing.bmp", "D:\testing.png"

ConvertImage "D:\testing.bmp", "D:\testing.tiff"

Getting user Input using .NET Forms

 

 

'Function to get a Point object

Public Function GetPoint(x,y)

  'Create a POINT object with constructor int, int

                     Set GetPoint = DotNetFactory("System.Drawing.Point","System.Drawing", x, y)

End Function

 

'Function to get a Size object

Public Function GetSize(x,y)

  'Create a Size object with constructor int, int

                     Set GetSize = DotNetFactory("System.Drawing.Size","System.Drawing", x, y)

End Function

 

'X, Y coordinate for a Label

lStartX = 15

StartY = 20

labelWidth = 75

 

'Width and height of each control

controlWidth = 160

controlHeight = 25

 

'X coordinate of a control in front of the variable

cDelta = lStartX + labelWidth + 10

 

'Difference in height between two controls

deltaHeight = 30

 

'Create a Label object for the requested user name

Set oLabelUserName = Dotnetfactory("System.Windows.Forms.Label","System.Windows.Forms")

 

'Set the properties of the user name Label

With oLabelUserName

  'Set the Size of the Label

                     .Size = GetSize(labelWidth, controlHeight)

                    

                     'Set the location of the Label on the form

                     .Location = GetPoint(lStartX, StartY)

                    

                     'Text to display for the Label

                     .Text = "&User Name:"

                    

                     'Tab index. Since we are using &UserName

                     'When user press ALT + U the label will get the focus

                     'But since a label cannot take focus the focus is passed

                     'on to the control with a higher tab index

                     .tabIndex = 0

End with

 

'Create an input text box object for the requested user name

Set oTxtUserName = DotNetFactory("System.Windows.Forms.TextBox","System.Windows.Forms")

 

'Set the text box properties

With oTxtUserName

  'name of the text box

                     .Name = "txtUserName"

                    

                     'Size and location

                     .Size = GetSize(controlWidth, controlHeight)

                     .Location = GetPoint(lStartX + cDelta, StartY)

                     .TabIndex = 1

End with

 

'Increase the Y coordinate to displace the new controls

StartY = StartY + deltaHeight

 

'Create the password label object and set its properties

Set oLabelPassword = Dotnetfactory("System.Windows.Forms.Label","System.Windows.Forms")

With oLabelPassword

                     .Text = "&Password:"

                     .Size = GetSize(labelWidth, controlHeight)

                     .Location = GetPoint(lStartX, StartY)

                     .TabIndex = 2

End with

 

'Create the text box object for the requested password

Set oTxtPassword = DotNetFactory("System.Windows.Forms.TextBox","System.Windows.Forms")

With oTxtPassword

                     .Name = "txtPassword"

                     .Size = GetSize(controlWidth, controlHeight)

                     'Set the password character property. PasswordChar only

                     'accepts a char parameter, so convert the * string to a Byte

                     .PasswordChar = Cbyte(Asc("*"))

                     .Location = GetPoint(lStartX + cDelta, StartY)

                     .TabIndex = 3

End with

 

'Increase the Y coordinate for the new controls

StartY = StartY + deltaHeight

 

'Create a Label for the requested Environment and set its properties

Set oLabelEnvironment = Dotnetfactory("System.Windows.Forms.Label","System.Windows.Forms")

With oLabelEnvironment

                     .Text = "&Environment:"

                     .Size = GetSize(labelWidth, controlHeight)

                     .Location = GetPoint(lStartX, StartY)

                     .TabIndex = 4

End with

 

'Create a combo box object for the the requested Environment

Set oLstEnvironment = DotNetFactory("System.Windows.Forms.ComboBox","System.Windows.Forms")

 

With oLstEnvironment

  'Name the list box

                     .Name = "lstEnvironment"

                     .Size = GetSize(controlWidth, controlHeight)

                     .Location = GetPoint(lStartX + cDelta, StartY)

                     .TabIndex = 5

 

  'Clear all items in the combo box list

                     .Items.Clear

                    

                     'Add items to the combo box list

                     .Items.Add "Local Environment"

                     .Items.Add "Testing Environment"

                     .Items.Add "Staging Environment"

                     .Items.Add "Production Environment"

                    

                     'Set the default as the Testing environment

                     .SelectedIndex = 1

End with

 

'Create the .NET form object

Set oForm = DotNetFactory("System.Windows.Forms.Form","System.Windows.Forms")

 

 

With oForm

                     'Title for the form

                     .Text = "Enter environment details"

                    

                     'Make it the top most window

                     .TopMost = True

                    

                     'Set the startup position a CenterScreen

                     .StartPosition = .StartPosition.CenterScreen

                    

                     'Set the form style as a fixed tool window

                     .FormBorderStyle = .FormBorderStyle.FixedToolWindow

                    

                     'Set the size of the window

                     .Size = GetSize(300,150)

 

  'Add the controls we just created to the form

                     .Controls.Add oLabelUserName

                     .Controls.Add oTxtUserName

 

                     .Controls.Add oLabelPassword

                     .Controls.Add oTxtPassword

 

                     .Controls.Add oLabelEnvironment

                     .Controls.Add oLstEnvironment

                    

                     'Show the form as a modal dialog. Code execution will advance to

                     'next line after the user closes the form

                     .ShowDialog()

 

  'Pause for one second

                     Wait 1

                    

                     'Get the user specified values from each form control

                     sUserName = oTxtUserName.Text

                     sPassword = oTxtPassword.Text

                     sEnvironment = oLstEnvironment.Text

 

                     'Close the form

                     .Close

End With

 

'Dispose of all the .Net objects

oLabelUserName.dispose

oTxtUserName.dispose

oLabelPassword.dispose

oTxtPassword.dispose

oLabelEnvironment.dispose

oLstEnvironment.dispose

oForm.dispose

 

'Destroy all of the object reference

Set oLabelUserName = Nothing

Set oTxtUserName = Nothing

Set oLabelPassword = Nothing

Set oTxtPassword = Nothing

Set oLabelEnvironment = Nothing

Set oLstEnvironment = Nothing

Set oForm = Nothing

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值