Visual Studio hangs when manipulating TextSelection.Text - c#

I'm creating a Visual Studio 2013 plugin (ok, extension package actually) that seeks to paste certain strings* into a currently open .vb or .cs file, but when I get to the point of doing the actual pasting of text the editor instance freezes up for a while. If there are reletively few lines, VS will come back after a few seconds, but for 20+ lines the editor just never comes back.
This is the gist of what my code looks like:
String myText = "foo";
DTE dte = this.GetService(typeof(DTE)) as DTE;
EnvDTE.TextSelection selection = (dte.ActiveDocument.Selection as EnvDTE.TextSelection);
selection.Text = "";
//Here myText ends up having some content written into it
selection.Text = myText; //VS hangs after this point
Any clues as to what I can do to fix (or at least debug) this? I've tried VS's Profiler but all I get is that 98% of the time is wasted on "msenv.dll" and I can't see what's going on inside..
*(takes SQL from the clipboard and breaks it into lines wrapped in AppendLine calls to a StringBuilder)

OK, I hadn't seen this question: https://stackoverflow.com/a/1096737/1605873
Turns out, I just needed to use selection.Insert(myText); rather than selection.Text = myText; it is absurdly faster.

Related

WinForms WebBrowser HtmlDocument.Write behaves differently in different solutions

Recently, my application has crashed when trying to display a rather lengthy (but otherwise simple) HTML e-mail.
The crash was caused by mshtml.dll getting a stack overflow (exception code 0xc00000fd). Of note here is that this didn't throw an exception but it actually just crashed the program as a whole. The error was retrieved from the Windows event log.
In the process of debugging, I created a smaller sample solution to try and narrow down the issue. However, not only does it work fine in the sample solution, it behaves completely different from the main program despite running the same code even for the simplest of HTML strings.
The code is as follows:
var webBrowser1 = new System.Windows.Forms.WebBrowser();
webBrowser1.AllowNavigation = false;
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.Navigate("about:blank");
var doc = webBrowser1.Document.OpenNew(true);
doc.Write("<HTML><BODY>This is a new HTML document.</BODY></HTML>");
var count = doc.All.Count;
var html = doc.All[0].OuterHtml;
In the sample solution this evaluates to:
count = 4; // [HTML, HEAD, TITLE, BODY]
html = "<HTML><HEAD></HEAD>\r\n<BODY>This is a new HTML document.</BODY></HTML>";
Meanwhile in the main program it comes out to:
count = 3; // [HTML, HEAD, BODY]
html = "<html><head></head><body>This is a new HTML document.</body></html>";
These are small discrepancies but that is largely due to the simple HTML used. The one that causes the crash has rather significant differences.
I am absolutely stumped as to how the result can be so vastly different.
The documentation for HtmlDocument.Write(string) states that:
It is recommended that you write an entire valid HTML document using the Write method, including HTML and BODY tags. However, if you write just HTML elements, the Document Object Model (DOM) will supply these elements for you.
But I have no idea how the DomDocument is provided nor why they would be different in the first place. Both solutions are running in x64 Debug mode and Net-Framework 4.6.2.
Both load the module: C:\WINDOWS\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a\Microsoft.mshtml.dll
How is it possible that these produce different results?!
Any and all help welcome.
Thanks in advance.
The difference in behavior stems from the registry entry as proposed by Jimi and linked here
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
To reiterate, in the above registry the main program had an entry "ApplicationFileName.exe"=dword:00002af9 while my new test-application didn't.
This, in and for itself, does not explain the crashing of mshtml.dll itself but since the question was about the difference in behavior I'll post this as the answer. The crash is most likely linked to the outdated version used by Visual Studio but I haven't yet had the chance to look into some of the proposed fixes for that.

Why is my clipboard-manipulating application behaving differently when run outside of Visual Studio?

I have a console app with an "output type" of "Windows Application" (to achieve a headless behavior, i.e. no UI, no console window). The purpose is to "clean" text in the Windows clipboard, i.e. trim all leading and trailing whitespace and remove formatting.
It works great when debugging, but when I run it from explorer, it just clears the clipboard contents.
Here's my code:
[STAThread]
internal static void Main(string[] args)
{
var currentClipboardText = System.Windows.Clipboard.GetText();
// only if the clipboard has text; leave any other content intact.
if(!string.IsNullOrEmpty(currentClipboardText))
{
currentClipboardText = currentClipboardText.Trim();
var pattern = #"[\t\r\n\v\f\u2028\u2029]"; // match vert. whitesp & tabs
currentClipboardText = Regex.Replace(currentClipboardText, pattern, " ");
System.Windows.Clipboard.SetDataObject(currentClipboardText);
}
}
Sample input with formatting in MS Word, copied to clipboard:
After I run the program in the dubugger (either in "debug" mode or "release" mode, makes no difference), here is the result pasted back into Word from the clipboard:
If I do the same excercise but run the program by double-clicking on it in Windows explorer (i.e. in the \bin\Debug directory), there is no text left on the clipboard to paste into Word:
What is the difference here? Why isn't it working outside of Visual Studio?
By default, data placed on the system Clipboard with SetDataObject is automatically cleared from the Clipboard when the application exits.
MSDN
Use System.Windows.Clipboard.SetDataObject(currentClipboardText, true); instead to keep the data in the clipboard after the application exits.
I have tested your code, and it does not work when debugging. I changed the line:
System.Windows.Clipboard.SetDataObject(currentClipboardText);
With:
System.Windows.Clipboard.SetText(currentClipboardText);
And it worked when debugging, and when not debugging. I think what is happening is that Word is no longer recognizing the DataObject as being paste-able text.
I hope this solves your problem.

Resharper compile time autoformat incorrectly changes code

Resharper changes below code
string strTest = "Test";
string strTest2 = "Test2";
to this
string strTest = "Test";string strTest2 = "Test2";
if cursor is at the end of the first line when I start project. It makes all breakpoints obsolete ("The breakpoint will not currently be hit. The source code is different from the original version.")
And sometimes it mixes comment line with code line and completely breaks execution. For instance:
//Comment line
string strTest = "Test";
changes to
//Comment linestring strTest = "Test";
If cursor is between double quotes it doesn't modify code.
If I suspend ReSharper plugin code doesn't change on compile time so I am pretty sure that ReSharper has some problems. I tried disabling formatting on ReSharper options but it still modifies code.
How can I disable this feature? Other formatting options seems ok (Both VS and ReSharper) so if I just disable compile time auto corrections it will be ok. I couldn't find any option for this.
PS: I use VS2013 with VSCommands for VS2013 extension. ReSharper version is 10.0.2.
Solution: As #Alexander mentioned it is related to DevExpress components. Emptying the licences.licx file contents and restarting visual studio/Clean&Rebuild project resolves the issue. This prebuild-event script solves the issue.
break>$(ProjectDir)\Properties\licenses.licx

Viewing Properties.Settings.Default variables

I am trying to use Settings.settings to define/persist some vars. For brevity, I've set up a test file to demonstrate the behavior I'm seeing:
First, I define a setting in Settings.settings:
I then have the following code to test changing variableName:
public Form1()
{
InitializeComponent();
string newString = Properties.Settings.Default.variableName;
Properties.Settings.Default.variableName = "This is a new string";
Properties.Settings.Default.Save();
}
Running the above in the debugger for the first time, I grab the current value (the value I set in the Settings.settings window initially) of variableName from Properties.Settings. As expected, newString is set to "This is a string". Good.....
After executing the next two lines, the debugger shows variableName changed to "This is a new string". Good....
I then run the app through the debugger again. I hit the string newString line and, prior to execution, newString is undefined (of course). Good....
As soon as I execute...
string newString = Properties.Settings.Default.variableName;
... and on subsequent executions of the code, the actual value of variableName is defined as "This is a new string" (Good...as expected).
I then go back to the Settings.settings window. variableName has not changed - it's still "This is a string". I've even closed VSE 2012 and re-opened the project. Settings.settings never changes.
Where is the new value being stored? I've checked all of the .config files ([appname].exe.config, [appname].vshost.exe.config, app.config, and the Settings.settings file) and the new value, "This is a new string" isn't anywhere to be found.
In summary, I'm getting the result I desire from the code, but I can't seem to view the result at design time other than to check the value of the var in the debugger. This seems not only peculiar to me, but impossible.
What am I missing/where am I not looking? I would fully expect the value of variableName to change in the Settings.settings window, but it never does. I've looked everywhere on StackOverflow/Google and can't seem to find the answer.
Thanks in advance....
The original value that you configured via Settings.settings is stored in a .config file alongside your executable's assembly. This will never change unless you modify the Settings file directly via Visual Studio; it's essentially a read-only file.
The user's customized setting is stored in a separate config file within the user's profile. The location of this file depends on your assembly's metadata. For example, on Windows 7/Vista the location might look like:
C:\Users\<user name>\AppData\Local\<company name>\<assembly name>\
AssemblyName\<version>\user.config
If you haven't customized the company name in your assembly's metadata then it may default to Microsoft. Also note that AppData is a hidden folder that may not be visible in Windows Explorer depending on your view settings.
I am not sure if I understand your question. That variable content stay persistent. Thats it. Why you would set a persistent variable to change it later?

Seeing the console's output in Visual Studio 2010?

I am writing a simple C# program with some outputs (Console.WriteLine("...");). The problem is, each time I run it, I cannot see the program's output in the output window.
The "program output" tag is already checked, and I already redirected all outputs to the intermediate window but to no avail.
How do I enable seeing the program's output?
I don't think the problem lies with my code. I tried running a simple program that just outputs a string and readline "ala hello world" and I am still unable to see any output. The problem is either with me looking for the output in the wrong location or Visual Studio acting out.
The debug.write method also doesn't work.
Using debug.Write, it all works, though it didn't before. Either something bugged out with me before I restarted or I just need to take a break, either way it's all good now. Thanks all for the helpful comments =)
You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.
Here are a couple of things to check:
For console.Write/WriteLine, your app must be a console application. (right-click the project in Solution Explorer, choose Properties, and look at the "Output Type" combo in the Application Tab -- should be "Console Application" (note, if you really need a windows application or a class library, don't change this to Console App just to get the Console.WriteLine).
You could use System.Diagnostics.Debug.WriteLine to write to the output window (to show the output window in VS, got to View | Output) Note that these writes will only occur in a build where the DEBUG conditional is defined (by default, debug builds define this, and release builds do not)
You could use System.Diagnostics.Trace.Writeline if you want to be able to write to configurable "listeners" in non-debug builds. (by default, this writes to the Output Window in Visual Studio, just like Debug.Writeline)
Add a Console.Read(); at the end of your program. It'll keep the application from closing, and you can see its output that way.
This is a console application I just dug up that stops after processing but before exiting:
class Program
{
static void Main(string[] args)
{
DummyObjectList dol = new DummyObjectList(2);
dol.Add(new DummyObject("test1", (Decimal)25.36));
dol.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolxs = new XmlSerializer(typeof(DummyObjectList));
dolxs.Serialize(Console.Out, dol);
Console.WriteLine(string.Empty);
Console.WriteLine(string.Empty);
List<DummyObject> dolist = new List<DummyObject>(2);
dolist.Add(new DummyObject("test1", (Decimal)25.36));
dolist.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolistxs = new XmlSerializer(typeof(List<DummyObject>));
dolistxs.Serialize(Console.Out, dolist);
Console.Read(); // <--- Right here
}
}
Alternatively, you can simply add a breakpoint on the last line.
Press Ctrl + F5 to run the program instead of F5.
System.Diagnostics.Debug.WriteLine() will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.
P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.
To keep open your windows console and to not use other output methods rather than the standard output stream cout go to Name-of-your-project -> Properties -> Linker -> System.
Once there, select the SubSytem Tab and mark Console (/SUBSYSTEM:CONSOLE). Once you have done this, whenever you want to compile use Ctrl + F5 (Start without debugging) and your console will keep opened. :)
I run into this frequently for some reason, and I can't fathom why this solution hasn't been mentioned:
Click View → Output (or just hold Ctrl and hit W > O)
Console output then appears where your Error List, Locals, and Watch windows are.
Note: I'm using Visual Studio 2015.
Visual Studio is by itself covering the console window, try minimizing Visual Studio window they are drawn over each other.
In Program.cs, between:
static int Main(string[] agrs)
{
and the rest of your code, add:
#if DEBUG
int rtn = Main2(args);
Console.WriteLine("return " + rtn);
Console.WriteLine("ENTER to continue.");
Console.Read();
return rtn;
}
static int Main2(string[] args)
{
#endif
You could create 2 small methods, one that can be called at the beginning of the program, the other at the end. You could also use Console.Read(), so that the program doesn't close after the last write line.
This way you can determine when your functionality gets executed and also when the program exists.
startProgram()
{
Console.WriteLine("-------Program starts--------");
Console.Read();
}
endProgram()
{
Console.WriteLine("-------Program Ends--------");
Console.Read();
}

Categories