I need to set up live connection between Catia and Matlab so I can send parameters values to my parametric design in Catia and read some other parameters and measures.
This is my sollution:
First I create:
VB NET (*.dll)
Public Class CatiaLinkLibrary
Dim CATIA As Object
Dim rootproduct
Sub StartCatia()
CATIA = CreateObject("CATIA.Application")
End Sub
Sub CloseCatia()
CATIA.Quit()
End Sub
Sub Visible(ByRef mode As Integer)
If mode = 1 Or mode = 0 Then
CATIA.Visible = mode
End If
End Sub
Sub OpenFile(ByRef filename As String)
CATIA.Documents.Open(filename)
rootproduct = CATIA.ActiveDocument.Product()
End Sub
Function GetMass() As Double
Return rootproduct.Analyze.Mass()
End Function
Function GetVolume() As Double
Return rootproduct.Analyze.Volume()
End Function
Function GetArea() As Double
Return rootproduct.Analyze.WetArea()
End Function
Function GetGravityCenter()
Dim gravitycenter(2)
rootproduct.Analyze.GetGravityCenter(gravitycenter)
GetGravityCenter = gravitycenter
End Function
Function GetIntertia()
Dim inertia(8)
rootproduct.Analyze.GetInertia(inertia)
GetIntertia = inertia
End Function
Sub ChangeParameter(ByRef parameterName As String, ByRef Value As Double)
Dim pd As Object
Dim part As Object
Dim parameters As Object
Dim length As Object
pd = CATIA.ActiveDocument
part = pd.Part
parameters = part.Parameters
length = parameters.Item(parameterName)
length.Value = Value
part.Update()
End Sub
Function GetParameter(ByRef parameterName As String) As Double
Dim pd As Object
Dim part As Object
Dim parameters As Object
Dim length As Object
pd = CATIA.ActiveDocument
part = pd.Part
parameters = part.Parameters
length = parameters.Item(parameterName)
Return length.Value()
End Function
Sub closeDoc(ByRef name As String)
Dim windows As Object
Dim window As Object
Dim doc As Object
windows = CATIA.Windows
window = windows.Item(name)
window.Activate()
window.Close()
doc = CATIA.ActiveDocument
doc.Close()
End Sub
Sub activeDoc(ByRef name As String)
Dim windows As Object
Dim window As Object
Dim doc As Object
windows = CATIA.Windows
window = windows.Item(name)
window.Activate()
doc = CATIA.ActiveDocument
End Sub
Function GetArea2() As Double
Dim pd As Object
Dim part As Object
Dim bodys As Object
Dim body As Object
Dim spabench As Object
Dim mymeas As Object
pd = CATIA.ActiveDocument
part = pd.Part
bodys = part.Bodies
body = bodys.Item("PartBody")
spabench = pd.GetWorkbench("SPAWorkbench")
mymeas = spabench.GetMeasurable(body)
Return mymeas.Area
End Function
End Class
Then, in Matlab I have class that wraps around this *dll:
Matlab class:
classdef CatiaLink < handle
properties
catia;
end
methods
function obj = CatiaLink()
%modify this path to your .NET DLL
NET.addAssembly('C:\DOKTORAT\Modele Geometryczne\CatiaLinkLibrary\CatiaLinkLibrary\bin\Debug\CatiaLinkLibrary.dll');
obj.catia = CatiaLinkLibrary.CatiaLinkLibrary;
obj.catia.StartCatia;
disp('Catia started')
end
function Visible(obj,mode)
obj.catia.Visible(mode);
end
function Quit(obj)
obj.catia.CloseCatia;
end
function Open(obj,filename)
obj.catia.OpenFile(filename);
end
function mass = GetMass(obj)
mass = obj.catia.GetMass;
end
function vol = GetVolume(obj)
vol = obj.catia.GetVolume;
end
function area = GetArea(obj)
area = obj.catia.GetArea;
end
function cog = GetCenterOfGravity(obj)
tmp = obj.catia.GetGravityCenter;
cog = [tmp(1),tmp(2),tmp(3)];
end
function inertia = GetInertia(obj)
tmp = obj.catia.GetIntertia;
inertia = [tmp(1), tmp(2), tmp(3); ...
tmp(4), tmp(5), tmp(6); ...
tmp(7), tmp(8), tmp(9)];
end
function setParameter(obj, parameterName, Value)
obj.catia.ChangeParameter(parameterName, Value);
end
function val = getParameter(obj, parameterName)
val = obj.catia.GetParameter(parameterName);
end
function closeDoc(obj, name)
obj.catia.closeDoc(name);
end
function activeDoc(obj, name)
obj.catia.activeDoc(name);
end
function area = getArea2(obj)
area = obj.catia.GetArea2;
end
end
end
So in my program I create Catia object by Catia = CatiaLink.
And than I use it like 10000 or even more times to set and get parameters.
Everything works just fine up to around couple thousand times and than I get error:
Error using CatiaLink/setParameter (line 42)
Message: No more threads can be created in the system. (Exception from
HRESULT: 0x800700A4)
Source: mscorlib
HelpLink:
Can someone explain what is happening? And how to prevent this?
It looks like you're never calling Catia.Quit()
Related
I'm assigning a value to a variable, where that value is either a number or an object instance depending on the result of a server request, as follows:
Sub assignVar()
Dim v As Variant
v = getValue
End Sub
Function getValue() As Variant
Dim result As Boolean
result = PostSomethingToServer()
If result Then
getValue = 1
Else
Set getValue = New Dictionary
getValue.Add "a", 1
End If
End Function
This works fine if I call assignVar(true), but if I call assignVar(false) then I get the error:
Wrong number of arguments or invalid property assignment
which is to be expected, because if getValue() returns an object, it should be assigned as set v = getValue. But if I write it this way, then I get a Type mismatch error because I'm trying to assign an integer using a Set statement.
How can I make sure that v gets assigned correctly for either return value of getValue()?
For now I'm resolving this by adding a ReturnValue class:
Option Explicit
Public value As Variant
Public valueIsObject As Boolean
Public Sub setup(value As Variant)
If IsObject(value) Then
Set Me.value = value
valueIsObject = True
Else
Me.value = value
valueIsObject = False
End If
End Sub
This way, I can rewrite the test methods as follows:
Sub assignVar()
Dim v As Variant
Dim rv as ReturnValue
Set rv = getValue
If rv.valueIsObject Then
Set v = rv.value
Else
v = rv.value
End If
End Sub
Function getValue() As ReturnValue
Dim result As Boolean
Dim dict as Dictionary
result = PostSomethingToServer()
set getValue=new ReturnValue
If result Then
getValue.setup 1
Else
Set dict = New Dictionary
dict.Add "a", 1
getValue.setup dict
End If
End Function
I would like to dynamically add a usercontrol to a form in VB.Net. I will be pulling the UserControl name (String) from a database and if that UserControl exists in the project I would like it to be added to the form.
I know how to programmatically add usercontrols to a form, but I am not sure how when using a string for the name.
Dim userContName As UserControl = dtModules.Rows(k).Item("uc_Name")
Panel1.Controls.Add(userContName)
I attempted this soultion
Public Sub LoadGroups()
dtModules = Tbl_GroupModulesTableAdapter1.GetDataBy_spGetModuleByGroup(grp.Name)
For k = 0 To dtModules.Rows.Count - 1
If grp.Name = dtModules.Rows(k).Item("Module_Group") Then
Dim fullyQualifiedClassName As String = dtModules.Rows(k).Item("Module_Name")
If fullyQualifiedClassName = Nothing Then
Else
Dim o = fetchInstance(fullyQualifiedClassName)
Dim b = CType(o, Control)
grp.Controls.Add(b)
End If
End If
Next
End Sub
Public Function fetchInstance(ByVal fullyQualifiedClassName As String) As Object
Dim nspc As String = fullyQualifiedClassName.Substring(0, fullyQualifiedClassName.LastIndexOf("."c))
Dim o As Object = Nothing
Try
For Each ay In Assembly.GetExecutingAssembly().GetReferencedAssemblies()
If (ay.Name = nspc) Then
o = Assembly.Load(ay).CreateInstance(fullyQualifiedClassName)
Exit For
End If
Next
Catch
End Try
Return o
End Function
Ok got it to work with this;
Dim ucName As String = Projectname.UserControlName
Dim newType As Type = Type.[GetType](ucName, True, True)
Dim o As Object = Activator.CreateInstance(newType)
Form.Controls.Add(o)
Once I got this it was pretty simple! thanks for the feedback!
I'm trying to access data from collection by using .item(). What I am trying to do is to collect data in collection function fncPopCcyLst and access it by .item(1) in cbSortCcy to get the row number. This is a test to see if I can store several data in my collection and access them via .item(). However, I get a VBA runtime error '5'. Will someone guide me kindly what I am doing wrong? Thank you.
Below are my codes.
Class Module: clsSngGenUtl
Private prpSngStrVal As String
Private prpSngRowNum As Long
Private prpSngClmNum As Long
'++ Define properties
'== String row number
Public Property Get SngStrVal() As String
SngStrVal = prpSngStrVal
End Property
Public Property Let SngStrVal(ByRef varStrVal As String)
prpSngStrVal = varStrVal
End Property
'++ Define properties
'== Scalar row number
Public Property Get SngRowNum() As Long
SngRowNum = prpSngRowNum
End Property
Public Property Let SngRowNum(ByVal varRowNum As Long)
prpSngRowNum = varRowNum
End Property
'++ Define properties
'== Single column number
Public Property Get SngClmNum() As Long
SngClmNum = prpSngClmNum
End Property
Public Property Let SngClmNum(ByRef varClmNum As Long)
prpSngClmNum = varClmNum
End Property
'++ Define functions
'== function get row number
Public Function fncGetRowNum(ByRef varWbName As Workbook, ByVal varWsName As String, ByRef varSttClm As Long) As Long
On Error GoTo Exception
prpSngRowNum = 0
prpSngRowNum = varWbName.Sheets(Trim(varWsName)).Cells(Rows.Count, varSttClm).End(xlUp).Row
fncGetRowNum = prpSngRowNum
ExitHere:
Exit Function
Exception:
Resume ExitHere
End Function
'== function get column number
Public Function fncGetClmNum(ByRef varWbName As Workbook, ByVal varWsName As String, ByRef varSttRow As Long) As Long
On Error GoTo Exception
prpSngClmNum = 0
prpSngClmNum = varWbName.Sheets(Trim(varWsName)).Cells(varSttRow, Columns.Count).End(xlToLeft).Column
fncGetClmNum = prpSngClmNum
ExitHere:
Exit Function
Exception:
Resume ExitHere
End Function`
Below is my collection class: clsColCcySrt
'++ Declare variables
Private prpColCcySrt As Collection
'++ Define properties
Public Property Get ColCcySrt() As Collection
Set ColCcySrt = prpColCcySrt
End Property
Public Property Set ColCcySrt(varColCcy As Collection)
Set prpColCcySrt = varColCcy
End Property
Public Function fncGetCcyRow(ByRef varStrVal As String) As Long
On Error GoTo Exception
Dim clsSngGen As clsSngGenUtl
Dim varRowNum As Long
varRowNum = 0
For Each clsSngGen In Me.ColCcySrt
varRowNum = clsSngGen.SngRowNum()
Next clsSngGen
'== Return value
fncGetCcyRow = varRowNum
ExitHere:
Exit Function
Exception:
If fncGetCcyRow = 0 Then
MsgBox "Exception: Value is <" & fncGetCcyRow & ">."
End If
Resume ExitHere
End Function
`
"Regular" Module to populate array: fncPopFxLst
`
Public Function fncPopCcyLst(ByRef varWbName As String, ByRef varWsName As String, ByRef varCcyTyp As String) As Collection
Dim clnColCcy As Collection
Dim clsArrGen As clsArrGenUtl
Dim clsSngGen As clsSngGenUtl
Dim varWbName As Workbook
Set clnColCcy = New Collection
'== Start collecting items
Set clsSngGen = New clsSngGenUtl
Set varWbName = ThisWorkbook
clsSngGen.SngStrVal = "Reuters"
clsSngGen.SngRowNum = clsSngGen.fncGetRowNum(varWbName, varWsName, 1)
clnColCcy.Add clsSngGen
Set fncPopCcyLst = clnColCcy
End Function
`
Lastly, the subroutine `
Private Sub cbSortCcy()
Dim clsColCcy As clsColCcySrt
Dim varDirPth As String
Dim varCcySrc As String
Dim varWsStrg As String
Dim varWbStrg As String
varDirPth = tbDirectoryName & "\" & tbFileName
varCcySrc = "Currency"
varWsStrg = "List"
varWbStrg = varDirPth
Set clsColCcy = New clsColCcySrt
Set clsColCcy.ColCcySrt = fncPopCcyLst(varWbStrg, varWsStrg, varCcySrc)
'Debug.Princ clsColCcy.fncGetCcyRow("Reuters")
Debug.Print clsColCcy.ColCcySrt.Item(1)
End Sub
`
VBA Run-time error '5' is:
"Invalid procedure call or argument"
In your class clsColCcySrt, you have a line:
varRowNum = clsSngGen.SngRowNum()
which would be correct if SngRowNum were a function and not a property. Remove the parentheses () to call the property.
I've seen some questions similar to this on here, but none of them seem to help me. I don't really care what API is used, be it Google, Yahoo!, The Weather Channel, or any other. I've got code that will get the high and low of the current day, based on the location given by the user, but I can't seem to get the hourly predictions for temperature or weather condition, which is what I'm really looking for. I don't really care for wind speeds, humidity, or the "feels like" temperature, though I'll add them if I can figure out how to. I'm trying to get data that will look something like what is here. (www.weather.com/...)
I'm pretty new to parsing XML so that may be part of my problem, too. Thanks in advance for any help. I greatly appreciate it.
I have something you might enjoy:
<Runtime.CompilerServices.Extension()>
Module Weather
Public Structure WeatherInfo_Forecast
Dim DayOfWeek As String
Dim low As Double
Dim high As Double
Dim icon As String
End Structure
Public Structure WeatherInfo_Wind
Dim direction As String
Dim speed As Double
Dim unit As String
End Structure
Public Structure WeatherInfo_Typed
Dim Failed As Boolean
Dim errormessage As Exception
Dim location As String
Dim forcast_date As DateTime
Dim checked_time_date As DateTime
Dim humidity As Double
Dim highf As Double
Dim lowf As Double
Dim highc As Double
Dim lowc As Double
Dim currenttempC As Double
Dim currenttempF As Double
Dim predicted_icon As String
Dim current_icon As String
Dim current_condition As String
Dim predicted_condition As IEnumerable(Of WeatherInfo_Forecast)
Dim wind_condition As WeatherInfo_Wind
Dim day As String
End Structure
<Runtime.CompilerServices.Extension()> _
Public Function ToC(ByVal F As Double) As Double
Return ((F - 32) / 9) * 5
End Function
<Runtime.CompilerServices.Extension()> _
Public Function TryParseAsDouble(ByVal s As String) As Double
Dim rv As Double
If Double.TryParse(s, rv) = False Then rv = Double.NaN
Return rv
End Function
<Runtime.CompilerServices.Extension()> _
Public Function TryParseAsDate(ByVal s As String) As DateTime
Dim rv As DateTime
If DateTime.TryParse(s, rv) = False Then rv = Nothing
Return rv
End Function
Private Function ParseHumidity(ByVal s As String) As Double
If Not s Is Nothing Then
Dim humRegEx As New System.Text.RegularExpressions.Regex("Humidity: (?<Value>\d+)\w*\%")
Dim m = humRegEx.Match(s)
If m.Length = 0 Then Return Double.NaN
Return Double.Parse(m.Groups("Value").Value)
End If
End Function
Private Function ParseWind(ByVal s As String) As WeatherInfo_Wind
Dim rv As New WeatherInfo_Wind
If Not s Is Nothing Then
Dim humRegEx As New System.Text.RegularExpressions.Regex("Wind\:\s+(?<Direction>[NEWSnews]{1,2})\s+at\s+(?<speed>(?<value>\d+)\s(?<units>\w+)){1}")
Dim m = humRegEx.Match(s)
rv.speed = Double.NaN
If m.Length = 0 Then Return rv
With rv
.direction = m.Groups("Direction").Value
If Double.TryParse(m.Groups("value").Value, .speed) = False Then .speed = Double.NaN
.unit = m.Groups("units").Value
End With
End If
Return rv
End Function
<DebuggerHidden()>
Public Function Grab_Weather(ByVal Location As String) As WeatherInfo_Typed
Dim GrabWeather As New WeatherInfo_Typed
With GrabWeather
.Failed = True
Try
Dim xml As XDocument = XDocument.Load("http://www.google.com/ig/api?weather=" & Location)
Dim xp = xml.<problem_cause>
If xp.Any Then Return GrabWeather
.location = xml...<city>.#data
.forcast_date = xml...<forecast_date>.#data.TryParseAsDate
.checked_time_date = xml...<current_date_time>.#data.TryParseAsDate
.humidity = ParseHumidity(xml...<humidity>.#data)
.highf = xml...<high>.#data.TryParseAsDouble
.lowf = xml...<low>.#data.TryParseAsDouble
.highc = GrabWeather.highf.ToC
.lowc = GrabWeather.highc.ToC
.currenttempC = xml...<temp_c>.#data.TryParseAsDouble
.currenttempF = xml...<temp_f>.#data.TryParseAsDouble
'.current_icon = "http://www.google.com" & xml...<icon>.#data
'.predicted_icon = "http://www.google.com" & xml...<high>.#data
.current_condition = xml...<condition>.#data
.predicted_condition = From f In xml...<forecast_conditions> _
Select New WeatherInfo_Forecast With { _
.DayOfWeek = f.<day_of_week>.Value, _
.high = f.<high>.#data.TryParseAsDouble, _
.low = f.<low>.#data.TryParseAsDouble}
'.icon = "http://www.google.com" & f.<icon>.#data}
.wind_condition = ParseWind(xml...<wind_condition>.#data)
.day = xml...<day_of_week>.#data
.Failed = False
Return GrabWeather
Catch ex As Exception
.errormessage = ex
Return GrabWeather
End Try
End With
End Function
End Module
I finally found what I was looking for from Weather Underground. They have three APIs, and, starting with the middle one, gives hourly forecasts for 36 hours. You get English and Metric predicted statistics for temperature, "feels like" temperature, dew point, wind speed, and wind direction. There's also wind chill and heat index, but every result for both in English and Metric was -9998, so I'm pretty sure those results are a bit off! Also there are qpf, snow, pop, and mslp. Unfortunately qpf and snow have not results and I'm not sure what pop and mslp are. All results are available in JSON and XML. They have some image requests, too, but I haven't looked into them yet.
Update:
Link Updated
As you know we have a new syntax in vb.net with possibility to create inline tasks so we could run it asynchronously.
This is the correct code:
Dim testDeclaring As New Task(Sub()
End Sub)
testDeclaring.Start()
but now I need to pass a parameter in the subroutine and I can't find correct syntax for that.
Is it possible any way?
It's not possible. However, you could just use the parameters from the current scope:
Public Function SomeFunction()
Dim somevariable as Integer = 5
Dim testDeclaring As New Task(Sub()
Dim sum as integer = somevariable + 1 ' No problems here, sum will be 6
End Sub)
testDeclaring.Start()
End Function
If you want to pass a parameter you could do this
Dim someAction As Action(Of Object) = Sub(s As Object)
Debug.WriteLine(DirectCast(s, String))
End Sub
Dim testDeclaring As New Task(someAction, "tryme")
testDeclaring.Start()
Dont know if you looking for this:
Dim t As Task = New Task(Sub() RemoveBreakPages(doc))
Sub RemoveBreakPages(ByRef doc As Document)
Dim paragraphs As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)
For Each p In paragraphs
If CType(p, Paragraph).ParagraphFormat().PageBreakBefore() Then
CType(p, Paragraph).ParagraphFormat().PageBreakBefore = False
End If
Next
End Sub
Regards.