How to create Instance of google chrome in C# - c#

I want to create an object for google chrome and do like this.
dynamic browserId = Type.GetTypeFromProgID("InternetExplorer.Application.1");
dynamic ie = Activator.CreateInstance(browserId);
ie.AddressBar = true;
ie.MenuBar = false;
ie.ToolBar = false;
ie.StatusBar = false;
ie.MenuBar = false;
ie.Visible = true;
ie.Navigate("www.stackoverflow.com/");
Above code is working but I want to do same for google chrome.

Open in default browser (Best Idea!)
Process.Start("http://www.stackoverflow.net");
open in Internet Explorer
Process.Start("iexplore", #"http://www.stackoverflow.net/");
open in Firefox
Process.Start("firefox", #"http://www.stackoverflow.net/");
open in Google Chrome
Process.Start("chrome", #"http://www.stackoverflow.net/");

Related

Internet Explorer 11 Click problem on Xunit

I am using Windows 10 with IE11 on selenium XUNIT test. Selenium doesn't click at a desired IE element. Can someone suggest a solution please?
We had similar problem back in the day when the change the webdriver for IE, whit this code I can run it only in some computers, because in another's we have a lost of comunication between IE and the driver/code due another problem.
public static IWebDriver ExplorerDriverSetUp()
{
var options = new InternetExplorerOptions();
options.RequireWindowFocus = false;
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
options.IgnoreZoomLevel = true;
options.EnsureCleanSession = true;
options.InitialBrowserUrl = URL;
IWebDriver driver = new InternetExplorerDriver(options);
driver.Manage().Window.Maximize();
return driver;
}

Run Selenium InternetExplorerDriver test with add-on (plugin) enabled

Trying to run my tests on IE. I need our plugin to be enabled.
Here is my code written in C#
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
options.UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Accept;
options.IgnoreZoomLevel = true;
options.EnsureCleanSession = true;
options.EnableNativeEvents = true;
driver = new InternetExplorerDriver(options);
If run under Selenium the plugin is seen as inactive and the site asks to download the plugin.
How can I make InternetExplorerDriver enable my plugin?
Is there smth like options.PluginsEnabled = true ???
Any ideas?

How to authenticate (user/password) proxy in c# selenium chrome driver

I have a HTTP/HTTPS proxy which need to authenticate using username and password. How do I do that using C# selenium chrome webdriver?
string host = proxies[count].Split(':')[0];
int port = Convert.ToInt32(proxies[count].Split(':')[1]) + 1;
string prox = host + ":" + port.ToString();
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy = prox;
proxy.SslProxy = prox;
options.Proxy = proxy;
options is the ChromeOptions class which I assign to the driver.
I created little package for yor problem (https://github.com/RDavydenko/OpenQA.Selenium.Chrome.ChromeDriverExtensions)
Install Package:
Install-Package OpenQA.Selenium.Chrome.ChromeDriverExtensions -Version 1.2.0
Use for your ChromeOptions:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chrome.ChromeDriverExtensions;
...
var options = new ChromeOptions();
// Add your HTTP-Proxy
options.AddHttpProxy(PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD);
var driver = new ChromeDriver(options); // or new ChromeDriver(AppDomain.CurrentDomain.BaseDirectory, options);
driver.Navigate().GoToUrl("https://whatismyipaddress.com/"); // Check your IP
Instead of PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD, use the parameters of your proxy
The only successful approach I have found is to use AutoIT ( https://www.autoitscript.com/site/autoit ).
I have mine setup for proxy authentication for all of the major browsers, but this should work for Chrome.
I wrote this on my phone from memory. If it doesn't work let me know and I'll correct.
WinWait("data:, - Google Chrome","","10")
If WinExists("data:, - Google Chrome","")Then
WinActivate("data:, - Google Chrome")
Send("USERNAMEGOESHERE"{TAB}")
Send("USERPASSWORDGOESHERE"{ENTER}")
Using AutoIT, create this as a script, compile it to exe, save it somewhere and reference the file with the following (Java code):
Runtime.getRuntime().exec("C:\\users\\USERID\\desktop\\FILENAME.exe");
I find it best to call the proxy script a step BEFORE you call the URL that triggers the proxy auth.
2019 Update
After multiple unfortunate attempts, the easiest solution is to create an extension for Chrome as explained by Mike in this post.
It sounds freaky, but it is actually really straightforward.
2021 Update
I have created a simple library (nuget package) that helps you with selenium proxy authentication. You can check the source at Github repo. It also works when using driver headless.
Usage:
public void Test()
{
// Create a local proxy server
var proxyServer = new SeleniumProxyAuth();
// Don't await, have multiple drivers at once using the local proxy server
TestSeleniumProxyServer(proxyServer, new ProxyAuth("123.123.123.123", 80, "prox-username1", "proxy-password1"));
TestSeleniumProxyServer(proxyServer, new ProxyAuth("11.22.33.44", 80, "prox-username2", "proxy-password2"));
TestSeleniumProxyServer(proxyServer, new ProxyAuth("111.222.222.111", 80, "prox-username3", "proxy-password3"));
while (true) { }
}
private async Task TestSeleniumProxyServer(SeleniumProxyAuth proxyServer, ProxyAuth auth)
{
// Add a new local proxy server endpoint
var localPort = proxyServer.AddEndpoint(auth);
ChromeOptions options = new ChromeOptions();
//options1.AddArguments("headless");
// Configure the driver's proxy server to the local endpoint port
options.AddArgument($"--proxy-server=127.0.0.1:{localPort}");
// Optional
var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
// Create the driver
var driver = new ChromeDriver(service, options);
// Test if the driver is working correctly
driver.Navigate().GoToUrl("https://www.myip.com/");
await Task.Delay(5000);
driver.Navigate().GoToUrl("https://amibehindaproxy.com/");
await Task.Delay(5000);
// Dispose the driver
driver.Dispose();
}
This is for firefox but the top answer might help.
C# Selenium WebDriver FireFox Profile - using proxy with Authentication
What you can do is to create a profile and save the authentication data in it. If your profile is called "webdriver" you can select it from your code in the initialization:
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("WebDriver");
profile.setPreferences("foo.bar",23);
WebDriver driver = new FirefoxDriver(profile);
Chrome won't let you use any extension for selenium web testing these days. And selenium doesn't have any built in username & password input for proxies.
The only solution I found is using AutoIt. It will automates windows level actions. While selenium only automates browser level actions.
Passing username and password to the proxy dialog box is A WINDOWS LEVEL ACTION.
To download and install AutoIt, you can go to : https://www.guru99.com/use-autoit-selenium.html
I wrote a simple AutoIt script as below :
; option to read substring in a window title
Opt("WinTitleMatchMode", 2)
; wait for proxy username & password dialog box
WinWait("- Google Chrome","","10")
; if the box shows up, write the username and password
; username & password are passed as program parameters
If WinExists("- Google Chrome","") Then
WinActivate("- Google Chrome")
; $CmdLine is a special array that holds parameters
if $CmdLine[0] = 2 Then
Send($CmdLine[1] & "{TAB}")
Send($CmdLine[2] & "{ENTER}")
EndIf
; any request dialog to save credential?
WinWait("Save password for ","","10")
; if any, close it
If WinExists("Save password for ","") Then
WinActivate("Save password for ")
Send("{TAB}")
Send("{SPACE}")
EndIf
EndIf
Exit
Compile the script to be an executable program as ProxyAuth.exe.
The program will receive two parameters : username and password.
With parameters, you can use dynamic username & password in your C# script.
Then you need to use the program in C# code as below :
ChromeOptions ChromeOptions = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = $"{ProxyIP}:{ProxyPort}";
proxy.HttpProxy = $"{ProxyIP}:{ProxyPort}";
ChromeOptions.Proxy = proxy;
ChromeOptions.AddArgument("ignore-certificate-errors");
Driver = new ChromeDriver(ChromeOptions);
Driver.Navigate().GoToUrl(Url);
string cmd = string.Format($"{ProxyUsername} {ProxyPassword}");
Process proc = new Process();
proc.StartInfo.FileName = "ProxyAuth.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
You will need to use OpenQA.Selenium, OpenQA.Selenium.Chrome, and System.Diagnostics namespaces.
** EDIT **
If you interested in using AutoIt, you can also use their library in NuGet. Just search in "Manage NuGet Packages" : AutoIt. Choose the one and only one AutoIt package shown and install it.
With this library, you don't need to create ProxyAuth.exe application as described above.
You can use the AutoIt library and make modifications in the C# code :
ChromeOptions ChromeOptions = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = $"{ProxyIP}:{ProxyPort}";
proxy.HttpProxy = $"{ProxyIP}:{ProxyPort}";
ChromeOptions.Proxy = proxy;
ChromeOptions.AddArgument("ignore-certificate-errors");
Driver = new ChromeDriver(ChromeOptions);
Driver.Navigate().GoToUrl(Url);
// use the AutoIt library
AutoItX.AutoItSetOption("WinTitleMatchMode", 2);
AutoItX.WinWaitActive("- Google Chrome", "", 10);
AutoItX.WinActivate("- Google Chrome");
AutoItX.Send(ProxyUsername);
AutoItX.Send("{TAB}");
AutoItX.Send(ProxyPassword);
AutoItX.Send("{ENTER}");
// dismiss save password prompt
AutoItX.WinWaitActive("Save password for ", "", 10);
AutoItX.WinActivate("Save password for ");
AutoItX.Send("{TAB}");
AutoItX.Send("{SPACE}");
Answered in another thread C# Selenium Proxy Authentication with Chrome Driver.
Main idea - use Selenium 4.0 and BiDi APIs.

Launching a RemoteApp programmatically without a system call to "mstsc"

I've an RDP file that successfully start a RemoteApp.
remoteapplicationmode:i:1
remoteapplicationprogram:s:||application
remoteapplicationname:s:application.exe
remoteapplicationcmdline:s:
authentication level:i:2
gatewayusagemethod:i:2
gatewayprofileusagemethod:i:1
gatewaycredentialssource:i:0
full address:s:aaa.bbb.ccc.com
I tried to copy its settings into my C# objects:
AxMsRdpClient7NotSafeForScripting rc = new AxMsRdpClient7NotSafeForScripting();
rc.OnConnected += (_1, _2) => { rc.RemoteProgram2.ServerStartProgram("application.exe", "", "%HOMEDRIVE%" + "%HOMEPATH%", true, "", true); };
rc.RemoteProgram2.RemoteProgramMode = true;
rc.RemoteProgram2.RemoteApplicationProgram = "||application";
rc.RemoteProgram2.RemoteApplicationName = "application.exe";
rc.TransportSettings.GatewayUsageMethod = 1;
rc.TransportSettings.GatewayProfileUsageMethod = 1;
rc.TransportSettings.GatewayCredsSource = 0;
rc.Server = "aaa.bbb.ccc.com";
rc.UserName = "DOMAIN\\user";
rc.AdvancedSettings7.PublicMode = false;
rc.AdvancedSettings7.ClearTextPassword = "pass";
rc.AdvancedSettings7.AuthenticationLevel = 2;
rc.DesktopWidth = SystemInformation.VirtualScreen.Width;
rc.DesktopHeight = SystemInformation.VirtualScreen.Height;
rc.AdvancedSettings7.SmartSizing = true;
rc.Connect();
I've been searching everywhere but I wasn't able to find any example of how to launch a RemoteApp programmatically.
I've red this page, but it was not very helpfull. The client (a COM control) is connecting successfully, but it just displays a blue screen and no RemoteApp is launched.
Furthermore, I'm not sure that the right method to launch rc.RemoteProgram2.ServerStartProgram, because it takes paths as arguments, while in my RDP file no path is present!
Can anyone help me? I'm using the right objects to do what I want?
The server runs Windows Server 2008R2
If all you want to do is pragmatically launch a RemoteApp you already have an rdp file for, then just start it as a process:
System.Diagnostics.Process.Start(#"C:\Path_To_Rdp_File.rdp");

Printing a pdf file on client side printer in asp.net C#?

I have a problem in my project that i open a dynamically generated PDF file in popup window which working correctly. But now i want to print that pdf directly when popup is open at client side printer, how can i solved it ??
I need help of yours. Please suggest me some code for this.
You need to open the popup with javascript and the fire the print() function on it.
var opts = 'width=700,height=500,toolbar=0,menubar=0,location=1,status=1,scrollbars=1,resizable=1,left=0,top=0';
var newWindow = window.open(yourUrl,'name',opts);
newWindow.print();
Note that the url you open must be in the same domain as your current page for this to work.
Try This Code It will Work For You.
Process printjob = new Process();
printjob.StartInfo.FileName = #"D:\R&D\Changes to be made.pdf" //path of your file;
printjob.StartInfo.Verb = "Print";
printjob.StartInfo.CreateNoWindow = true;
printjob.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
PrinterSettings setting = new PrinterSettings();
setting.DefaultPageSettings.Landscape = true;
printjob.Start();

Categories