Getting started with Watin - watin

I am trying to do the quick start example, I bring in the ref's using NuGet in VS2010, I scrape the sample code on the webpage, I see my NUnit Session window, I click the green arrow, but the browser doesn't get invoked (doesn't start). What am I missing?
using System;
using NUnit.Framework;
using WatiN.Core;
namespace FirstWatinProject
{
[TestFixture]
public class Class1
{
[Test]
[STAThread]
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnK")).Click();
Assert.IsTrue(browser.ContainsText("WatiN"));
}
}
}
}
I am getting the following error in NUnit Sessions window;
SearchForWaitOnGoogle Failed: System.IO.FileNotFoundException: Could
not load file or assembly 'Interop.SHDocVw, Version=1.1.0.0,
Culture=neutral etc...

Okay, solved the error, it is as the following other overflow thread concludes;
WatiN System.IO.FileNotFoundException Interop.SHDocVw
BUT, a key action in the sequence is to build the class library project AFTER setting the Interop.SHDocVw dlls' 'Embed Interop Types' property to 'False';
Then you can hit the green arrow in NUNIT Sessions window and you will see the IE browser startup after a second or two. Simply click it and you will see whatever actions you have programmed.
God is in the details!

Setting the Interop.SHDocVw, Microsoft.mshtml dlls' 'Embed Interop Types' property to 'False';
Of course Visual Studio would give you warnings on how to amend.
The Use of Nugget Package Manager

Check for the availability of Interop.SHDocVw.dll,
Make sure that your project has a reference to Interop.SHDocVw.dll and the dll is present in the Bin/Release Folder depending upon how you are running..

Just select Build from the main menu...then select Configuration Manager. In the list select you project and change its Plateform 'Any CPU' etc to x86.
If you have only Only CPU option, you can use ... option when chosing platform and create new setting, that is for X86 platform and then choose it.
ref:
Change target to x86 in VS2010

I already had a reference to Interop.SHDocVw. The easiest fix for me was simply changing .NET from 4.5 to 3.5 in Visual Studio settings. After making the change, it worked fine.

Related

Visual Studio - disable stepping into source code of module (Shouldly)

I am using a an assertion framework called Shouldly for C#.
The code looks like this:
[Fact]
public void SimpleTest()
{
false.ShouldBe(true);
}
This is the same as:
[Fact]
public void SimpleTest()
{
Assert.True(false);
}
However, when I debug the example that uses Shouldly, this happens:
But I want this to happen:
The issue
When I debug with Shouldly, Visual Studio steps into the source code of the Shouldly package. I don't want to see the internals, I just want to see what line of the test my code broke on. I can use the Stack Trace to find what line my code broke on but this slows down my flow a lot.
I remember when I first started debugging with Shouldly, VS asked me if it should download the source files (.pdb?) of Shouldly to debug with, I think I accidentally told it yes.
If I look at the Modules I have loaded in VS, it shows me this:
It thinks Shouldly is "User Code" which is probably why it debugs into this. How can I disable this?
I have this issue every time I change VS version. I've managed to fix it before but this time I can't figure it out.
You can disable symbol loading for a loaded module by:
opening the Module window
searching for the module you want to change
right clicking on it and disabling Always Load Automatically

C++ Windows Forms application icon exception

I want to set an icon for my Windows Form application. My actions step by step:
I created an 'icon.ico' (256x256) and put it into my project folder
In my 'Form1.h [Design]' I chose this file using Properties
This code appeared in 'Form1.h'
void InitializeComponent(void)
{ ...
this->Icon = (cli::safe_cast<System::Drawing::Icon^>(resources->GetObject(L"$this.Icon")));
... }
The object '$this.Icon' appeared in 'Form1.resx'
I rebuilt the whole project -> no errors
During execution the line 'this->Icon = ...' causes an exception: System.Resources.MissingManifestResourceException: 'Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "WinForm.Form1.resources" was correctly embedded or linked into assembly "MyProject" at compile time, or that all the satellite assemblies required are loadable and fully signed.'
Here I found numerous advices, such as remove/add icon or set some custom properties for 'Form1.resx', but none of them works for me
Just like above, change line to:
this->Icon = gcnew System::Drawing::Icon(L"ICON_NAME.ico");
You might get error/exception while opening form creator but you shouldn't lose any data.
Been there, done that :)
Place the Icon you want to connect to your Form in the project directory.
Then replace the line above with the following:
this->Icon = gcnew System::Drawing::Icon(L"app.ico");
This should neutralize the bug that Microsoft has not fixed.
If you are using visual studio 2019 , you need to change the name of namespace in Form1 the same as your project name, i did it and it works
and make sure you change it in main :
[STAThread]
int main() {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Application::Run(gcnew your_namespace_name::Form1());
return 0;
}

Debugging not hit breakpoints in .NET CORE MVC 6 application

I am working on .NET CORE 1.0 MVC 6 application and I stuck with the debugging point as it stopping hitting yesterday. with number of try I delete project and start again. First time it load symbols even due I have uncheck in Tool --> Debugging --> symbols, however it hit breakpoints. Now it only hitting C# class 'Startup.cs' if I choose 'Enable Just My Code' but in controller. I have Debug option from dropdown, not really sure why. Need help here.
I change as
Select Debug->Options->Debugging->General
Tick Enable .NET Framework source stepping.
but still no success
Module
Trying to Hit in Controller home class for MVC Core in Index and about
public class HomeController : Controller
{
public IActionResult Index()
{
var x = 2 + 3;
return View();
}
public IActionResult About()
{
var x3 = 2 + 6;
var xx = "dd";
ViewData["Message"] = "Your application description page.";
return View();
}
Debugging output
actually your screen shot was not the debug output, it was the build output.
If you disable the "Enable Just My Code", and enable/disable the Microsoft symbols Server under TOOLs->Options->Debugging->Symbols, and then debug your app after you re-open it, how about the result?
If I create a new app, the breakpoint was hit normally, if I re-open the solution, actually it still could hit the breakpoint, but it is very slow. Like the screen shot 1, if you visit the "debug" output window, it would list the symbols loaded one by one, after about 1min, it would hit the breakpoint like screen shot 2. Of course, I enabled the Microsoft symbols under TOOLS->Options->Debugging->Symbols and disabled the Enable Just My Code for the above steps.
So for your issue, one possible reason is that it just loads the symbols slowly, just wait for a moment.
While Jack Zhai-MSFT's solution worked I still had some weird behavior: breakpoints were working partially. Found solution here that works perfectly: Breakpoint Failed to Bind - Visual Studio 2015
While the above link is loaded with tons of solutions in my case changing configuration from Release to Debug under Build menu Configuration Manager solved all my breakpoints related problems.
I thought I was running into this same behavior except in my case it was caused by Temporal Coupling in the Startup.cs class of my .NET Core MVC application.
I had included my app.UseMiddleware() call below my app.UseMvc() call and because of this my middleware component would initialize but was never hit by requests coming into my application. Moving my call to app.UseMiddleware call above the app.UseMvc call fixed this and now my requests are being properly routed through my custom middleware.
app.UseMVC MUST BE THE LAST "app.Use()" call in the Configure method of your Startup.cs class
I faced the same problem and none of the above solutions worked.
Finally I figured out below setting works like a charm.
Go to Tools->Options->Debugging->General->Uncheck "Use Managed Compatibility Mode" checkbox
Worked for me by enabling following Debugging option "Enable .Net framework source stepping"
This solved my problem
-> Close visual studio. -> Deleting .vs folder reopen visual studio. Doing this solved the problem breakpoint couldn't be hit

Visual Studio 2010 Not Recognizing Unit Test

In an existing solution I added a new Test Project. In my Test Project .cs file I have a class decorated with the [TestClass] attribute and a method decorated with the [TestMethod] attribute. I have verified that in Configuration Manager the build check box is checked for the Test Project (as my google search has revealed was the problem for others with this issue). I have set Test Project as my start up project for the solution. When I try to start the test I get "Can not start test project because the project does not contain any tests". I am really new to unit testing. What am I missing?
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Whole bunch of stuff
Assert.Inconclusive("Done");
}
}
Update: So I opened a new instance of VS, went to File => New => Project => Test Project. Did not touch or edit anything. Went straight to the cs file and here are its contents in its entirety:
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject2
{
public class Inspection
{
public bool SubmitInsp()
{
return true;
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Inspection insp = new Inspection();
bool result = insp.SubmitInsp();
Assert.IsTrue(result);
}
}
}
Same error about the project not containing any test when I try to start it. Also found this in the build output "Could not load file or assembly '~\my documents\visual studio 2010\Projects\TestProject2\bin\Debug\TestProject2.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)"
I don't know that units tests get much simpler than this. What the heck???
I've had the same problem, when tests in an working test project suddenly weren't recognized anymore.
Comparing the project file with one from another working test project showed me that the <ProjectTypeGuids> node was missing from the main <PropertyGroup> node.
Adding this line inside the <PropertyGroup> node solved my problem:
C#:
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
VB:
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
I was able to get this to work by modifying the devenv.exe configuration file found here:
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe.config.
Add the following line to the <runtime> section, then restart Visual Studio:
<loadFromRemoteSources enabled = "true" />
(Here is the link that helped me)
The FrstCBC's anwser did not worked for me.
I am on a VirtualBox machine with Windows 7 64 bits and Visual Studio 2012.
I had to move the output to a local folder : open the unit tests project properties and in the Build tab, browse the Output path to a local folder. The tests are now detected and can be run.
Test Projects saved to a network folder or anywhere locally on my computer have this issue. Created another Test Project and saved it to my flash drive, works just fine. I don't know if it is because my machine is 64 bit or because its a virtual machine or what, but I guess I just need to test everything on external storage devices.
For me it was just that my class and method weren't public (I realize the poster did have public, but I found this post by Googling "testclass testmethod margin icons missing"). Dumb mistake on my part, but maybe it will help others.
Verify that all the .cs files are marked as Compile in the Properties window. If it is marked as Content then you will hit this issue.

Error HRESULT E_FAIL has been returned from a call to a COM component

In Silverlight 4 app; what does this error mean?:
"Error HRESULT E_FAIL has been returned from a call to a COM component."
It's a very generic error. The VS debugger doesn't point to the exact location of the error when debugging.
This is kind of an old question, but I figured I'd give my answer since I found this thread by Googling for the exact same problem.
In my case, I'd copied some sample XAML from the web to get started with Silverlight Toolkit 4. That sample XAML contained a simple button with a click event handler that didn't relate to any handler that actually existed in my code behind. I didn't notice this simple problem at first, because the compiler didn't give me an error message, I just saw the "Error HRESULT E_FAIL has been returned from a call to a COM component" message above at runtime. It was only when I isolated my sample XAML by copying it into a brand new Silverlight application without any other content that the real underlying problem was revealed at compile-time.
So, if you've got the same error message at runtime, my advice is to check your XAML carefully for any errors that you had expected should have been picked up at compile time, but which for some reason ended up as the runtime error noted above. In order to debug, you can do what I did and isolate the code that's causing the error in a standalone Silverlight app with no other content, and see if like me you get a more helpful error message to guide you.
HTH.
There are many solutions out there but this is the only solution that worked several times for me.It has been tried on VS2012 VS2013 and VS2015, I find it working equally good for all.Just follow steps bellow to fix this issue
Step 1 : Close Visual Studio
Step 2 : Delete *.csproj.user and *.suo files
Step 3 : Reopen VS, and try to run project again in debug mode.
NOTE : This situation occurs when multiple users working on same
project with different VS versions .suo file is not supported
for round-tripping between the two VS versions.It contains information
about what settings current user has selected for his/hers VS working
environment.
In my situation:
I create a
class MyControl : ContentControl {
}
By default, the class is not public and XAML cannot load it and throw exception
Error HRESULT E_FAIL has been returned from a call to a COM component
Just change the scope of class to public and error disappear.
Hope this help.
PS. Microsoft should provide more on information than just throw a mystery error message without any stack trace.
I also had this error and I found that this problem is related to not have added all requiered assemblies to your project. In my case I was using a UserControl with a depency with the Silverlight Toolkit and I havent added this reference.
I just added the reference and everything solved :)
I had this error using the current SL4 Telerik controls. A similar issue has been reported here with a solution ... of sorts. The problem seems to be with the way Expression Blend manages the cache of controls.
Here's one way to generate this error, which I stumbled upon today. We have the following button in XAML:
<Button x:Name="button" Click="Button_Click" Content="Click me" />
The event handler that handles the button's Click event is as follows:
private void Button_Click(object sender, RoutedEventArgs e)
{
button.Margin = new Thickness(0, double.NaN, 0, 0);
}
When I click on the button I get the aforementioned error. The same error arises if I replace NaN with PositiveInfinity or NegativeInfinity.
Interestingly, I get a different error message if the first parameter of the Thickness constructor contains the NaN instead of the second.
I had this error from problems with XAML. The strange thing was that I had missing resources used by Style and Margin attributes - which means the app runs fine, and even resharper only reports a 'hint'.
Once I cleared up those problems my "Error HRESULT E_FAIL has been returned from a call to a COM component." disappeared. As others have said though, this is a vague error, very difficult to debug. In this case I have inherited a large project with 100's of VS and ReSharper messages with varying severity - missing StaticResource on Style attributes were not the first place I checked!
I had this error in my xaml page and there were no syntax errors. Cleaning and re-building the project solved my issue. fyi...
The IIS App Pool has to run as an account that has query access to the Team Foundation Server. This fixes the problem for me.
Most of the reason of this problem related dependency propertied on component design.
You just face off this problem on design.
Soulution is easy but takes time :) Clean project and rebuild all. When you enter the desing again you should see everything is fine!
I hope this helps!
If you see this exception recently, please try to re-install silverlight sdk4.
This is a security and permissions issue. Look into the IIS and make sure Integrated Security is ON. Then set Application Protection level to Medium (If it is high then this might be the result). Then check your Web.Config file. Make sure impersonation is off.
This should help.
I had this problem while I was encoding Live video and audio (using Microsoft Expression) and the next piece of code throws the exception randomly:
// Set bitrate
liveJob.OutputFormat.VideoProfile.Bitrate = new ConstantBitrate(2500);
// Set Video size
liveJob.OutputFormat.VideoProfile.Size = new Size(320,240);
until i've figured out that the second line throws the exception while the first one is still running in another thread !
and of course, it was my fault - i've called the method in code, and it was also been called by Click event...
I had this exception and went nuts. I would advice you check if you had recently installed a component that had possible conflicting namespace items. In my case I installed the windows phone tool-kit which had items that were similarly named with the stock tool kit on windows phone.
Asap I uninstalled this from the Nuget package manager, all was back to normal.
Here is what FINALLY fixed this problem for us when trying to use MICROSOFT.TEAMFOUNDATION library when querying Team Foundation Server:
Team Foundation Explorer has to be installed with the currect version that is referenced in the application.
MSDTC – Configuration. (See DTC config below)
IIS App Pool has to run as an account that has query access to the Team Foundation Server
IIS App Pool has to run as an account that has COM access on IIS Server (We have a dedicated server for this so we made the identity user an administer on the local server).
Firewall has to be off or configured to allow COM access for DTC service.
DTC config ----
Click Start, click Run, type dcomcnfg and then click OK to open Component Services.
In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, and click to expand Distributed Transaction Coordinator.
Right click Local DTC, and click Properties to display the Local DTC Properties dialog box.
Click the Security tab.
In the Security Settings section, click Network DTC Access.
In the Client and Administration section, select Allow Remote Clients and Allow Remote Administration.
In the Transaction Manager Communication section, select Allow Inbound and Allow Outbound.
In the Transaction Manager Communication section, select Mutual Authentication Required (if all remote machines are running Windows Server 2003 SP1 or Windows XP SP2 or higher), select Incoming Caller Authentication Required (if running MSDTC in a cluster), or select No Authentication Required if some of the remote machines are pre-Windows Server 2003 SP1 or pre-Windows XP SP2. No Authentication Required is the recommended selection.
I hope this helps.
My problem was a missing Style. I had overridden a control template with a custom brush like so:
<Style x:Key="MyCustomStyle" TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Thumb">
....
<TextBlock Foreground="{StaticResource MyCustomBrush}"
and was missing my definition of MyCustomBrush, like so:
<SolidColorBrush x:Key="MyCustomBrush" Color="#FFAC0909"/>
and then BOOM, app didn't startup and I got that COM error message.
Well, I was almost going to eat my computer..
At last, I find out the problem is that I MAYBE BY ACCIDENT removed one parameter of one Margin setting of an Image object in the XAML page, orz..
Margin="0,-20,0"
which should be
Margin="0,-20,0,0"
Obviously I didn't realized I have ever modified anything of the XAML, so I have been troubleshooting the code behind for "a little while"..
Fortunately, I found this post and rechecked everything include the XAML page.. that was ... something...
For me, I narrowed it down to a SplitButton control that I downloaded off CodePlex ages ago. I had upgraded the solution from Silverlight 4 to Silverlight 5 and got slammed with this error. I was able to narrow it down by commenting out the XAML to all controls then uncommented it back in one by one until the error appreared again:
System.Reflection.TargetInvocationException was unhandled by user code
Message=Exception has been thrown by the target of an invocation.
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at Homexaml_3.BindingOperation(Object BindingState, Int32 , Action )
InnerException:
Message=Error HRESULT E_FAIL has been returned from a call to a COM component.
StackTrace:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.UIElement_Measure(UIElement element, Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
What fixed it was manually removing the outdated references System.Windows.Control and System.Windows.Controls.Toolkit then re-added them from the Silverlight 5 SDK folder.
Hope it helps someone (and helps me!) if it happens again a few months down the road.
I received this error recently in VS 2013 for a Silverlight 5 project. None of the above worked for me. Oddly enough, it was a threading problem (normally I am used to an exception that explains this if I am trying to create UIElements on a background thread by mistake).
Wrapping my code that adds UIElements to the MainPage with Dispatcher.BeginInvoke solved the problem:
Dispatcher.BeginInvoke(() =>
{
// your code
});
Most of the times its difficult to see where exactly the problem is located especially in XAML.
Another way to find out where its failing is to perform the following steps
Copy the exception it shows in the output window of Visual Studio. example. System.Reflection.TargetInvocationException
Click on Debug -> Exceptions. It shows up the exception list.
Click on the "Add.." button.
Paste the exception copied in the step 1 in the text box. Select "Common Language Runtime exceptions" in the drop down list.
Click on "Ok" button. The selected exception will be highlighted. Make sure you check the checkbox against the exception. Click on "Ok" button again to close the dialog.
Now run the application in debug mode. The application breaks when the exception occurs. Sometimes in the assembler mode as well.
At this point in time you have two options,
Click on the View details of the exception screen shown. Dig into
the inner exceptions until you get a clue from where its
originating.
View the call stack to see which code of line of your is causing
this exception. This will provide clues to resolve the issue.
For me, this was a XAML parsing error. In a data template, I had an extra S between two tags (probably because I pressed S instead of CTRL+S). For example...
<DataTemplate>
<Border/>s
</DataTemplate>
So, I would suggest you look for poorly formatted XML in the view that causes this exception when displayed.
In my case it was, when I tried to import database into the SSDT project, but this database already was in project, but was empty. I've just updated my project with Tools -> SQL server -> New schema comparsion. Source - database, target - project. Compare - update.
Hope it helps to someone
This error seems to be a 'catch-all' for errors that otherwise are not given a specific definition or tracing, especially those having to do with relatively external Xaml code.
In my particular case, there seemed to be an issue with the namespaces. My UserControl is in its own namespace (creatively named "UserControls"). My Pages are in their own namespace ("Pages"). I wanted to reference an enum definition in the Pages namespace from within my UserControl, so I simply added a using statement: using MySolution.Pages;. Trivial enough, and I didn't want to believe that this was the problem. But when I removed that using statement and simply created the enum in my UserControls namespace, voila, no more HRESULT error and also, as an added bonus, my dependency properties defined in the UserControl, which otherwise were mysteriously not showing up in the Xaml intellisense, suddenly were there and ready to use.
I suspect that underlying cause for this in my case was some sort of circular reference issue. And since there was no more specific error available to relate that information to me, it simply got shuffled into this HRESULT E_FAIL Com error.
I fixed this error by deleting the XAML file and add a new one from add new item. Then I pasted the XAML codes that was there in the old file.
This is an old question but in my case, none of the above solutions worked. I was trying to update the NuGet packages in Visual Studio 2017 but I was getting the following Exception.
update-package : Failed to add reference to 'System.Web.Razor'.
Error HRESULT E_FAIL has been returned from a call to a COM component.
In fact, other NuGet commands like restore-package were failing with similar exception message.
I discovered a few assemblies were missing under the packages directory so I deleted the packages directory and returned back to the Visual Studio 2017. When I opened the solution it asked me to restore the packages and after that, I was able to update the packages.
NOTE: Take a backup of package directory before deleting it.
I encountered this same error after installing VS2019 and trying to open a large solution (20+ projects), with both vcxproj and csproj projects, that target VS2015. The csproj all loaded fine, while the vcxproj all failed with the OP's error. Deleting the .vs folder did not work.
What did work was setting VC++'s "Fallback Location", under the "Browsing Database Fallback" settings.
Tools (menu)
-Options...
--Text Editor
---C/C++
---Advanced
----Browsing Database Fallback
-----Fallback Location
I set mine to D:\VC++\v16. Where I use v140 for VS2015 and v141 for VS2017. Also set "Always Use" and "Do not warn".
If anyone facing this issue, while adding reference in console/windows applications, follow the below steps
Open "Developer Command Prompt for VS 2017" as Admin
CD into "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\PublicAssemblies"
Run "gacutil -i Microsoft.VisualStudio.Shell.Interop.11.0.dll"
Restart Visualstudio
Reference - https://developercommunity.visualstudio.com/t/add-a-reference-raise-error-error-hresult-e-fail-h/260196

Resources