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;
Related
hi firends i have started with sap b1 i created my own add-on sap using c# in visual studio 2010 my form will sent a value to my crystal report directly without showing previou any one can help my version sap is 9.2
i tried this code but it doesn't work
//add crystalreport to my add-on
SAPbobsCOM.ReportTypesService rptTypeService = (SAPbobsCOM.ReportTypesService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService);
SAPbobsCOM.ReportType newType = (SAPbobsCOM.ReportType)
rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType);
newType.TypeName = "CodeBarre_etat";
newType.AddonName = "PRINT_CODEBARRE";
newType.AddonFormType = "PRINT_CODEBARRE";
newType.MenuID = "PRINT_CODEBARRE";
SAPbobsCOM.ReportTypeParams newTypeParam = rptTypeService.AddReportType(newType);
//add layout to my report
SAPbobsCOM.ReportLayoutsService rptService = (SAPbobsCOM.ReportLayoutsService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService);
SAPbobsCOM.ReportLayout newReport = (SAPbobsCOM.ReportLayout)
rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout);
newReport.Author = Menu.company.UserName;
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal;
newReport.Name = "PRINT_CODEBARREL";
newReport.TypeCode = newTypeParam.TypeCode;
SAPbobsCOM.ReportLayoutParams newReportParam = rptService.AddReportLayout(newReport);
// Set the report layout into the report type.
newType = rptTypeService.GetReportType(newTypeParam);
newType.DefaultReportLayout = newReportParam.LayoutCode;
rptTypeService.UpdateReportType(newType);
SAPbobsCOM.BlobParams oBlobParams = (SAPbobsCOM.BlobParams)
Menu. company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams);
oBlobParams.Table = "OITM";
oBlobParams.Field = "Template";
SAPbobsCOM.BlobTableKeySegment oKeySegment = oBlobParams.BlobTableKeySegments.Add();
oKeySegment.Name = "ItemCode";
oKeySegment.Value = newReportParam.LayoutCode;
FileStream oFile = new FileStream("CodeBarre_etat.rpt", System.IO.FileMode.Open);
int fileSize = (int)oFile.Length;
byte[] buf = new byte[fileSize];
oFile.Read(buf, 0, fileSize);
oFile.Dispose();
//SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)
//Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob);
SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)(Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob));
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize);
Menu.company.GetCompanyService().SetBlob(oBlobParams, oBlob);
Not sure what the issue might be with your code, but below is a working implementation of what you're trying to do (albeit in VB, not in C#, but translating it should be fairly trivial).
Here's a sample call:
setCrystalReport(REPORT_TITLE_SUMMARY, My.Settings.ReportsPath.TrimEnd("\") & "\" & "comm_report_summary.rpt", _
oForm, "myFormTypeID", "My Add-On Name", "MENU_ID_VALUE")
Function:
'Returns new CR TypeCode
Private Function setCrystalReport(ByVal rptName As String, ByVal rptPath As String, ByRef oForm As SAPbouiCOM.Form, ByVal formType As String, _
ByVal addOnName As String, ByVal menuID As String) As String
Try
'1. Ad a new report type => ReportTypesService (8.81+ only)
Dim rptTypeService As SAPbobsCOM.ReportTypesService
Dim newType As SAPbobsCOM.ReportType
rptTypeService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService)
newType = rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType)
newType.TypeName = rptName
newType.AddonName = addOnName
newType.AddonFormType = formType
newType.MenuID = menuID
Dim newTypeParam As SAPbobsCOM.ReportTypeParams
newTypeParam = rptTypeService.AddReportType(newType)
'2. Add a new report layout => ReportLayoutService
Dim rptService As SAPbobsCOM.ReportLayoutsService
Dim newReport As SAPbobsCOM.ReportLayout
rptService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService)
newReport = rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout)
newReport.Author = SBO_Company.UserName
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal
newReport.Name = rptName
newReport.TypeCode = newTypeParam.TypeCode
Dim newReportParam As SAPbobsCOM.ReportLayoutParams
newReportParam = rptService.AddReportLayout(newReport)
'3. Set the report layout into the report type
newType = rptTypeService.GetReportType(newTypeParam)
newType.DefaultReportLayout = newReportParam.LayoutCode
rptTypeService.UpdateReportType(newType)
'4. Link the Report layout code to the Crystal Report file
Dim oBlobParams As SAPbobsCOM.BlobParams
Dim oKeySegment As SAPbobsCOM.BlobTableKeySegment
oBlobParams = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams)
oBlobParams.Table = "RDOC"
oBlobParams.Field = "Template"
oKeySegment = oBlobParams.BlobTableKeySegments.Add()
oKeySegment.Name = "DocCode"
oKeySegment.Value = newReportParam.LayoutCode
Dim oFile As New FileStream(rptPath, System.IO.FileMode.Open)
Dim fileSize As Integer
fileSize = oFile.Length
Dim buf(fileSize) As Byte
oFile.Read(buf, 0, fileSize)
oFile.Dispose()
Dim oBlob As SAPbobsCOM.Blob
oBlob = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob)
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize)
SBO_Company.GetCompanyService().SetBlob(oBlobParams, oBlob)
'5. Link the new report type to your form
Return newType.TypeCode
Catch ex As Exception
Dim exString As String = ""
exString = "Exception caught in setCrystalReport Method. Details: " & ex.Message
If Not ex.InnerException Is Nothing Then
exString += " Inner Exception: " + ex.InnerException.Message
End If
SBO_Application.StatusBar.SetText(exString, SAPbouiCOM.BoMessageTime.bmt_Medium, _
SAPbouiCOM.BoStatusBarMessageType.smt_Error)
Return "-1"
End Try
End Function
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)))))"
I need to verify that a provided username is a Domain Administrator in c#.
Any idea's on how to do this?
You can use WindowsIdentity to get the current user.
Then create a WindowsPrincipal with the WindowsIdentity.
And check WindowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator)
Hope this can help you.
EDIT : I just see the ASP tag now... This link could help you, same thing but for ASP.
Function ADUserInfo(sLogonUser, cOption)
Dim oConnection
Dim oCommand
Dim oRoot
Dim oDomain
Dim sADsPath
Dim sDomain
sDomain = Mid(sLogonUser, 1, Instr(1, sLogonUser, "\") - 1)
Set oConnection = CreateObject("ADODB.Connection")
With oConnection
.Provider = "ADsDSOObject"
.Mode = "1" 'Read
.Properties("Encrypt Password") = True
.Open "Active Directory Provider"
End With
Set oCommand = CreateObject("ADODB.Command")
oCommand.ActiveConnection = oConnection
Set oRoot = GetObject("LDAP://" & sDomain & "/rootdse")
Set oDomain = GetObject("LDAP://" & sDomain & "/" & oRoot.Get("defaultNamingContext"))
sADsPath = "<" & oDomain.ADsPath & ">"
Select Case lcase(cOption)
Case "groups"
ADUserInfo = ADUserGroups(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Case "name"
ADUserInfo = ADUserName(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Case "supervisor"
End Select
End Function
Function ADUserGroups(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Dim sFilter
Dim sAttribsToReturn
Dim sDepth
Dim sDomainSID
Dim vObjectSID
Dim sObjectSID
Dim sGroupRID
Dim iPrimaryGroupID
Dim oPrimaryGroup
Dim oRS
Dim value
Dim cGroups
Dim sDomain
Dim sLogonName
sDomain = Mid(sLogonUser, 1, Instr(1, sLogonUser, "\") - 1)
sLogonName = Mid(sLogonUser, Instr(1, sLogonUser, "\") + 1)
sFilter = "(&(objectCategory=Person)(objectClass=user)(sAMAccountName=" & sLogonName & "))"
sAttribsToReturn = "memberOf,primaryGroupID,objectSID"
sDepth = "subTree"
ocommand.CommandText = sADsPath & ";" & sFilter & ";" & sAttribsToReturn & ";" & sDepth
Set oRS = ocommand.Execute
' Only one user should meet the criteria
If (oRS.RecordCount = 1) Then
' Get that user's info
For i = 0 To oRS.Fields.Count - 1
If (oRS.Fields(i).Name = "memberOf") Then
' I've never seen this field come back with more than
' ONE value, but the original code I started with
' treated the memberOf property as though it was a
' collection. So, I've left it a collection until
' I can verify it. KLW
cGroups = ""
For Each value In oRS.Fields(i).Value
cGroups = cGroups & replace(split(value,",")(0),"CN=","") & ";"
Next
ElseIf (oRS.Fields(i).Name = "primaryGroupID") Then
' need this to get the PrimaryGroup after other group membership has been obtained
' (Primary Group ID and Object SID ID needed to get the primary group)
iPrimaryGroupID = oRS.Fields(i).Value
ElseIf (oRS.Fields(i).Name = "objectSID") Then
' adVarBinary -- need this to get the PrimaryGroup.
' It is not included in the memberOf group list
vObjectSID = oRS.Fields(i).Value
sObjectSID = SDDL_SID(vObjectSID)
End If
Next
' The primary group is not included in memberOf...
' We have the SDDL form of the user's SID.
' Remove the user's RID ( the last sub authority)
' up to the "-"
'
sDomainSID = Mid(sObjectSID, 1, (InStrREV(sObjectSID,"-")))
' Build the SID of the Primary group
' from the domainSID and the Primary Group RID in
' the PrimaryGroupID.
'
sGroupRID = StrRID(iPrimaryGroupID)
sDomainSID = sDomainSID & sGroupRID
' Get the primary group
'
set oPrimaryGroup = GetObject("LDAP://" & sDomain & "/<SID=" & sDomainSID & ">")
cGroups = replace(split(oPrimaryGroup.Get("DistinguishedName"),",")(0),"CN=","") & ";" & cGroups
ADUserGroups = cGroups
End If
End Function
Function ADUserName(sLogonUser, oConnection, oCommand, oRoot, oDomain, sADsPath)
Dim sFilter
Dim sAttribsToReturn
Dim sDepth
Dim sDomainSID
Dim vObjectSID
Dim sObjectSID
Dim sGroupRID
Dim iPrimaryGroupID
Dim oPrimaryGroup
Dim oRS
Dim value
Dim sDomain
Dim sLogonName
sDomain = Mid(sLogonUser, 1, Instr(1, sLogonUser, "\") - 1)
sLogonName = Mid(sLogonUser, Instr(1, sLogonUser, "\") + 1)
sFilter = "(&(objectCategory=Person)(objectClass=user)(sAMAccountName=" & sLogonName & "))"
sAttribsToReturn = "distinguishedName"
sDepth = "subTree"
ocommand.CommandText = sADsPath & ";" & sFilter & ";" & sAttribsToReturn & ";" & sDepth
Set oRS = ocommand.Execute
' Only one user should meet the criteria
If (oRS.RecordCount = 1) Then
' Get that user's info
For i = 0 To oRS.Fields.Count - 1
If (oRS.Fields(i).Name = "distinguishedName") Then
ADUserName = replace(split(oRS.Fields(i).Value,",")(0),"CN=","")
End If
Next
End If
End Function
function SDDL_SID ( oSID )
dim IssueAuthorities(11)
Dim SubAuthorities
Dim strSDDL
Dim IssueIndex
Dim Revision
Dim i, j, k, index, p2, subtotal, dblSubAuth
IssueAuthorities(0) = "-0-0"
IssueAuthorities(1) = "-1-0"
IssueAuthorities(2) = "-2-0"
IssueAuthorities(3) = "-3-0"
IssueAuthorities(4) = "-4"
IssueAuthorities(5) = "-5"
IssueAuthorities(6) = "-?"
IssueAuthorities(7) = "-?"
IssueAuthorities(8) = "-?"
IssueAuthorities(9) = "-?"
' First byte is the revision value
'
Revision = ascb(midB(osid,1,1))
' Second byte is the number of sub authorities in the
' SID
'
SubAuthorities = CInt(ascb(midb(oSID,2,1)))
strSDDL = "S-" & Revision
IssueIndex = CInt(ascb(midb(oSID,8,1)))
strSDDL = strSDDL & IssueAuthorities(IssueIndex)
index = 9
i = index
for k = 1 to SubAuthorities
p2 = 0
subtotal = 0
for j = 1 to 4
dblSubAuth = CDbl(ascb(midb(osid,i,1))) * (2^p2)
subTotal = subTotal + dblSubAuth
p2 = p2 + 8
i = i + 1
next
' Convert the value to a string, add it to the SDDL Sid and continue
'
strSDDL = strSDDL & "-" & cstr(subTotal)
next
SDDL_SID = strSDDL
end function
function Get_HexString( oSID )
Dim outStr, i, b
outStr = ""
for i = 0 to Ubound(oSid)
b = hex(ascb(midb(oSid,i+1,1)))
if( len(b) = 1 ) then b = "0" & b
outStr = outStr & b
next
Get_HexString = outStr
end function
function StrRID( inVal )
dim dLocal
if( (inVal and &H80000000) <> 0 ) then
dLocal = CDbl((inval and &H7FFFFFFF))
dLocal = dLocal + 2^31
StrRID = cstr(dLocal)
else
StrRID = Cstr(inVal)
end if
end function
I have an excel template file saved in web server folder.
During the run time I am giving the data source using the variable(dunsno) and date
but it throws an error:
Format of the initialization string does not conform to specification starting at index 3.
I just want to know how to write the connection string in the server side
I have done this:
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='Server.MapPath(~/Profile/ + "Tempfile" + dunsno + DateTime.Today.ToString("dd.MM.yyyy") + ".xls");Extended Properties=Excel 8.0;";
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("~/temp/"));
var fileList = directoryInfo.GetFiles();
string newFileName = Server.MapPath("~/Profile/" + "Tempfile" + dunsno + DateTime.Today.ToString("dd.MM.yyyy") + ".xls");
foreach (FileInfo fleInfo in fileList)
{
fleInfo.CopyTo(newFileName, true);
}
OleDbConnection MyConnection;
OleDbCommand MyCommand = new OleDbCommand();
MyConnection = new OleDbConnection(connStr);
MyConnection.Open();
MyCommand.Connection = MyConnection;
string sql = "Insert into [Sheet1$] (id,name) values('3','c')";
MyCommand.CommandText = sql;
MyCommand.ExecuteNonQuery();
MyConnection.Close();
}
Some more VBA point to have this clarity :
Sub GrabLastNames()
'dimension (set aside memory for) our variables
Dim objIE As InternetExplorer
Dim ele As HTMLLinkElement
Dim e As HTMLLinkElement
Dim h As HTMLLinkElement
Dim t As HTMLTable
Dim s As String
Dim x, y, z
Dim c As Integer
Dim post As Object, Elem As Object
Set objIE = New InternetExplorer
objIE.Visible = True
i = 0
objIE.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=ALB&commit=OK"
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
Set post = objIE.Document.getElementById("countrycriteria_country")
For Each Elem In post.getElementsByTagName("option")
c = c + 1
If c = 6 Then Exit For
Elem.Selected = True
objIE.Document.getElementById("countrycriteria_country").Focus
objIE.Document.getElementById("countrycriteria_country").FireEvent ("onchange")
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
For Each ele In objIE.Document.getElementsByTagName("table") '.getElementById("myTable").getElementsByTagName("tr")
s = LCase(Trim(ele.innerText))
If InStr(s, "immunization schedule") Or InStr(s, "percentage target population vaccinated by antigen") Then
For Each e In ele.Rows
i = i + 1
j = 3
' Sheet1.Cells(i, 1).Value = Elem.Value
For Each h In e.Cells
j = j + 1
Sheet1.Cells(i, j).Value = h.innerText
Next h
Next e
End If
Next ele
Next Elem
ActiveWorkbook.Save
End Sub
Sub Select_Item()
Dim post As Object, Elem As Object
With CreateObject("InternetExplorer.Application")
.Visible = True
.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=ALB&commit=OK" ''stored the html elements within "element.html" file to test it locally
While .Busy = True Or .ReadyState < 4: DoEvents: Wend
Set post = .Document.getElementById("countrycriteria_country")
For Each Elem In post.getElementsByTagName("option")
If Elem.Value = "BHS" Then Elem.Selected = True: Exit For
' i = i + 1
' If i = 4 Then Exit For
Next Elem
Application.Wait (Now + TimeValue("0:00:02"))
.Document.getElementById("countrycriteria_country").Focus
Application.Wait (Now + TimeValue("0:00:02"))
'.Document.getElementById("countrycriteria_country").Change
.Document.getElementById("countrycriteria_country").FireEvent ("onchange")
End With
End Sub
' Loop vba========
' Elem.Selected = True
' objIE.Document.getElementById("countrycriteria_country").Focus
' objIE.Document.getElementById("countrycriteria_country").FireEvent ("onchange")
' Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
Sub getCoverage()
Application.ScreenUpdating = False
Sheet1.Cells.Clear
'dimension (set aside memory for) our variables
Dim objIE As InternetExplorer
Dim ele As HTMLLinkElement
Dim e As HTMLLinkElement
Dim h As HTMLLinkElement
Dim t As HTMLTable
Dim s As String
Dim x, y, z
Dim con(1000)
Dim c As Integer
Dim post As Object, Elem As Object
Dim s1 As String, s2 As String, s3 As String, s4 As String
Set objIE = New InternetExplorer
objIE.Visible = True
' Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
s1 = LCase(shtweb.Range("d5").Value)
s2 = LCase(shtweb.Range("e5").Value)
s3 = LCase(shtweb.Range("f5").Value)
s4 = LCase(shtweb.Range("g5").Value)
s2 = IIf(s2 = "", "fsdfswew", s2)
s3 = IIf(s3 = "", "fsdfswew", s3)
s4 = IIf(s4 = "", "fsdfswew", s4)
i = 0
objIE.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=ALB&commit=OK"
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
Set post = objIE.Document.getElementById("countrycriteria_country")
For Each Elem In post.getElementsByTagName("option")
con(c) = Elem.Value
c = c + 1
Next Elem
'objIE.
For k = 0 To c
If con(k) = "" Then Exit For
objIE.Navigate "http://apps.who.int/immunization_monitoring/globalsummary/countries?countrycriteria%5Bcountry%5D%5B%5D=" & con(k) & "&commit=OK"
Do While objIE.Busy = True Or objIE.ReadyState <> 4: DoEvents: Loop
For Each ele In objIE.Document.getElementsByTagName("table") '.getElementById("myTable").getElementsByTagName("tr")
s = LCase(Trim(ele.innerText))
If InStr(s, s1) Or InStr(s, s2) Or InStr(s, s3) Or InStr(s, s4) Then
For Each e In ele.Rows
i = i + 1
j = 3
Sheet1.Cells(i, 1).Value = con(k)
For Each h In e.Cells
j = j + 1
If Left(h.innerText, 1) = "=" Then
Sheet1.Cells(i, j).Value = "'" & h.innerText
Else
Sheet1.Cells(i, j).Value = h.innerText
End If
Next h
Next e
End If
Next ele
Next k
ActiveWorkbook.Save
Application.ScreenUpdating = True
End Sub
use Path.Combine and a OleDbConnectionStringBuilder to create a valid connection-string:
var conString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}"
, Path.Combine(dir, "nik.mdb"));
var conBuilder = new OleDbConnectionStringBuilder(conString);
using (var con = new OleDbConnection(conBuilder.ConnectionString))
{
// ...
}
Maybe you have white-spaces in the connection string.
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;
}
}