IVsDropdownBarClient and GetEntryText: Problems with text buffers - c#

In my Visual Studio extension, I'm going to read the text that is in the navigation bar. Therefore I listen to window created events and from the IVsCodeWindow object I get the IVsDropdownBar to get the current selection in the dropdown bar. This works fine. Then I'm using the following code snippet to extract the text of the current selection:
string text;
barClient.GetEntryText(MembersDropdown, curSelection, out text);
if (hr == VSConstants.S_OK)
{
Debug.WriteLine("Text: " + text);
} else {
Debug.WriteLine("No text found!");
}
However, this does not work. My extension crashes with an unhandled exception in the second line of the code snippet. I read the documentation and could find the following note:
The text buffer returned in ppszText is typically created by the
IVsDropdownBarClient object and the buffer must persist for the life
of the IVsDropdownBarClient object. If you are implementing this
interface in managed code and you need to have the string disposed of
by the caller, implement the IVsCoTaskMemFreeMyStrings interface on
the IVsDropdownBarClient interface.
I assume that this is part of my problem, but I can't really understand what I have to change in my code to get it working. Any hints?

I'm pretty sure now that the Visual Studio SDK Interop DLLs have the wrong marshalling information for IVsDropDownbarClient.GetEntryText and that there's no way to call that method using that interface.
The best workaround I've found so far is:
Use the tlbimp tool to generate an alternate Interop DLL for textmgr. (You can safely ignore the dozens of warnings including the one about GetTextEntry.)
tlbimp "c:\Program Files (x86)\Microsoft Visual Studio 11.0\VSSDK\VisualStudioIntegration\Common\Inc\textmgr.tlb"
(Optional) If you're using source control, you'll probably want to copy the resulting file (TextManagerInternal.dll) to a subdirectory of your extension project and check it in as an external dependency.
In your Visual Studio extension project, add a reference to the file (TextManagerInternal.dll).
Add the following method that should properly handle the string marshalling.
static public string HackHackGetEntryText(IVsDropdownBarClient client, int iCombo, int iIndex)
{
TextManagerInternal.IVsDropdownBarClient hackHackClient = (TextManagerInternal.IVsDropdownBarClient) client;
string szText = null;
IntPtr ppszText = IntPtr.Zero;
try
{
ppszText = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr)));
if(ppszText == IntPtr.Zero)
throw new Exception("Unable to allocate memory for IVsDropDownBarClient.GetTextEntry string marshalling.");
hackHackClient.GetEntryText(iCombo, iIndex, ppszText);
IntPtr pszText = Marshal.ReadIntPtr(ppszText);
szText = Marshal.PtrToStringUni(pszText);
}
finally
{
if(ppszText != IntPtr.Zero)
Marshal.FreeCoTaskMem(ppszText);
}
return szText;
}
}

Related

C#: ArgumentException when calling System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()

I am in a bit of a strange situation. I have been given a fairly large suite of PowerShell modules and functions, and it is my job to tie these together into an executable. The requirements state that this must be a single, standalone executable with no installer and .net 3.5 may be the only dependency. The Windows Management Framework is not an exception and cannot be assumed to exist on the machine. To get around this, I have added System.Management.Automation as a reference and made it an embedded resource, along with all of the PowerShell module files, and load them from reflection at runtime. This seems to work OK, but I have some errors that I cannot seem to figure out and think it might have something to do with this system.
So Here is the issue: When I start to initialize things to run the PowerShell command, I get a strange error that I can't seem to control.
Here is the code:
public static void RunCommand(object objcommand)
{
//create a script block for toolbox once, get the embeded resource, convert from byte array to string, make scriptblock from string
ScriptBlock toolbox = System.Management.Automation.ScriptBlock.Create(System.Text.Encoding.Default.GetString(Properties.Resources.toolbox));
string command = (string)objcommand;
//get the module name
string modname = options.Commands[command]["module"];
//get the module from the embeded resources, convert to string, convert to scriptblock
var module = System.Management.Automation.ScriptBlock.Create(new System.IO.StreamReader(myasm.GetManifestResourceStream("piramids.Resources." + modname + ".psm1")).ReadToEnd());
using (var powerShell = PowerShell.Create())
{
System.Management.Automation.Runspaces.Runspace rs = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); //i think this line triggers the exception
rs.Open();
powerShell.Runspace = rs;
//make the necesary powershell modules of the command availible
powerShell.AddCommand("new-module").AddParameter("ScriptBlock", toolbox).Invoke();
powerShell.AddCommand("new-module").AddParameter("ScriptBlock", module).Invoke();
//if inethistory, make dlls availible
if (modname.Equals("inethistory"))
{
powerShell.AddCommand("add-type").AddParameter("Path", sqldll).Invoke();
powerShell.AddCommand("add-type").AddParameter("Path", esentdll).Invoke();
}
ICollection<PSObject> output = new List<PSObject>(0);
try {
output = powerShell.AddCommand("get-" + command).AddCommand(format).AddCommand("out-string").Invoke();//pipeline.Invoke();
} catch (System.Management.Automation.RuntimeException e)
{
Console.Error.WriteLine("An Error occured while executing '" + command + "'");
Console.Error.WriteLine(e.Message);
}
//do stuff with the results
and here is the stack trace:
Unhandled Exception: System.ArgumentException: The path is not of a legal form.
at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at System.Diagnostics.FileVersionInfo.GetFullPathWithAssert(String fileName)
at System.Diagnostics.FileVersionInfo.GetVersionInfo(String fileName)
at System.Management.Automation.PSVersionInfo.GetPSVersionTable()
at System.Management.Automation.PSVersionInfo.get_PSVersion()
at Microsoft.PowerShell.DefaultHost..ctor(CultureInfo currentCulture, CultureInfo currentUICulture)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()
at piramids.Program.RunCommand(Object objcommand)
at piramids.Program.Main(String[] args)
I believe this line is where the exception occurs:
System.Management.Automation.Runspaces.Runspace rs = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
The CreateRunspace method is not documented to throw any exceptions, and this exception comes from so many levels down that I have no idea what kind of path this thing is checking, as I never called a function that asked for a path.
I am stumped. Does anyone have any idea what may be causing this?
EDIT: After some digging, here is what I found. PSVersionTable is a static field of VersionInfo, so the static constructor is called the first time get called for this field. The static constructor calls an internal method called GetBuildVersion, which tries to get the assembly location of PSVersionInfo. According to This documentation page:
If the assembly is loaded from a byte array, such as when using the Load(Byte[]) method overload, the value returned is an empty string ("").
I am loading from a byte array, so this will be an empty string. But then GetBuildVersion uses this location to do FileVersionInfo.GetVersionInfo which verifies the path with Path.GetFullPath. According to This documentation page:
ArgumentException:
the path is a zero-length string
So there is the problem. Now the question is, How do I assign a location to an assembly loaded from a byte array? May God have mercy on me.
I'm not at all convinced this is even remotely reasonable to expect PowerShell code to work without installing WMF. If I were approached with that request I would respond that all code must be rebuilt in another .NET language (that is, C#).
Still, perhaps you can see if it's this static method. You'll have to de-PowerShell the code I'm afraid. The PowerShell accelerator is just a simple way for me to get at the System.Management.Automation assembly. The class is not public and the method on the class is not public either.
$verInfo = [PowerShell].Assembly.GetTypes() | Where-Object Name -eq 'PSVersionInfo'
$verInfo.GetMethod('get_PSVersion', [System.Reflection.BindingFlags]'NonPublic,Static').Invoke($null, [System.Reflection.BindingFlags]'NonPublic,Static', $null, #(), $null)
Chris

C# Setup Project run after install

Hello guys I'm new to the forum also programming and need some help about a project.
So I recently start developing a program that firstly must add its path at the end of Registry => Environment => Path.
For this job I created project (MainLogic) which contain a class (Program) that do the job, Installer Class that contains this events below and configured Setup Project. SOURCE
public InstallerClass1()
{
this.Committed += InstallerClass1_Committed;
this.Committing += InstallerClass1_Committing;
}
private void InstallerClass1_Committing(object sender, InstallEventArgs e)
{
//Console.WriteLine("");
//Console.WriteLine("Committing Event occurred.");
//Console.WriteLine("");
}
private void InstallerClass1_Committed(object sender, InstallEventArgs e)
{
Directory.SetCurrentDirectory(Path.GetDirectoryName
(Assembly.GetExecutingAssembly().Location));
Process.Start(Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location) + "\\MainLogic.exe");
}
The program was installed correctly but MainLogic.exe file I call after installation cause an error and can't start. The exception is Null Reference at MainLogic.Program.Main(String[] args)
Here is a picture for better understanding -
Is there a way to avoid that exception or could you offer me another that will work.
*** Here what i found. I can execute creating and typing in to file. Writing on the console. Probably a lot of other stuff without problem. But when try to execute this peace of code which actually I have to use...
Registry.CurrentUser.OpenSubKey("Pass Key", RegistryKeyPermissionCheck.ReadWriteSubTree).SetValue("Finaly", "Done");
Registry.CurrentUser.Close();
...the exception I described above occurs. Suggestions?
So the main reason for all those "exercises" is because I want to implement ffmpeg in my application.
I guess you are hear about ffmpeg (a video/audio processing program that works in command prompt).
So what I'm working on is to implement it in my project for mp3 extracting from video files but I wanna make it more user friendly so the user can pass commands through GUI and from there my code should do the other job. So ffmpeg works through command prompt (I know there is a wrappers but I'm not very satisfied with what read about) but firstly you have to add his path to Path's value in the registry. And here's where my problem came from.
Maybe it's sounds stupid for you but you know.. when you start something make it all the way.
If course you can just add exception handling and see what goes wrong but you don`t neet that anyway. Try to set the registry key directly in your Installer
[RunInstaller(true)]
public partial class Installer1 : Installer
{
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
const string key_path = "SOFTWARE\\YourCompany\\YourApplication";
const string key_value_name = "InstallationDirectory";
RegistryKey key = Registry.LocalMachine.OpenSubKey(key_path, Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree);
if (key == null)
{
key = Registry.LocalMachine.CreateSubKey(key_path);
}
string tgt_dir = "someDirectory";
key.SetValue(key_value_name, tgt_dir);
}
if you want to alter the path enironment variables set the key there. You can simply add a new variable or look for an exiting one (including the value) for example with Registry.GetValue MSDN-Link
User Variables
HKEY_CURRENT_USER\Environment
System Variables
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Highlighting code window text from Visual studio tool window using VSPackage

I'm kind off new to the Visual Studio Extensions. Is there a way to interact to code window from Visual Studio 2010 tool window.
I have a Datagrid hosted on the VisualStudio tool window. DataGrid contains ClassName, MethodName e.tc. On the click of className/MethodName need to acheive the following
Open the particular .cs file containing className/MethodName
HighLight the particular className/MethodName.
I know this acheivable using "IWpfTextView" class, but not sure how. Did a lot of googling but in vain.Even the link below remains to be un-answered link.
Any help on the above will be greatly appreciated.
I actually did almost the same thing. You can see complete source code on Visual Localizer.
Basically you need to do two things:
Obtain IVsTextView instance for the file
call its SetSelection() method which takes range (start line, end line, start column, end column) as parameters. You may also want to call the EnsureSpanVisible() to scroll down.
Obtaining IVsTextView is quite easy as well. In my project (Visual Localizer) there's a class called DocumentViewsManager, located in VLlib/components that has fairly straightforward method called GetTextViewForFile(), which takes only file path as an argument. It does the following:
use VsShellUtilities.IsDocumentOpen method to obtain IVsWindowFrame for given file path
pass this to the VsShellUtilities.GetTextView method, which returns IVsTextView
Hope it helps.
Thanks cre8or.
I found an alternative to do the same.
You need to use "TextSelection" class to highlight the above code line.
foreach (CodeElement codeElement in projectItem.FileCodeModel.CodeElements)// search for the function to be opened
{
// get the namespace elements
if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
{
foreach (CodeElement namespaceElement in codeElement.Children)
{
// get the class elements
if (namespaceElement.Kind == vsCMElement.vsCMElementClass || namespaceElement.Kind == vsCMElement.vsCMElementInterface)
{
foreach (CodeElement classElement in namespaceElement.Children)
{
try
{
// get the function elements to highlight methods in code window
if (classElement.Kind == vsCMElement.vsCMElementFunction)
{
if (!string.IsNullOrEmpty(highlightString))
{
if (classElement.Name.Equals(highlightString, StringComparison.Ordinal))
{
classElement.StartPoint.TryToShow(vsPaneShowHow.vsPaneShowTop, null);
classElement.StartPoint.TryToShow(vsPaneShowHow.vsPaneShowTop, null);
// get the text of the document
EnvDTE.TextSelection textSelection = window.Document.Selection as EnvDTE.TextSelection;
// now set the cursor to the beginning of the function
textSelection.MoveToPoint(classElement.StartPoint);
textSelection.SelectLine();
}
}
}
}
catch
{
}
}
}
}
}
}

Is an Application Associated With a Given Extension?

It is sometimes desirable to have your application open the default application for a file. For example, to open a PDF file you might use:
System.Diagnostics.Process.Start("Filename.pdf");
To open an image, you'd just use the same code with a different filename:
System.Diagnostics.Process.Start("Filename.gif");
Some extensions (.gif for example) just about always have a default handler, even in a base Windows installation. However, some extensions (.pdf for example) often don't have an application installed to handle them.
In these cases, it'd be desirable to determine if an application is associated with the extension of the file you wish to open before you make the call to Process.Start(fileName).
I'm wondering how you might best implement something like this:
static bool ApplicationAssociated(string extension)
{
var extensionHasAssociatedApplication = false;
var condition = // Determine if there is an application installed that is associated with the provided file extension.;
if (condition)
{
extensionHasAssociatedApplication = true;
}
return extensionHasAssociatedApplication;
}
I would recommend following the advice in David's answer BUT since you need to detect an association:
To check whether a file has an association you can use the native function FindExecutable which is basically what Windows Explorer uses internally... it gives a nice error code (SE_ERR_NOASSOC) if there is no association. Upon success it gives a path to the respective executable.
Thee DllImport for it is
[DllImport("shell32.dll")]
static extern int FindExecutable(string lpFile, string lpDirectory, [Out] StringBuilder lpResult);
Another option would be to walk the registry for example (not recommended since complex due to several aspets like WoW64 etc.):
The real association is stored in the key that HKEY_CLASSES_ROOT\.pdf points to - in my case AcroExch.Document, so we checkoutHKEY_CLASSES_ROOT\AcroExch.Document. There you can see (and change) what command is going to be used to launch that type of file:
HKEY_CLASSES_ROOT\AcroExch.Document\shell\open\command
#Yahia gets the nod. I'm posting my quick solution for posterity so you can see what I went with. There are lots of possible improvements to this code, but this will give you the idea:
public static bool HasExecutable(string path)
{
var executable = FindExecutable(path);
return !string.IsNullOrEmpty(executable);
}
private static string FindExecutable(string path)
{
var executable = new StringBuilder(1024);
FindExecutable(path, string.Empty, executable);
return executable.ToString();
}
[DllImport("shell32.dll", EntryPoint = "FindExecutable")]
private static extern long FindExecutable(string lpFile, string lpDirectory, StringBuilder lpResult);
In a situation like this the best approach is to try to open the document and detect failure. Trying to predict whether or not a file association is in place just leads to you reimplementing the shell execute APIs. It's very hard to get that exactly right and rather needless since they already exist!
You will have too look at the registry to get that information.
You can follow from:
HKEY_CLASSES_ROOT\.extension
and it usually leads to something like HKEY_CLASSES_ROOT\extfile\Shell\Open\Command
and you will come to the command to open the file type.
Depending on what you are doing, it may be ideal to just ask for forgiveness ( that is, just open the file and see)
All of that information lives in the registry.. you could navigate to HKEY_CLASSES_ROOT, find the extension and go from there to find the default handler. But depending on the type of file and the associated handler(s) you'll need to wade into CLSIDs and whatnot... you're probably better off catching an exception instead.
This information is in the registry. For example:
# Mount the HKCR drive in powershell
ps c:\> new-psdrive hkcr registry hkey_classes_root
ps c:\> cd hkcr:\.cs
# get default key for .cs
PS hkcr:\.cs> gp . ""
(default) : VisualStudio.cs.10.0
...
# dereference the "open" verb
PS hkcr:\.cs> dir ..\VisualStudio.cs.10.0\shell\open
Hive: hkey_classes_root\VisualStudio.cs.10.0\shell\open
Name Property
---- --------
Command (default) : "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" /dde
ddeexec (default) : Open("%1")

Vista TaskDialog Wrapper: Unable to find an entry point named 'TaskDialogIndirect' in DLL 'ComCtl32'

I'm try to use Vista TaskDialog Wrapper and Emulator and I'm getting the following exception:
"Unable to find an entry point named 'TaskDialogIndirect' in DLL 'ComCtl32'."
...in a simple Console application:
class Program
{
[STAThread]
static void Main(string[] args)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
PSTaskDialog.cTaskDialog.MessageBox(
"MessageBox Title",
"The main instruction text for the message box is shown here.",
"The content text for the message box is shown here and the text willautomatically wrap as needed.",
PSTaskDialog.eTaskDialogButtons.YesNo,
PSTaskDialog.eSysIcons.Information
);
}
}
What am I doing wrong?
UPDATE:
Actually, I'm working on an Excel plugin using excel-dna. How can I control what dll Excel loads?
http://exceldna.codeplex.com/discussions/286990#post728888
I haven't been at Office programming in a while, but my guess is that Excel loads both versions of comctl32, so you may need to use the Activation Context API to direct your code to the version that includes TaskDialog. Some ideas for fixing the problem (not solutions as such):
For test purposes, make a temporary enumeration of all modules in the active process - just to check if 6.10 is actually loaded (see below for a simple example of such an enumeration, albeit with a different intent).
Use the Activation Context API to get to the right version. Example of use from C# (for enabling themes by way of comctl32 6.0) here.
Alternatively (I never actually got this to work reliably in a WPF application I worked on), make a dialog abstraction class, which falls back to MessageDlg depending on the version available to you. There may be better ways of doing the check, but...:
FileVersionInfo version = ProcessUtils.GetLoadedModuleVersion("comctl32.dll");
if (version != null && version.FileMajorPart >= 6 && version.FileMinorPart >= 1)
{
// We can use TaskDialog...
}
else
{
// Use old style MessageBox
}
The enumeration of modules:
internal static FileVersionInfo GetLoadedModuleVersion(string name)
{
Process process = Process.GetCurrentProcess();
foreach (ProcessModule module in process.Modules)
{
if (module.ModuleName.ToLower() == name)
{
return module.FileVersionInfo;
}
return null;
}
}
In addition to what all the others are saying: This error will disappear if you set the ForceEmulationMode on PSTaskDialog to true.

Categories

Resources