Using winforms, C# FW4.5 to open an excel sheet with late bound, like this:
objExcel = CreateObject("Excel.Application")
Now I want to use the InvokeMember method, but I don't know all the members of excel I can invoke.
For example, I know I can call it like this: InvokeMember("Close",... in order to close excel, but where can I find list of all the members I can invoke and what each one of them does?
Late-bound
Using winforms, C# FW4.5 to open an excel sheet with late bound, like this:
If you must use late-binding, using c# 4.0's dynamic keyword is a whole lot easier than InvokeMember, though it won't show you what methods you can invoke ahead of time.
Check out the following code that uses late-binding via the dynamic keyword. Notice how Visual Studio allows me to type in any old thing. Though auto-complete for the final members aren't available, it does show members for items I've used already. I won't know until runtime whether I got it right (such is the limitation of late-binding this way).
C# now supports dynamic late-binding. The language has always been strongly typed, and it continues to be so in version 4.0. Microsoft believes this makes C# easy to use, fast and suitable for all the work .NET programmers are putting it to. But there are times when you need to communicate with systems not based on .NET....The dynamic keyword in C# is a response to dealing with the hassles of these other approaches Tell me more
...and more specifically:
The COM interop scenario that the C# team specifically targeted in the C# 4 release was programming against Microsoft Office applications, such as Word and Excel. The intent was to make this task as easy and natural in C# as it always was in Visual Basic. Tell me more...
Early-bound
OP:
Now I want to use the InvokeMember method, but I don't know all the members of excel I can invoke
Though late binding is fine, even with dynamic, I like early binding. To get a list of methods, it's much easier and type-safe to use early binding via adding Microsoft.Office.Interop.Excel to your project.
Early binding:
var application = new Microsoft.Office.Interop.Excel.Application();
application.Visible = true;
application.ShowWindowsInTaskbar = true;
Here it is in VS:
C# 4 Goodness
c# 4 brings with it some stuff you'll only see when dealing with COM, like indexed properties - something not possible in c# types.
You can’t define types in C# that have indexed properties, but you can use them provided you’re doing so on a COM type more
Some smaller language features in C# 4.0 are supported only when writing code against a COM interop API
e.g.
ws.Range["A1", "B3"].Value = 123;
...is a whole lot easier than pre-c# 4:
ws.get_Range("A1", "B3").Value2 = 123;
C# 4.0 supports indexed properties on COM interop types. You can’t define types in C# that have indexed properties, but you can use them provided you’re doing so on a COM type more...
Tell me more
C# 4.0 - New C# Features in the .NET Framework 4, MSDN Mag July 2010
Dynamic .NET - Understanding the Dynamic Keyword in C# 4, MSDN Mag Feb 2011
Related
I was trying to find out how I can access Excel's enumerations through COM interoperability using C#.
Its simple to do it using early binding but with late binding I only found out that I can access enums in the same file.
If the enumerations are in a different DLL they can't be accessed. So either I use the integer values or create my own enums.
Is it really not possible to access them through late binding? If so, why? I would expect that early binding is late binding code made easy by the IDE or so.
If the enumerations are in a different DLL they can't be accessed. So either I use the integer values or create my own enums.
It is by definition, not possible to access pre-defined enums via late-binding. Obviously they will appear as "integers" to .NET. Sure you could cast some int to an enum that you have defined or perhaps a constant but such code is only for your benefit and does not represent the strong contract the COM library usually publishes.
Is it really not possible to access them through late binding? If so, why? I would expect that early binding is late binding code made easy by the IDE or so.
Early-binding makes use of either COM Type Libraries or COM Interop libraries. These are essentially .NET wrappers around COM types by providing C# or VB.NET-familiar types. With it you get intellisense in the form of statement completion; parameter help; and method help. The compiler will help you in any mistakes you might make at compile-time. Early-binding only works if the type library or COM interop library is present.
Late-binding gives you nothing in the form of intellisense. There is no indication of what objects are available; what methods are present; nor what parameters to pass. Your code may compile but you could still get runtime errors. Late binding does not use nor require type libraries nor COM interop libraries.
In addition, the term late binding means something quite specific to COM. It generally involves the invoking of IDispatch to get a list of method names. I'm not sure that .NET's enumType.GetField("Bar").GetValue() qualifies.
Late Binding Example
Late binding C# code:
// You will get no intellisense help here
var progId = "Excel.Application";
dynamic excelApp = Activator.CreateInstance(Type.GetTypeFromProgID(progId));
excelApp.Workbooks.Add = true; // VS happily lets me type all this
dynamic workSheet = excelApp.ActiveSheet; // hope this all works at runtime
Late binding or not
Isn't this example accessing an enum via late-binding with reflection? The difference is that it only works for the same file
Perhaps, it's a form of late binding. I would probably use the term decoupled.
Late-binding in the COM world is generally used in one or more of the following scenarios:
a) don't know what you will be interfacing with ahead of time
b) you do know, but you don't have access to any type library either because its not installed or the developer never created it
c) want to decouple your app from any specific version of the COM library
The example you supplied which uses enumType.GetField("Bar").GetValue(null); tells me a few things:
you know you are dealing with Excel
you have access to a form of "type library" - one that contains definitions. In this case enum constants
You are somewhat coupled to Excel
With this in mind, I'm not sure why you want to follow a late-bound route. You seem to be taking the harder approach.
Tell me more
C# create excel sheet late bound
My company has created several COM objects and they were using them happily from .NET. But now, our client wants to change to Java. I thought it would be interesting to use JACOB or j-interop (I'm not sure which of them) for some tasks, but the resultant code is pretty unmanageable. So I want to write a tool that can read the TypeLib of the COM library and then generate Java wrapper classes for hidding all those unmanageable code.
I'm a newbie in the COM world, so I don't know how to obtain the information about interfaces, methods and parameters that describe a COM object. I read about something called TypeLib, but I don't know how to read it. How can I obtain information from it?
The official API is available here: Type Description Interfaces.
You can use it from C++ directly but I suggest you use .NET (C# in my sample) with an extra tool that Microsoft has written long time ago (mine is dated 1997), named TLBINF32.DLL. It's also a COM object but is Automation (VBScript, Javascript, VB/VBA) and .NET compatible.
You can find TLBINF32.DLL googling for it (this link seems to work today: tlbinf32.dll download, make sure you get the .ZIP file, not what they call the "fixer"...). Note it's a 32-bit DLL so your program must be compiled as 32-bit to be able to use it. I don't know of any 64-bit version but how to use it a with 64-bit client is described here: tlbinf32.dll in a 64bits .Net application
How to use this library is explained in detail here in this december 2000 MSDN magazine's article: Inspect COM Components Using the TypeLib Information Object Library. It's VB (not .NET) oriented, but it's quite easy to translate in .NET terms.
Here is a sample console app in C# that just dumps all type info from a type lib (here MSHTML.TLB):
class Program
{
static void Main(string[] args)
{
TypeLibInfo tli = new TypeLibInfo();
tli.ContainingFile = #"c:\windows\system32\mshtml.tlb";
foreach (TypeInfo ti in tli.TypeInfos)
{
Console.WriteLine(ti.Name);
// etc...
}
}
}
is there any convert reference between java (for android) and C# ?
for example:
in C#: messagebox.show(sum.tostring()); ==> in java ???
There's no way to convert C# code to Java, but they're really similar. If you have a strong handle on C#, I find it very easy to ramp up with Java for Android. In your example, there are two things going on, so look at them individually.
Converting between value types and strings is very similar. Just as in C#, all the primitive types have corresponding wrapper classes (int has Integer, etc). These all have a parseXXX method and a toString method, and the String class has overloads of the valueOf method for all of the primitive types.
for example:
int someInt = Integer.parseInt(someString);
String someString = someInt.toString();
String someString = String.valueOf(someInt);
As far as showing a dialog in one line of code, that doesn't exist in Android (assuming you're talking about Android specifically because of the tag).
If you just want to see information, you can use Toast. If you need to actually display a dialog that the user interacts with, you need to learn how to display dialogs in Android.
http://developer.android.com/guide/topics/ui/dialogs.html
http://developer.android.com/guide/topics/ui/notifiers/toasts.html
http://developer.android.com/reference/java/lang/String.html
http://developer.android.com/reference/java/lang/package-summary.html
We have developed the CS2J tool for converting C# programs to Java. Unlike other converters it doesn't just translate the C# syntax into Java syntax it also has a flexible translation library so that you can convert Net framework and 3rd party library calls into their Java equivalent.
It doesn't have any specific support for the mobile SDKs (though that would be a good idea), but the translations are extensible so you can easily add a translation for the "messagebox" class and a translation its "show" method and so on.
Although C# and Java are similar languages there are a lot of details that are different and we think such a tool is very useful if you want to convert decent sized projects.
But, how does COM support them? Does C++ support them? Is is ignorant of me to assume that all COM code is written in C++? Or is COM just a methodology, a way to architect your app?
I'm curious. I've been writing lots of COM automation from C# lately and this question just occurred to me.
this link might help answer your question about optional parameters (the answer is "yes" you can do them):
http://msdn.microsoft.com/en-us/library/f25e2b6b%28VS.80%29.aspx
com is a binary specification. you can technically create a com object (server) in any language. the microsoft languages obviously (sinisterly?) make it easier than others because they wrote the spec. create a com server in straight C is possible ... technically. in reality it is a massive undertaking.
best regards,
don
If you're working with COM and Automation in C/C++ (or old versions of Delphi), you should use VARIANTs for the parameters that you want to make optional. Also, optional arguments as defined in C++ style are not supported for COM.
That said, for those VARIANTs that you are to provide when you are calling another object and you want to specify optional parameters (say, when talking to MS Word or Excel via Automation), you will need to initialize those VARIANTS with type VT_ERROR and the scode field set to DISP_E_PARAMNOTFOUND.
When receiving calls from other objects that are capable of omitting parameters (VBScript, JScript), you need to check all your VARIANTs for cases where the type has been set to VT_ERROR and the scode field is DISP_E_PARAMNOTFOUND.
The .NET equivalent is to use an object set to Type.Missing for those parameters mapped to COM optional parameters. The following link may be useful in seeing both sides of the story.
.NET4Office : Type.Missing, C#, and Word (MSDN Blog)
All of this is rooted in how older versions of VB (6 and previous) handled optional arguments. Here is a MS Support KB link that is pretty succinct.
How to pass optional parameters when you call a function from C++ (kb238981)
To address your other questions, it is incorrect to assume that a majority of COM objects are written in C++, as COM is strictly about declaring interfaces and layouts of interfaces in a well known manner. It doesn't matter what language or tools are used to make COM objects so long as they observe and obey the layouts for the interfaces that are supported.
Finally, you're correct about COM being a methodology- not quite in the sense of setting architecture for any specific app, but in making it possible to strongly define interconnected components that may make up an application or may be made available to other applications.
I found a fairly complex function in a greasemonkey script that I would like to use in my C# app. Basically I am parsing a page and I need to collect all or 4 members of var avar = {}; (i haven't done this yet but they are all strings using var avar.name = "val")
Then I need to call the gm func which returns a string and takes in 3 strings. How can I call the function in C#? I am using .NET 3.5
I'm assuming that you are after some code-reuse on the server-side or in some other freestanding app that processes HTML data.
You can compile (at least a subset of) JavaScript in .net using the Microsoft.JScript.JScriptCodeProvider class -- though note that the class warns
This API supports the .NET Framework
infrastructure and is not intended to
be used directly from your code.
Once compiled the assembly generated (as specified by the CompilerParameters supplied to the provider) should be dynamically loadable. It would be advisable to examine the generated assembly with a tool like Reflector to see what it is you've actually generated, in terms of classes and namespaces.
Disclaimer -- I've only ever used this technique with the CSharpCodeProvider acting on C# source, but I would expect there to be a reasonable level of compatibility across .net languages for this sort of thing.
EDIT -- For an example of compiling JavaScript from C# see this blog post on Verifying JavaScript syntax using C#.
First, you probably want to consider exactly why you're trying to do this. Is it that you want to use the algorithm from the JS in C#? If so, go ahead. If you want to use C# in client-side code (i.e. the browser), go investigate Silverlight instead.
Second, I'm not sure that what you're trying to do is actually possible. Depending on what youre trying to achieve, you may be better off translating the Javascript from the Greasemonkey app into C# 3.5 (assuming that the script's licensing conditions allow this), for use in your app.
The translation shouldn't be hugely difficult - C# has been getting more and more like JS in the last few versions. Just watch out for the "var" keyword; it means something slightly different in C# to what it means in JS (contrast "type inference" in C# with "dynamic typing" in JS).
Of course, maintaining both versions of the code after you've done this will be tricky and painful. I recommend keeping 1 authoritative version of the code if you can.
Good luck!
Can you provide more information about your script and what you want to accomplish? Most Greasemonkey scripts interact with the DOM via the use of Javascript. You can run Javascript in C# but the DOM will not be available to you.