I am using below code to use autocad object.
Dim acadapp As AcadApplication
acadapp = GetObject(, "AutoCAD.Application")
'''and using below code to create object -------------
acadapp = CreateObject("AutoCAD.Application")
Getting error "Cannot create ActiveX component".
I tried using 18,19 and various combination as below :
acadapp = GetObject(, "AutoCAD.Application.18")
But nothing work.
Please help.
#Locke : Thanks for reply.I tried your soltion as below :
Dim acadType As Type
Try
acadapp =
System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.18.1")
''Above code din't worked so tried below code also
' acadapp = DirectCast(Marshal.GetActiveObject("AutoCAD.Application.18.1"),
'AcadApplication)
Catch ex As Exception
acadType = Type.GetTypeFromProgID("AutoCAD.Application")
acadapp = DirectCast(Activator.CreateInstance(acadType, True), AcadApplication)
End Try
Showing Exception :
Unable to cast COM object of type 'System.__ComObject' to interface type 'AutoCAD.AcadApplication'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{8E75D910-3D21-11D2-85C4-080009A0C626}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Here's what I typically use when dealing with AutoCAD interop. It checks for a running instance, and creates a new one if necessary:
private static AcadApplication GetAcadApp(string progId)
{
// Create the return application
AcadApplication returnApp = null;
try
{
// Try getting a running instance
returnApp = (AcadApplication)Marshal.GetActiveObject(progId);
}
catch (COMException)
{
try
{
// Try creating a new instance
Type acadType = Type.GetTypeFromProgID(progId);
returnApp = (AcadApplication)Activator.CreateInstance(acadType, true);
}
catch (COMException)
{
// Report failure
MessageBox.Show(string.Format("Cannot create object of type \"{0}\"", progId));
}
}
// Return the application
return returnApp;
}
An AcadApplication COM object can be set like this:
// Get/create an AutoCAD instance
var acadApp = getAcadApp("AutoCAD.Application.18");
Regardless of C# or VB.NET, using Marshal.GetActiveObject and Activator.CreateInstance are probably the better ways to approach this.
According to the exception, the problem is not the GetActiveObject() call, but that the returned object doesn't support the interface you're looking for. Most likely reason is that your code references a different version of AcadApplication than the one you're getting back from GetActiveObject(). Change your project to reference the COM library version for the returned AutoCAD instance, and it should work fine.
Related
I am testing using an existing System.Net.Mail.MailMessage with MimeKit's support for direct casting to a MimeMessage in addition to using MimeKit's DkimSigner and MailKit's Smtp client.
I am getting "The type initializer for 'MimeKit.ParserOptions' threw an exception." With a stack trace mentioning 'at MimeKit.MimeMessage.CreateFromMailMessage(MailMessage message)'
There is also an Inner Excpetion: "The type initializer for 'MimeKit.Utils.CharsetUtils' threw an exception." Stacktrace: 'at MimeKit.ParserOptions..ctor() at MimeKit.ParserOptions..cctor()
I am not getting any exception on my development box but that only executes up to the conversion and signing not the actual smtp sending.
Dim netMail As New System.Net.Mail.MailMessage
netMail.From = New System.Net.Mail.MailAddress("no_reply#lionandlambchurch.com")
netMail.To.Add(txtTo.Text)
netMail.Subject = txtSubject.Text
netMail.Body = txtContent.Text
Dim mimeMail As MimeMessage = CType(netMail, MimeMessage)
Dim headersToSign = New List(Of HeaderId)
headersToSign.Add(HeaderId.From)
headersToSign.Add(HeaderId.To)
headersToSign.Add(HeaderId.Subject)
headersToSign.Add(HeaderId.Date)
Dim privateKeyPath = AppDomain.CurrentDomain.BaseDirectory + "\App_Data\rsa.private"
Dim signer = New Cryptography.DkimSigner(privateKeyPath, "lionandlambchurch.com", "key1")
Dim loggerPath = AppDomain.CurrentDomain.BaseDirectory + "\logs\smtp-mailkit.log"
mimeMail.Sign(signer, headersToSign, Cryptography.DkimCanonicalizationAlgorithm.Relaxed, Cryptography.DkimCanonicalizationAlgorithm.Simple)
' Don't attempt sending locally
If Request.Url.Host.ToLower().Contains("localhost") Then Return
Using client As New MailKit.Net.Smtp.SmtpClient(New ProtocolLogger(loggerPath))
client.Connect("relay-hosting.secureserver.net", 25, False)
If chkAuthenticate.Checked Then
client.Authenticate("no_reply#lionandlambchurch.com", "****")
End If
client.Send(mimeMail)
client.Disconnect(True)
End Using
Had same problem and I solved it by opening the NuGet console in Visual Studio and installing the newest System.Text.Encoding.CodePages package:
install-Package System.Text.Encoding.CodePages
Based on the exception, the error is occurring during the conversion, not sending.
For some reason, the static constructor for MimeKit.ParserOptions is failing because the static constructor for MimeKit.Utils.CharsetUtils is failing.
Looking at MimeKit's code, all I can think of is that your server doesn't have UTF-8 or Latin1 support.
e.g. System.Text.Encoding.GetEncoding (65001, new EncoderExceptionFallback (), new DecoderExceptionFallback ()); or Encoding.GetEncoding (28591, new EncoderExceptionFallback (), new DecoderExceptionFallback ()); is throwing an exception.
Honestly, I don't know how that could even happen.
What .NET are you using on your server?
I have got a sample add in for excel:
I create a object InDesign.Application
Dim myInDesign As InDesign.Application
Dim myDoc As InDesign.Document
Dim myPage As InDesign.Page
myInDesign = CType(Activator.CreateInstance(Type.GetTypeFromProgID("InDesign.Application"), True), InDesign.Application)
myDoc = myInDesign.Documents.Add
myDoc = myInDesign.ActiveDocument
InDesign opens, But the add-in shows error at:
`myInDesign = CType(Activator.CreateInstance(Type.GetTypeFromProgID("InDesign.Application"), True), InDesign.Application)`
Content of Error:
Unable to cast COM object of type 'System.__ComObject' to interface type 'InDesign.Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{ABD4CBB2-0CFE-11D1-801D-0060B03C02E4}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Why? Can you help me?
Have you added the reference to the InDesign Type Library using vb.net's com interface?
Open the references panel in Visual Studio and choose the "COM" tab, and look for InDesign in your list. It will default to Copy Local = False.
Now you can use the COM functions just like you were writing vbs.
I would like to deserialize the returned JSON from a service call in VB.NET to an anonymous type but I was having error. It works in C# using dynamic type but i dont know how to do it in VB.
Here is my JSON returned from a web service call:
{"format":"png","height":564,"width":864}
Here is my VB code json above assigned to param text:
Dim testObj = Newtonsoft.Json.JsonConvert.DeserializeObject(text)
But when i tried to access testObj.format, an exception was thrown with message
{"Public member 'format' on type 'JObject' not found."}
I already have added Option Strict Off. I dont want to use an Object/Class to deserialize the JSON. If its in C# assigning this to dynamic type will be working fine.
Can anyone please help? I am not expert in VB but I need to have this running on VB. TIA
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim testObj = js.Deserialize(source, New Object().GetType())
Then you can access the key(attribute name)/values via:
value=testobj(key)
One more thing, you can access your Newtonsoft key(attribute name)/values through:
value=testObj.item(key)
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim DeSerialObjEventData = New With {.Prop1 = String.Empty, .Prop2 = String.Empty, .Prop3 = String.Empty}...
Dim testObj = js.DeserializeAnnonomusType(source, DeSerialObjEventData)
I have written an external application to drive autocad with a dll that was registered for COM. I have followed this codes to write my application however i have replaced the following code with AddNumbers() method:
public string OpenDWGFile(string MyDWGFilePath)
{
DocumentCollection dm = Application.DocumentManager;
Document doc = null;
if(File.Exists(MyDWGFilePath))
{
doc = dm.Open(MyDWGFilePath, false);
Application.DocumentManager.MdiActiveDocument = doc;
return "This file is exists";
}
else
return "This file is not exist";
}
but when i run my application the autocad software open and then close immediatly and this error message is shown : Exception has been thrown by the target of an invocation.
but if i comment the following lines of my code the application works without any errors:
doc = dm.Open(MyDWGFilePath, false);
Application.DocumentManager.MdiActiveDocument = doc;
You are creating a second instance of the DocumentManager and giving it a reference to an object retrieved from the first one. I think you want to use
dm.MdiActiveDocument = doc;
I am getting the following message when trying to return a new object to VBA from my Visual Foxpro COM server.
"Run-time error '-2147417851 (80010105)':
Method 'ReturnObject' of object 'Itestclass' failed"
If I remove the "Dim ... As" line the error goes away but then I lose intellisense for the COM object.
This is the VBA code:
Sub Test()
'' Removing the following line gets rid of the error but loses intellisense for the COM object
Dim objTest As testcom.TestClass
Set objTest = CreateObject("TestCOM.TestClass")
Set objNew = objTest.ReturnObject '' This is the line that causes the error
End Sub
I have created a link to the TestCOM type library in Tools > References
Here is the Visual Foxpro (VFP) code:
The COM server is being built as an out of process EXE. If I build it as an inprocess .DLL then the VBA code causes Excel to crash.
DEFINE CLASS ObjectToReturn AS SESSION OLEPUBLIC
ENDDEFINE
DEFINE CLASS TestClass AS SESSION OLEPUBLIC
FUNCTION ReturnObject
RETURN CREATEOBJECT("ObjectToReturn")
ENDFUNC
ENDDEFINE
I have tried changing the RETURN CREATEOBJECT("ObjectToReturn") to RETURN CREATEOBJECT("CUSTOM") but the problem persists.
Please advise how I can get rid of this error without losing the intellisense for the COM object in VBA. Thanks
I don't know why you are going through such difficulties... This should be able to help you... You can define your class as OlePublic and set some properties on it like the samples at the top. You can set these properties anywhere through the other functions that are not HIDDEN.
If you need to are trying to get at certain elements OF some other "object", try creating an instance of the object and stick it into a property on the OlePublic class... see my method
DoSomethingElse
which does a simple scatter NAME call to the "SomeObject" property of the class. Even though you are not explicitly returning it, it should be visible from within your creation of it from VB...
DEFINE CLASS VFPClassForVB as Session OLEPublic
cTmpFiles = ""
cCOMUser = ""
SomeObject = ""
FUNCTION Init()
*/ Who is user... always ignore the machine....
This.cCOMUser = SUBSTR( SYS(0), AT( "#", SYS(0)) +1 )
This.cTmpFiles = "somepath\"
*/ Unattended mode... any "MODAL" type dialog will throw error / exception
SYS(2335, 0 )
*/ ALWAYS HAVE EXCLUSIVE OFF FOR COM!!!
SET EXCLUSIVE OFF
*/ ALWAYS HIDE DELETED RECORDS!!!
SET DELETED ON
ENDFUNC
*/ Error handler at the CLASS level will always be invoked
*/ instead of explicit ON ERROR or TRY/CATCH handlers...
FUNCTION xError(nError, cMethod, nLine)
lcMsg = "User: " + SYS(0) + " Tmp:" + SYS(2023);
+ " Method: " + cMethod + " Error: " + STR( nError,5);
+ " Line: " + STR( nLine, 6 )
STRTOFILE( lcMsg, This.cTmpFiles + "COMLog.txt" )
*/ NOW, throw the COM Error...
COMReturnError( cMethod + ' Error:' + str(nError,5);
+ ' Line:' + str(nline,6);
+ ' Msg:' + message(), _VFP.ServerName )
RETURN
HIDDEN FUNCTION SomeOtherFunction( lcWhat String,;
lnThing as Integer ) as String
*/ Do something
RETURN 1
ENDFUNC
*/ Another completely visible function direct form VB
FUNCTION DoSomethingElse( SomeParameter as String ) as String
USE SomeTable
*/ Now, this object should be visible as a direct property in VB
SCATTER MEMO NAME This.SomeObject
ENDFUNC
ENDDEFINE
Your VB side, even from your sample...
Sub Test()
Set objTest = CreateObject("MySampleProject.VFPClassForVB")
objTest.DoSomethingElse( "I dont care" )
dim Something as objTest.SomeObject.ColumnFromTable
End Sub
You can create as many OlePublic classes in your in-code class libraries that you want to expose and just create those instances as needed. Let me know if this helps you get closer and we'll try to keep working it out.
I've tried all sorts of samples, but looking at what you have of the object where both are VFP OleObject entries, each is exposed, and can be created individually. You don't need to create one to create the other.
Is there some reason SPECIFIC you are trying to create one object from another? You can have one object expose a bunch of methods and properties to perform whatever you need from VFP.
If you want to have multiple object classes exposed, and under a central control, you can always create your primary object for communication and have IT create an instance of each "other" class on it. Then, expose methods on your main class to handle the communications between them to act out whatever it is you need.