Create QC Resource with uft - vbscript

I found a lot of examples about uploading a resource to ALM via UFT.
However there were always a resource already created in ALM.
How can i create and upload a resource to ALM using UFT?
My problem is I don't know how many resources I am going to need, so I have to dinamically create resources and then upload them.
I do not want to upload files as attachments to the run.
Thank you

I think I found the answer here: http://www.codetweet.com/other/create-new-resource-almqc-using-ota/
Sub CreateNewResource(resourceFolderId As Integer, fileType As String, fileName As String, fileParentFolderPath As String)
On Error GoTo Errhandler:
'--- Represents a file or folder stored in the Quality Center repository
Dim resource As QCResource
'--- Represents a QC resource folder.
Dim resourceFolder As QCResourceFolder
'--- Services for managing QC resources.
Dim resourceFactory As QCResourceFactory
'--- Services for managing QC resource folders.
Dim resourceFolderFactory As QCResourceFolderFactory
'--- Services to manage resource storage.
Dim testResourceStorage As IResourceStorage
Dim resourceItem
Dim resourceFound As Boolean
' ***TDConn is TDConnection class object.Create this object before using this function.
Set resourceFolderFactory = TDConn.QCResourceFolderFactory
Set resourceFolder = resourceFolderFactory.Item(resourceFolderId)
Set resourceFactory = resourceFolder.QCResourceFactory
Set currResourceList = resourceFactory.NewList("")
For ItemCount = 1 To currResourceList.Count
currItem = currResourceList.Item(ItemCount).Name
If UCase(currItem) = UCase(fileName) Then
Set resourceItem = currResourceList.Item(ItemCount)
resourceFound = True
Exit For
End If
Next
If Not resourceFound Then
'--- Create a resource
Set resourceItem = resourceFactory.AddItem(fileName)
resourceItem.ResourceType = fileType
resourceItem.fileName = fileName
resourceItem.Post
'--- Check if the resources added successfully
Set currResourceList = resourceFactory.NewList("")
For ItemCount = 1 To currResourceList.Count
currItem = currResourceList.Item(ItemCount).Name
If UCase(currItem) = UCase(fileName) Then
resourceFound = True
Exit For
End If
Next
If resourceFound Then
'--- Attach the file to resource
resourceItem.vC.CheckOut ""
Set testResourceStorage = resourceItem
testResourceStorage.UploadResource fileParentFolderPath, False
resourceItem.vC.CheckIn "Automated check-in by utility" & Now
Else
oFile.WriteLine ("Recently added new resource not found on ALM.Try again later.")
Exit Sub
End If
Else
resourceItem.vC.CheckOut ""
Set testResourceStorage = resourceItem
testResourceStorage.UploadResource fileParentFolderPath, False
resourceItem.vC.CheckIn "Automated check-in by utility" & Now
End If
Set resourceFolderFactory = Nothing
Set resourceFolder = Nothing
Set resourceFactory = Nothing
Set currResourceList = Nothing
Exit Sub
Errhandler:
MsgBox("Error Executing - `CreateNewResource` ; Error Uploading file " & fileName)
Exit Sub
End Sub

Related

Excel and Word behaving difrerently in the same code

I have a problem - instances of Excel and Word behave differently in the same procedure. Have a look at the code. The idea there is to have a procedure that handles resaving files in excel and word in various format combinations.
The problem is that I notice that word and excel behave differently - the appWord and appExcel have different type names. At some point appWord is changed from Application to Object, which then makes it impossible to close it. I don't understand the differences in the behaviour, since the code applied to them is identical.
Option Explicit
Dim fso
Dim appWord
Dim appExcel
Set fso = CreateObject("Scripting.FileSystemObject")
startWord
ResaveFiles appWord.Documents, "docx", 12, 0
appWord.quit
startExcel
ResaveFiles appExcel.Workbooks, "xlsx", 51, 56
appExcel.quit
MsgBox "All done."
Sub ResaveFiles(appType, srcExtName, srcExtNum, tmpExtNum)
Dim objFile
Dim objOpenFile
Dim strDirectory
For Each objFile in fso.GetFolder(".").Files
If lcase(fso.GetExtensionName(objFile)) = srcExtName Then
If typeName(appType) = "Documents" Then StartWord
If typeName(appType) = "Workbooks" Then StartExcel
Set objOpenFile = appType.Open(objFile.path)
strDirectory = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "._temp")
objOpenFile.SaveAs strDirectory, tmpExtNum
objOpenFile.Close
msgBox typename(appType) & objFile
msgBox typename(appWord) 'First typename test
msgBox Typename(appExcel)
If typeName(appType) = "Documents" Then appWord.Quit
If typeName(appType) = "Workbooks" Then appExcel.Quit
set objOpenFile = appType.Open(strDirectory)
objOpenFile.SaveAs objFile.path, srcExtNum
objOpenFile.Close
fso.DeleteFile(strDirectory)
msgBox typename(appWord) 'Second typename test
msgBox Typename(appExcel)
End If
Next
End Sub
'Start Word
Sub StartWord
Set appWord = CreateObject("Word.Application")
appWord.visible = false
appWord.DisplayAlerts = false
End Sub
'Start Excel
Sub StartExcel
Set appExcel = CreateObject("Excel.Application")
appExcel.visible = false
appExcel.DisplayAlerts = false
End Sub
I have tested it in the following way (with two typename tests) - when there are word files available, first appWord is Application and appExcel is empty, then it changes to Object and appExcel stays Empty (in this case we get an error when the subprocedure ends at AppWord.Quit). When there are no word files, and the script is processing Excels, first appWord is Object and appExcel is Application, then appWord is still Object and appExcel is still Application - in this case there are no errors when the subprocedure ends, on the appExcel.Quit.
Maybe i'm wrong, just my opinion:
If typeName(appType) = "Documents" Then appWord.Quit
If typeName(appType) = "Workbooks" Then appExcel.Quit
set objOpenFile = appType.Open(strDirectory)
appType is a reference to what appWord.Documents or appExcel.Workbooks are referencing before entering your ResaveFiles Sub, where you instantiate a new copy of 'Excel.Application' or 'Word.Application', and in each of the cases, you instruct the application TO QUIT. The question is not why in the case of word you got an error. From my point of view YOU SHOULD got an error. The question is why, if instructed to quit, excel keeps open and maintaining references to handle your code.
EDIT - And not tried. Just adapted from OP code. Adapt as needed
Option Explicit
ResaveFiles "Word.Application", "docx", 12, 0
ResaveFiles "Excel.Application", "xlsx", 51, 56
MsgBox "All done."
Sub ResaveFiles(progID, srcExtName, srcExtNum, tmpExtNum )
Dim app, doc
Dim fso, objFile, objOpenFile, strDirectory
Set fso = CreateObject("Scripting.FileSystemObject")
For Each objFile in fso.GetFolder( "." ).Files
If LCase(fso.GetExtensionName( objFile.Name )) = srcExtName Then
' Get references
Set app = GetNewAppInstance( progID )
Set doc = GetDocumentHandler( app )
' Save temp
Set objOpenFile = doc.Open( objFile.Path )
strDirectory = fso.BuildPath( objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "._temp" )
objOpenFile.SaveAs strDirectory, tmpExtNum
objOpenFile.Close
' Release objects
Set objOpenFile = nothing
Set doc = nothing
app.Quit
Set app = nothing
' Get references again
Set app = GetNewAppInstance( progID )
Set doc = GetDocumentHandler( app )
' Resave file
Set objOpenFile = doc.Open( strDirectory )
objOpenFile.SaveAs objFile.path, srcExtNum
objOpenFile.Close
' Release objects
Set objOpenFile = nothing
Set doc = nothing
app.Quit
Set app = nothing
' Clean
fso.DeleteFile(strDirectory)
End If
Next
End Sub
Function GetNewAppInstance( ByVal progID )
Set GetNewAppInstance = CreateObject( progID )
With GetNewAppInstance
.Visible = False
.DisplayAlerts = False
End With
End Function
Function GetDocumentHandler( app )
Dim name
name = app.Name
If InStr(name,"Excel") > 0 Then
Set GetDocumentHandler = app.Workbooks
ElseIf InStr(name,"Word") > 0 Then
Set GetDocumentHandler = app.Documents
Else
Set GetDocumentHandler = app
End If
End Function

How to set outlook folder initial view programatically

I want to set a public folder to have an initial view (custom view), I know how to do it manually on outlook 2007, however, I cannot find any property or method i can use in the Interop (Folder and MAPI folder) that can do this.
After a few hours of googling, i came out the following:
Imports NUnit.Framework
Imports System.Windows.Forms
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Net
Imports System.Runtime.InteropServices
Imports Outlook = Microsoft.Office.Interop.Outlook
<TestFixture()>
Public Class TestOutlook
<Explicit()>
<Test()>
Public Sub TestSetFolderInitialView()
Dim ol As New Outlook.Application
Dim exCatched As Exception = Nothing
Try
' Get My Mailbox
Dim myFolder As Outlook.MAPIFolder = Nothing
For i As Integer = 0 To ol.Session.Folders.Count - 1
myFolder = ol.Session.Folders(i + 1)
If myFolder.Name = "Mailbox - Rex" Then ' Change it to your mail box name
Exit For
End If
Next
' Get the folder I want to Set initial view
Dim testFolder As Outlook.MAPIFolder = Nothing
If myFolder IsNot Nothing Then
For i As Integer = 0 To myFolder.Folders.Count - 1
Dim pFolder = myFolder.Folders(i + 1)
If pFolder.Name = "Inbox" Then
For Each fol As Outlook.MAPIFolder In pFolder.Folders
If fol.Name = "TestFolder" Then
testFolder = fol
Exit For
End If
Next
Exit For
End If
Next
End If
If testFolder IsNot Nothing Then
Try
' Create a test view
Dim newVw = CType(testFolder.Views.Add("RexTest-" & DateTime.Now.ToString("yyyyMMdd-hhmmss"),
Outlook.OlViewType.olTableView,
Outlook.OlViewSaveOption.olViewSaveOptionThisFolderEveryone),
Outlook.TableView)
newVw.LockUserChanges = True
newVw.Save()
newVw.Apply()
' PR_DEFAULT_VIEW_ENTRYID:
Dim ns = "http://schemas.microsoft.com/mapi/proptag/"
Dim PR_DEFAULT_VIEW_ENTRYID = "0x36160102"
Dim PR_FOLDER_XVIEWINFO_E = "0x36E00102"
Dim defaultVw = testFolder.PropertyAccessor.GetProperty(ns & PR_DEFAULT_VIEW_ENTRYID)
Dim xVwInfo = testFolder.PropertyAccessor.GetProperty(ns & PR_FOLDER_XVIEWINFO_E)
' the defaultVw is nothing for the first time (actually throw exception)
' if i manually change it from the outlook,
' the value will be something like: 000000004B593F3D35EF8C42AB181C105AE444D40700E46C905CB9ABE446AA44351902AFC40E000026BF7A8C000040DB82FE9B98724F9B222A9C9BDB42CD0000005CF0280000
' **** The problem is how to get the correct binary data for the newly created view so i can set it like this: *****
'testFolder.PropertyAccessor.SetProperty(ns & PR_DEFAULT_VIEW_ENTRYID, testFolder.PropertyAccessor.StringToBinary(newVw.Name))
Catch ex As Exception
' _log.Warn(String.Format("Error set initial view {0} to folder - {1}", newVw.Name, testFolder.Name), ex)
exCatched = ex
' First time error 'The property "http://schemas.microsoft.com/mapi/proptag/0x36160102" is unknown or cannot be found' will be shown
' If we set the initial view of the folder in the outlook, this error will go away
End Try
End If
Catch ex As Exception
Debug.WriteLine(ex.Message)
Debug.WriteLine(ex.StackTrace)
exCatched = ex
Finally
If ol IsNot Nothing Then
Marshal.ReleaseComObject(ol)
ol = Nothing
End If
End Try
If exCatched IsNot Nothing Then
Throw exCatched
End If
End Sub
End Class
Now the only left part is how to get the correct binary data from the newly created view. some clue to manipulate the binary value: http://microsoft.public.win32.programmer.messaging.narkive.com/x1fNHHA5/default-view
however it was written in a different language and I got no idea how to make it in vb or c#.
any help appreciated.
Have you tried MAPIFolder.CurrentView and MAPIFolder.Views?

Visual Studio. How to copy record from database to word .doc and print it

In Visual studio 2010>New Project>Visual Basic>Windows>Windows forms Application, i have made a form (form1.vb) and a database (Local Database>"Database1.sdf") and a Table with 3 Columns ("Name","City","Age").
I like to copy this 3 fields and paste to document "test1.doc" (open this with Ms Office or Open Office Writer). I have bookmarks ("PasteName", PasteCity", "PasteAge") in specified places in test1.doc .
How to make a button to open the document "test1.doc" and copy - paste this 3 items from table to doc and preview before print it? (not for save - only print preview and close without save after printing)
I have find this code for MS Office but didn't work in Visual Studio. I like something similar. (this code is for a doc Form Fields - I have Bookmarks in my doc).
Private Sub cmdPrint_Click()
Dim appWord As Word.Application
Dim doc As Word.Document
Set appWord = GetObject(, "Word.Application")
Set appWord = New Word.Application
Set doc = appWord.Documents.Open("C:\WordForms\CustomerSlip.doc", , True)
With doc
.FormFields("fldCustomerID").Result = Me!CustomerID
.FormFields("fldCompanyName").Result = Me!CompanyName
.FormFields("fldContactName").Result = Me!ContactName
.Visible = True
.Activate
End With
Set doc = Nothing
Set appWord = Nothing
End Sub
Thanks programers people
This works for me. (button action)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Print customer slip for current customer.
Dim appWord As Word.Application
Dim doc As Word.Document
'Avoid error 429, when Word isn't open.
On Error Resume Next
Err.Clear()
'Set appWord object variable to running instance of Word.
appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
'If Word isn't open, create a new instance of Word.
appWord = New Word.Application
End If
doc = appWord.Documents.Open("D:\Test.docx", , True)
doc.Visible()
doc.Activate()
With doc.Bookmarks
.Item("Name").Range.Text = Me.NameID.Text
.Item("City").Range.Text = Me.CityID.Text
End With
Dim dlg As Word.Dialog
dlg = appWord.Dialogs.Item(Word.WdWordDialog.wdDialogFilePrint)
dlg.Display()
'doc.Printout
doc = Nothing
appWord = Nothing
Exit Sub
errHandler:
MsgBox(Err.Number & ": " & Err.Description)
End Sub

Upgrading VB6 code from Outlook 2007 to Outlook 2010

We want to upgrade our VB6 code to use Outlook 2010, but we're getting the following error:
Active x cannot create object
This is our current code:
Public Sub SendEmail()
Set emailOutlookApp = CreateObject("Outlook.Application.12")
Set emailNameSpace = emailOutlookApp.GetNamespace("MAPI")
Set emailFolder = emailNameSpace.GetDefaultFolder(olFolderInbox)
Set emailItem = emailOutlookApp.CreateItem(olMailItem)
Set EmailRecipient = emailItem.Recipients
EmailRecipient.Add (EmailAddress)
EmailRecipient.Add (EmailAddress2)
emailItem.Importance = olImportanceHigh
emailItem.Subject = "My Subject"
emailItem.Body = "The Body"
'-----Send the Email-----'
emailItem.Save
emailItem.Send
'-----Clear out the memory space held by variables-----'
Set emailNameSpace = Nothing
Set emailFolder = Nothing
Set emailItem = Nothing
Set emailOutlookApp = Nothing
Exit Sub
I'm not sure if "Outlook.Application.12" is correct. But I can't find a definitive answer for this.
For Outlook 2010, this is definitly corect Outlook.Application.14.
But, I don't know what about office 2007.
I think it's Outlook.Application.12 and for lower versions it is simply "Outlook.Application".
Here's the code I switched to for 2010:
Private Sub EmailBlahbutton_Click()
Dim mOutlookApp As Object
Dim OutMail As Object
Dim Intro As String
On Error GoTo ErrorHandler
Set mOutlookApp = GetObject("", "Outlook.application")
Set OutMail = mOutlookApp.CreateItem(0)
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
'These are the ranges being emailed.
ActiveSheet.Range(blahblahblah).Select
'Intro is the first line of the email
Intro = "BLAHBLAHBLHA"
'Set the To and Subject lines. Send the message.
With OutMail
.To = "blahblah#blah.com"
.Subject = "More BLAH here"
.HTMLBody = Intro & RangetoHTML(Selection)
.Send
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
ActiveSheet.Range("A1").Select
ActiveWindow.ScrollColumn = ActiveCell.Column
ActiveWindow.ScrollRow = ActiveCell.Row
Set OutMail = Nothing
Set mOutlookApp = Nothing
Exit Sub
ErrorHandler:
Set mOutlookApp = CreateObject("Outlook.application")
Resume Next
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2010
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Why do you explicitly specify the version? Why not simply
Set emailOutlookApp = CreateObject("Outlook.Application")
Try "Outlook.Application.14". Not sure if this is related though: 2007 to 2010 upgrade issue
I realize it's not the exact issue, but it may lead you down the right path.

VBScript Permission Denied on CopyFile

I'm running a VBScript in SQL Agent but I get a 'Permission Denied' on line 34 (the first copy attempt). I've run this script outside SQL Agent with no problems
FYI: The 'X:\' drive is mapped to a SharePoint folder. This may be the culprit.
Function Main()
Const SourceDrive As String = "X:\"
Dim fso
Dim Today
Dim FileName
Dim FromFile
Dim FromDrive
Dim ArchivePath
Set fso = CreateObject("Scripting.FileSystemObject")
Today = Format(Now, "yyyyMMdd")
'To add more sources just add them to the array list
Dim Sources() As Variant
Sources() = Array("Item1", _
"Item2")
'To add more targets just add them to the array list
Dim Targets() As Variant
Targets() = Array("C:\Users\myalias\Desktop\MyToFolder", _
"C:\Users\myalias\Desktop\MyToFolder2")
For i = 0 To UBound(Sources)
FileName = "WebSurveyAlertCallbacks_" & Sources(i) & "_" & Today & ".xls"
FromDrive = fso.BuildPath(SourceDrive, Sources(i))
FromFile = fso.BuildPath(FromDrive, FileName)
ArchivePath = fso.BuildPath(FromDrive, "Archive")
If fso.FileExists(FromFile) Then
For t = 0 To UBound(Targets)
fso.CopyFile FromFile, fso.BuildPath(Targets(t), FileName), True
Next
fso.CopyFile FromFile, fso.BuildPath(ArchivePath, FileName), True
fso.DeleteFile FromFile
End If
Next
Set fso = Nothing
Main = DTSTaskExecResult_Success
End Function
The agent probably runs under a different user-account (i.e. not you) and then doesn't have permissions to the files/folders you're using.
When you run it outside, it uses your logged on user's permissions and executes fine.

Resources