HPQC C# Create Test Planning Test - c#

Working on a QC integration tool and having trouble creating a test in the Test Plan - unfortunately the API is written for VB6, and I'm working in C#.
Here's what I've got so far:
private void HPQC_Create_Test_Plan_Test(TDConnectionClass tdConnection, string ParentFolderPath, string TestName)
{
try
{
TreeManager treeM = (TreeManager)tdConnection.TreeManager;
ISysTreeNode ParentFolder = (ISysTreeNode)treeM.get_NodeByPath(ParentFolderPath);
TestFactory TestF = (TestFactory)tdConnection.TestFactory;
Test TstTest = (Test)TestF.AddItem(System.DBNull.Value);
TstTest.Name = TestName;
TstTest.Type = "MANUAL";
TstTest.Post();
HPQC_Status_Test_Plan.Text = "Test " + TestName + " created.";
tdConnection.Logout();
tdConnection.Disconnect();
tdConnection = null;
}
catch (Exception ex)
{
HPQC_Status_Test_Plan.Text = "Test Creation Failed.";
Console.WriteLine("[Error] " + ex);
tdConnection.Logout();
tdConnection.Disconnect();
tdConnection = null;
}
}
The code errors out on the Post with a simple "Failed to Post" and I'm at a loss as to why.
Here's the API example in VB6:
Public Sub AddTest(FolderName$, TestName$)
Create new test.
This example assumes that the subject folder containing the
new test is directly under the root "Subject" folder.
Dim objTest As Test
Dim folder As SubjectNode
Dim testF As TestFactory
Dim TreeMgr As TreeManager
Dim Path As String
Dim Trees As List
Dim RootName As String
Dim SubjRoot As SubjectNode
'tdc is the global TDConnection object.
Set TreeMgr = tdc.TreeManager
' Use TreeManager.TreeRoot to get the list of subject
' root nodes from the tree manager.
' There is only one item in this list.
Set Trees = TreeMgr.RootList(TDOLE_SUBJECT)
' Get the name of the subject tree root in your project.
RootName = Trees.Item(1)
Path = RootName & "\" & FolderName
On Error Resume Next
Set folder = TreeMgr.NodeByPath(Path)
On Error GoTo 0
If folder Is Nothing Then 'Create the folder
' Get the SubjectNode root node object from the
' tree manager by name.
Set SubjRoot = TreeMgr.TreeRoot(RootName)
Set folder = SubjRoot.AddNode(FolderName)
End If
Set testF = folder.TestFactory
Set objTest = testF.AddItem(Null)
objTest.name = TestName
objTest.Type = "SYSTEM-TEST"
objTest.Post
Dim VerCtl As VCS
Dim bIsLocked As Boolean
Dim strLockedBy As String
Set VerCtl = objTest.VCS
VerCtl.Refresh
bIsLocked = VerCtl.IsLocked
strLockedBy = VerCtl.LockedBy
' After POST, Test is checked in.
Debug.Print "Is locked: " & bIsLocked
'Is locked: False
Debug.Print "Is locked by: """ & strLockedBy & """"
'Is locked by: ""
VerCtl.CheckOut -1, "To change state", True
VerCtl.Refresh
bIsLocked = VerCtl.IsLocked
strLockedBy = VerCtl.LockedBy
Debug.Print "Is locked: " & bIsLocked
'Is locked: True
Debug.Print "Is locked by: """ & strLockedBy & """"
'Is locked by: "User1"
' Take an arbitrary field to change.
Debug.Print "Status: """ & objTest.Field("TS_STATUS") & """"
'Status: ""
objTest.Field("TS_STATUS") = "Ready"
objTest.Post
VerCtl.CheckIn "", "Changed status"
VerCtl.Refresh
bIsLocked = VerCtl.IsLocked
strLockedBy = VerCtl.LockedBy
Debug.Print "Is locked: " & bIsLocked
'Is locked: False
Debug.Print "Is locked by: """ & strLockedBy & """"
'Is locked by: ""
End Sub
Thanks in advance!

I have something similar but more suited to generating a folder structure also.
Our root folder in QC is "Subject" but you can simply change this in order to create the specific folder you want. Also instead of setting the ["TS_SUBJECT"] title this is not required as we are using the node at the leaf node to create the tests into the specified folder.
private TestFactory addSubjectTreeStructure(String subjectField)
{
String folderRootString = subjectField;
folderRootString = folderRootString.Replace("\\", "/");
String[] folders = folderRootString.Split('/');
// Test Plan Tree Manager
TreeManager treeMgr = tdc.TreeManager;
SubjectNode subjectNode = treeMgr.get_NodeByPath("Subject");
ISysTreeNode node = (ISysTreeNode)subjectNode;
// Creating the folders in test plan.
for (int i = 0; i < folders.Length; i++)
{
try
{
node = node.FindChildNode(folders[i]);
}
catch (Exception ex)
{
node = node.AddNode(folders[i]);
Console.WriteLine(ex.Message + ".\nChild not found. Adding new node: " + folders[i]);
}
}
// Set the leaf folder and then returning the TestFactory from where all test cases will be generated from.
SubjectNode folder = treeMgr.get_NodeById(node.NodeID);
return folder.TestFactory;
}
Then by using the returned test factory you can create the tests in this folder.

Gave it the weekend to think it over, and realized that the code above didn't have a parent attribute to link to in the tree. Unfortunately TreeManager in C# does not have TreeRoot to work with for some reason.
Worked around that by grabbing the path manually for the prototype - the user has to key in parent path like "Root\Subject" into a textbox.
The key attribute was the "TS_Subject" which is the NodeID of the folder that you want to attach the test to.
The following code works for me:
private void HPQC_Create_Test_Plan_Test(TDConnectionClass tdConnection, string ParentFolderPath, string TestName)
{
try
{
TreeManager treeM = (TreeManager)tdConnection.TreeManager;
ISysTreeNode ParentFolder = (ISysTreeNode)treeM.get_NodeByPath(ParentFolderPath);
TestFactory TestF = (TestFactory)tdConnection.TestFactory;
Test TstTest = (Test)TestF.AddItem(System.DBNull.Value);
TstTest.Name = TestName;
TstTest.Type = "MANUAL";
TstTest["TS_SUBJECT"] = ParentFolder.NodeID;
TstTest.Post();
HPQC_Status_Test_Plan.Text = "Test " + TestName + " created.";
tdConnection.Logout();
tdConnection.Disconnect();
tdConnection = null;
}
catch (Exception ex)
{
HPQC_Status_Test_Plan.Text = "Test Creation Failed.";
Console.WriteLine("[Error] " + ex);
tdConnection.Logout();
tdConnection.Disconnect();
tdConnection = null;
}
}

Related

How to copy an Excel worksheet to an e-mail body with formatting?

I am creating a console application on a server, that will copy the contents of a MS Excel file (with colors and formatting) to the body of an e-mail. I am not trying to attach the worksheet, but simply copy it so that when the business users view the e-mail on their phone/tablet/device, they don't need the Excel application installed to view the report.
I need help in figuring out how to copy and display the worksheet in the body of the email.
Currently I have the following, but it only copies the actual string data, not any pretty formatting:
public static void pullDataFromExcel(string fileName)
{
string mySheetPath = #"C:\Users\lmilligan\Downloads\";
MSExcel.Application excelApp = new MSExcel.Application();
excelApp.DisplayAlerts = false;
excelApp.Visible = true;
MSExcel.Workbook book = excelApp.Workbooks.Open(mySheetPath + fileName);
MSExcel.Worksheet sheet = book.ActiveSheet;
book.RefreshAll();
var data = "";
foreach (MSExcel.Range row in sheet.UsedRange.Rows)
{
foreach (MSExcel.Range cell in row.Columns)
{
data += cell.Value + " ";
}
data += "\n";
}
MSOutlook.Application olApp = new MSOutlook.Application();
MailMessage mail = new MailMessage("email#myServer.com", "thisIsMe#myServer.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "mail.myServer.net";
mail.Subject = "AutoMailer test";
mail.Body = Convert.ToString(sheet);
client.Send(mail);
book.Save();
book.Close();
excelApp.Quit();
}
static void Main(string[] args)
{
pullDataFromExcel("mySheet.xlsx");
}
Not the exact answer you're looking for, but if you can live with a PDF attachment then I've used something similar to this before to export the active sheet as a PDF file including the formatting:
Sub PDFMail()
Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String
Dim OutlApp As Object
' Define PDF filename
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = PdfFile & FName & ".pdf"
' Export activesheet as PDF
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
' Use already open Outlook if possible
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
' Prepare e-mail with PDF attachment
With OutlApp.CreateItem(0)
' Prepare e-mail
.Subject = "SUBJECT HERE"
.To = "TO HERE"
.CC = "CC HERE
.BCC = "BCC HERE"
.Body = "BODY TEXT HERE"
.Attachments.Add PdfFile
' Try to send
On Error Resume Next
.Send
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0
End With
' Delete PDF file
Kill PdfFile
' Quit Outlook if it was created by this code
If IsCreated Then OutlApp.Quit
' Release the memory of object variable
Set OutlApp = Nothing
End Sub

VS consider ' as a comment note formula

I am trying to open a excel file in vb.net with excel interop
then add a formula to F2 then save as excel as csv
Can someone point me how to concatenate an ' with number in a formula cs when i write ' the Visual studio consider it as a comment not a formula
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim newFileName As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".csv"
Dim oExcelFile As Object
Try
oExcelFile = GetObject("c:\database", "Excel.Application")
Catch
oExcelFile = CreateObject("Excel.Application")
End Try
oExcelFile.Visible = True
Dim strfilename As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".xls"
Dim strFolderPath As String = "c:\database"
oExcelFile.Workbooks.Open(strFolderPath + "\" + strfilename)
Dim oExcelsheet As Excel.Worksheet
oExcelsheet = oExcelFile.sheets("table1")
oExcelsheet.Range("f1").Value = "CRC"
oExcelsheet.Range("f2").Formula = " = IF(LEN(A2)=2,(CONCATENATE("'00000",A2)),IF(LEN(A2)=3,CONCATENATE("'0000",A2),IF(LEN(A2)=4,CONCATENATE("'000",A2),IF(LEN(A2)=5,CONCATENATE("'00",A2),IF(LEN(A2)=6,CONCATENATE("'0",A2),A2)))))"
oExcelFile.DisplayAlerts = False
oExcelFile.ActiveWorkbook.SaveAs(Filename:=strFolderPath + "\" + newFileName, FileFormat:=Excel.XlFileFormat.xlCSV, CreateBackup:=False)
oExcelFile.ActiveWorkbook.Close(SaveChanges:=False)
Dim file_count As Integer = File.ReadAllLines(strFolderPath + "\" + newFileName).Length
MsgBox(file_count)
oExcelFile.DisplayAlerts = True
oExcelFile.Quit()
oExcelFile = Nothing
The problem is that you have included double quotes (") inside your string literal. The first double quote inside the string is taken to mean the end of the string. It happens to be followed by a single quote which indicate the start of a comment. If you include a double quote inside a string literal, you need to have two of them. Here is the corrected statement (I split it over three lines for readability).
oExcelsheet.Range("f2").Formula = "=IF(LEN(A2)=2,(CONCATENATE(""'00000"",A2))," _
& "IF(LEN(A2)=3,CONCATENATE(""'0000"",A2),IF(LEN(A2)=4,CONCATENATE(""'000"",A2)," _
& "IF(LEN(A2)=5,CONCATENATE(""'00"",A2),IF(LEN(A2)=6,CONCATENATE(""'0"",A2),A2)))))"

Convert from VBA to C#

I want to convert this VBA code in C# language but I get this error: 'SolidWorks.Interop.sldworks.IFace2.Normal' is a 'property' but is used like a 'method'
Please help me how can I resolve this error.
VBA:
Option Explicit On
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swFace As SldWorks.face2
Dim vNorm As Object
swApp = Application.SldWorks
swModel = swApp.ActiveDoc
swSelMgr = swModel.SelectionManager
swFace = swSelMgr.GetSelectedObject5(1)
vNorm = swFace.Normal
Debug.Print("Normal = (" & vNorm(0) & ", " & vNorm(1) & ", " & vNorm(2) & ")")
End Sub
C#:
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace NORMAL.csproj
{
public partial class SolidWorksMacro
{
public void Main()
{
SldWorks swApp = default(SldWorks); ModelDoc2 swModel = default(ModelDoc2); SelectionMgr swSelMgr = default(SelectionMgr); Face2 swFace = default(Face2);
swModel = (ModelDoc2)swApp.ActiveDoc;
swSelMgr = (SelectionMgr)swModel.SelectionManager;
swFace = (Face2)swSelMgr.GetSelectedObject6(1, -1);
Double[] vNorm = (Double[])swFace.Normal();
Debug.Print("vNorm: " + vNorm[0]);
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
I have one more question.
How can I convert this:
VBA:
`
Set swXform = swDocExt.GetCoordinateSystemTransformByName(sAxisName)
Debug.Print " Rotational sub-matrix 1 = (" & swXform.ArrayData(2) & ")"
`
C# (don't work)
`
swXform = swDocExt.GetCoordinateSystemTransformByName(sAxisName);
Debug.Print(" Rotational sub-matrix 1 = (" + swXform.ArrayData[2] + ") mm");
`
Change this line
Double[] vNorm = (Double[])swFace.Normal();
to
Double[] vNorm = (Double[])swFace.Normal;

Using a script task in SSIS with C# language, how to convert a DTS ActiveX script that creates files and then appends the full file names

I'm trying to convert a DTS process to SSIS and I want to convert a DTS script task that creates 3 files (only creates the file if there’s data to write to it) and then appends the full file names to a variable, which is then copied to a global variable. Since I'm new to this I would like a step by step demonstation if possible, Please, Please, Pretty Please help...Thanks. Below is an example of the DTS script that creates two instead of three files:
Function Main()
DIM dbConnection, rsGetFileDetails, rsGetInfo
DIM fsoFileSystem, fExportFile
DIM sGroupCode, sSequenceNumber, sFileIdentifier, FileName
DIM sLineItem, sAttachmentPaths
DIM FileLocation
sAttachmentPaths = ""
FileLocation = DTSGlobalVariables("FileDestPath").Value
'****************************************************
'*********Connect to Database******************
'****************************************************
SET dbConnection = CreateObject( "ADODB.Connection" )
dbConnection.Provider = "sqloledb"
dbConnection.Properties("Data Source").Value = "Server"
dbConnection.Properties("Initial Catalog").Value = "Database"
dbConnection.Properties("Integrated Security").Value = "1234"
dbConnection.Open
'*******************************************************************
'***********GET TRACE ALERT DELIST DATA************
'*******************************************************************
SET fsoFileSystem = CreateObject( "Scripting.FileSystemObject" )
SET rsGetInfo = CreateObject( "ADODB.recordset" )
sql = "SELECT tblExample1.IDNumber, tblExample2.First_Name, tblExample3.Main_Name FROM tblExample1 INNER JOIN tblExample2 ON tblExample1.IDNumber = tblExample2.Entity_ID_Number WHERE (tblExample1.IDNumber = '2') AND (Process_Date IS NULL)"
rsGetInfo.Open sql, dbConnection
IF rsGetInfo.EOF THEN
ELSE
FileName = "MyFileName_" & Replace( Date() , "/" , "")
'//Create the file
SET fExportFile = fsoFileSystem.CreateTextFile( FileLocation & FileName & ".txt", true )
DTSGlobalVariables("FileLocation").Value = FileLocation & FileName & ".txt"
rsGetInfo.MoveFirst
DO WHILE NOT rsGetInfo.EOF OR rsGetInfo.BOF
sLineItem = ""
sLineItem = rsGetInfo("IDNumber") & vbtab & rsGetDelistInfo("First_Name") & vbtab & rsGetInfo("Main_Name")
fExportFile.Write(sLineItem & vbcrlf)
rsGetInfo.MoveNext
LOOP
'// Set Attachment Path
sAttachmentPaths = FileLocation & FileName & ".txt"
END IF
'*******************************************************************
'***********GET DEFAULT DELIST DATA************
'*******************************************************************
SET fsoFileSystem = CreateObject( "Scripting.FileSystemObject" )
SET rsGetInfo = CreateObject( "ADODB.recordset" )
sql = "SELECT Contract_No FROM tblfunny WHERE (funnyNumb = 1) and (Process_Date IS NULL)"
rsGetInfo.Open sql, dbConnection
IF rsGetInfo.EOF THEN
ELSE
FileName = "MyFileName_" & Replace( Date() , "/" , "")
'//Create the file
SET fExportFile = fsoFileSystem.CreateTextFile( FileLocation & FileName & ".txt", true )
DTSGlobalVariables("FileLocation").Value = FileLocation & FileName & ".txt"
rsGetInfo.MoveFirst
DO WHILE NOT rsGetInfo.EOF OR rsGetInfo.BOF
sLineItem = ""
sLineItem = rsGetInfo("Contract_No")
fExportFile.Write(sLineItem & vbcrlf)
rsGetInfo.MoveNext
LOOP
'// Set Attachment Path
IF sAttachmentPaths = "" THEN
sAttachmentPaths = FileLocation & FileName & ".txt"
ELSE
sAttachmentPaths = sAttachmentPaths & "; "& FileLocation & FileName & ".txt"
END IF
END IF
Main = DTSTaskExecResult_Success
End Function

Why does DirectoryEntry("WinNT://") not show group everyone?

The below function (is supposed to) lists all groups on the local machine.
Now the question: Why does the "everyone" group not show up ?
If I change directory permissions as user, I see the "everyone" group, so it must be there, somewhere.
Public Shared Function GetAllGroups() As DataTable
Return GetAllGroups(System.Environment.MachineName)
End Function
' Tools.Permissions.Local.GetAllGroups() '
Public Shared Function GetAllGroups(ByVal strDomain As String) As DataTable
Dim dt As New DataTable
Dim dr As DataRow = Nothing
Try
Dim bException As Boolean = False
Dim deLocalMachine As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry("WinNT://" + strDomain)
'Dim deRootObject As System.DirectoryServices.DirectoryEntry = GetDirectoryEntry(strPath, strUserName, strPassword, bException) '
If bException Then
Return Nothing
End If
For Each child As System.DirectoryServices.DirectoryEntry In deLocalMachine.Children
Try
If StringComparer.OrdinalIgnoreCase.Equals(child.SchemaClassName, "group") Then
If Not dt.Columns.Contains("Members") Then
dt.Columns.Add("Members", GetType(System.String))
End If
For Each strPropertyName As String In child.Properties.PropertyNames
If Not dt.Columns.Contains(strPropertyName) Then
dt.Columns.Add(strPropertyName, GetType(System.String))
End If
Next strPropertyName
dr = dt.NewRow
Dim strMembers As String = ""
For Each member As Object In DirectCast(child.Invoke("Members"), IEnumerable)
Using memberEntry As New System.DirectoryServices.DirectoryEntry(member)
Try
strMembers += memberEntry.Properties("Name").Value.ToString() + Environment.NewLine
Console.WriteLine(memberEntry.Path)
Catch exFixMeIsNotNullNotWorking As Exception
End Try
End Using
Next
dr("Members") = strMembers
For Each strPropertyName As String In child.Properties.PropertyNames
If StringComparer.OrdinalIgnoreCase.Equals(strPropertyName, "objectSid") Then
Dim strSID As String = ""
Try
Dim sidThisSid As New System.Security.Principal.SecurityIdentifier(child.Properties(strPropertyName).Value, 0)
strSID = sidThisSid.ToString()
' http://stackoverflow.com/questions/1040623/convert-a-username-to-a-sid-string-in-c-net '
' NTAccount ntAccount = (NTAccount)sid.Translate( typeof( NTAccount ) ); '
' Dim ntAccount As Security.Principal.NTAccount = CType(sidThisSid.Translate(GetType(Security.Principal.NTAccount)), Security.Principal.NTAccount) '
Catch ex As Exception
End Try
dr(strPropertyName) = strSID
Else
dr(strPropertyName) = child.Properties(strPropertyName).Value.ToString()
End If
Next strPropertyName
dt.Rows.Add(dr)
End If
Catch ex As Exception ' Don't finish just because one fails
Console.WriteLine(ex.Message.ToString & vbLf & vbLf & ex.StackTrace.ToString, MsgBoxStyle.Critical, "FEHLER ...")
End Try
Next
Catch ex As Exception
Console.WriteLine(ex.Message.ToString & vbLf & vbLf & ex.StackTrace.ToString, MsgBoxStyle.Critical, "FEHLER ...")
End Try
Return dt
End Function ' ListEverything
The Everyone group isn't a standard group but rather an implicit group or built-in principal. If you open your local "Users and Groups" you won't see it listed there either. The same is true of other "groups" such as Authenticated Users. If you want to access these you need to use the System.Security.Principal.WellKnownSidType enumeration. This Windows 2008 article is really relevant for older versions of Windows, too.

Categories