I am trying to open more then one instance of tor browser with different identities with c#.
One of the brwoswers opens fine:
But when the code opens the second I get empty browser:
Here is my c# code:
IWebDriver browser;
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.proxy.type", 1);
profile.SetPreference("network.proxy.socks", "127.0.0.1");
profile.SetPreference("network.proxy.socks_port", 9150);
browser = new FirefoxDriver(profile);
// browser.Quit();
//Firefox's proxy driver executable is in a folder already
// on the host system's PATH environment variable.
browser.Navigate().GoToUrl("http://dnsleaktest.com");
//IWebElement header = browser.FindElement(By.Id(“site - header"));
//Assert.True(header.Displayed);
// browser.Close();
Thread.Sleep(10000);
IWebDriver browser2;
FirefoxProfile profile2 = new FirefoxProfile();
profile2.SetPreference("network.proxy.type", 1);
profile2.SetPreference("network.proxy.socks", "127.0.0.1");
profile2.SetPreference("network.proxy.socks_port", 9152);
browser2 = new FirefoxDriver(profile2);
// browser.Quit();
//Firefox's proxy driver executable is in a folder already
// on the host system's PATH environment variable.
browser.Navigate().GoToUrl("http://dnsleaktest.com");
//IWebElement header = browser.FindElement(By.Id(“site - header"));
//Assert.True(header.Displayed);
// browser.Close();
Please correct my English if needed
Related
I have 2 .NET Core 2.0 console applications. The first application calls the second one via System.Diagnostics.Process.Start(). Somehow the second app is inheriting the development configuration information located in the appsettings.development.json of the first app.
I execute the first app by running either dotnet run in the root of the project or dotnet firstapp.dll in the folder where the DLL exists. This is started from in Powershell.
Both apps are separate directories. I'm not sure how this is happening.
UPDATE WITH CODE
The apps reside in
C:\Projects\ParentConsoleApp
C:\Projects\ChildConsoleApp
This is how I call the app from parent application:
System.Diagnostics.Process.Start("dotnet", "C:\\projects\\ChildConsoleApp\\bin\\Debug\\netcoreapp2.0\\publish\\ChildConsoleApp.dll" + $" -dt {DateTime.Now.Date.ToString("yyyy-MM-dd")}");
This is how I load the configuration from JSON (this is same in both apps):
class Program
{
private static ILogger<Program> _logger;
public static IConfigurationRoot _configuration;
public static IServiceProvider Container { get; private set; }
static void Main(string[] args)
{
RegisterServices();
_logger = Container.GetRequiredService<ILogger<Program>>();
_logger.LogInformation("Starting GICMON Count Scheduler Service");
Configure();
// At this point DBContext has value from parent! :(
var repo = Container.GetService<ICountRepository>();
var results = repo.Count(_configuration.GetConnectionString("DBContext"), args[0]);
}
private static void Configure()
{
string envvar = "DOTNET_ENVIRONMENT";
string env = Environment.GetEnvironmentVariable(envvar);
if (String.IsNullOrWhiteSpace(env))
throw new ArgumentNullException("DOTNET_ENVIRONMENT", "Environment variable not found.");
_logger.LogInformation($"DOTNET_ENVIRONMENT environment variable value is: {env}.");
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
if (!String.IsNullOrWhiteSpace(env)) // environment == "Development"
{
builder.AddJsonFile($"appsettings.{env}.json", optional: true);
}
_configuration = builder.Build();
}
private static void RegisterServices()
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("nlog.config");
Container = serviceProvider;
}
}
The problem is caused by the fact that you set base path for configuration builder to the current working directory:
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
When you create a child process, it inherits current directory from the parent process (unless you set current directory explicitly).
So the child process basically uses JSON configs from the directory of parent process.
There are several possible fixes:
Do not set base path to the current directory.
When the application is launched, you don't know for sure that current directory will match directory where application binaries are placed.
If you have an exe file in c:\test\SomeApp.exe and launch it from the command line while the current directory is c:\, then current directory of your application will be c:\. In this case, if you set base path for configuration builder to current directory, it will not be able to load configuration files.
By default, configuration builder loads config files from AppContext.BaseDirectory which is the directory where application binaries are placed. It should be desired behavior in most cases.
So just remove SetBasePath() call:
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
If for some reason you want to set the base path of configuration builder to the current directory, then you should set correct current directory for the launched child process:
var childDllPath = "C:\\projects\\ChildConsoleApp\\bin\\Debug\\netcoreapp2.0\\publish\\ChildConsoleApp.dll";
var startInfo = new ProcessStartInfo("dotnet", childDllPath + $" -dt {DateTime.Now.Date.ToString("yyyy-MM-dd")}")
{
WorkingDirectory = Path.GetDirectoryName(childDllPath),
};
Process.Start(startInfo);
As #CodeFuller explained, the reason is that both apps read the same appsettings.{env}.json file. For simplicity, you may just rename the config file (and the corresponding name in .AddJsonFile) for the second app to prevent any possible overrides.
See, when you register JSON file as a configuration source by .AddJsonFile, configuration API allows you to use whatever file name you need and
you are not forced to use the same $"appsettings.{env}.json" pattern for both applications.
From the command line I can successfully connect via FTP to my host using either
ftp.domain.com or domain.com
C:\Users\Aaron>ftp
ftp> open
To domain.com
Connected to domain.com.
220 FTP Server ready.
User (domain.com:(none)): Login failed.
ftp> close
221 Goodbye.
ftp> open
To ftp.domain.com
Connected to ftp.domain.com.
220 FTP Server ready.
User (ftp.domain.com:(none)): Login failed.
ftp> close
221 Goodbye.
ftp> quit
I escaped entering the password above and scrubbed the domain, but it still shows for each connection I was successful. When I run this code in Visual studio, I get the invalid URI.
Here is my code I've tried in C#
Uri target = new Uri("ftp://ftp.domain.com/");
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(target);
requestDir.Credentials = new NetworkCredential("user", "pass");
Uri target = new Uri("ftp://ftp.domain.com/");
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(target);
requestDir.Credentials = new NetworkCredential("user", "pass");
The requested URI is invalid for this FTP command
I've looked on here as there are many like this, but I've tried all of them (I think) and I just keep on getting this error. Any ideas?
Thanks!
I was able to get it working with the help of some other posts here and a lot of troubleshooting. I now have this working and have moved on to new errors. Here is the code for the successful FTP upload:
reqCakes = (FtpWebRequest)WebRequest.Create("ftp://domain.com/images/" + "koala.jpg");
reqCakes.UseBinary = true;
reqCakes.Method = WebRequestMethods.Ftp.UploadFile;
reqCakes.Credentials = new NetworkCredential("user", "pass");
BinaryReader rdrCakes = new BinaryReader(File.Open(fileToOpen, FileMode.Open));
rdrCakes.Close();
byte[] cakeData = File.ReadAllBytes(fileToOpen);
reqCakes.ContentLength = cakeData.Length;
Stream reqStream = reqCakes.GetRequestStream();
reqStream.Write(cakeData, 0, cakeData.Length);
reqStream.Close();
What I'm trying to do in SSIS is have a WMI Event Watcher Task which watches a folder for a file to be created, then does something with it. The primary part is the "watching the folder for file creation".
I have a network folder (full path): \\srvblah10\main\child\target\
All the sites I've gone to has this as an example:
SELECT * FROM __InstanceCreationEvent WITHIN 10
WHERE TargetInstance ISA "CIM_DirectoryContainsFile"
AND TargetInstance.GroupComponent = "Win32_Directory.Name=\"d:\\\\NewFiles\""
Since the folder is a network folder, I can't provide the physical disk letter. So is there a way to use a similar WQL query but for network folder paths as opposed to physical folder paths?
You have to map the drive with a dos command:
net use s: \srvblah10\main\child\target\ /user dotnetN00b Pa$$word
then you can the WMI Event Watcher Task to watch it.
I was trying to do this for awhile, and finally gave up on trying to use the SSIS WMI Event Watcher task, and just wrote the equivalent in a Script task. The issue that was the challenge was getting the WMI Event Watcher to make the remote connection with specific user credentials that I wanted to obtain from a configuration section (not hard code into the package).
The second issue that was going to make not using a script difficult was simply translating the network share, into the local path name on the server, which the Event Watcher requires. You'll see from the scrip below, everything is accomplished with a minimal of effort.
Just an additional heads up, make sure to include the DTS.Variables the script uses in the ReadOnlyVariables (as normal). The code below requires three DTS variables, for example if you are trying to watch for files being dropped in the following location \copernicus\dropoff\SAP\Import, then you would set the variables as shown below:
User::ServerName - the hostname of the server where the share lives
(copernicus)
User::ShareName - the name of the network share
(dropoff)
User::ImportPath - the directory path of the directory to
watch for new files in (/SAP/Import)
public void Main()
{
string localPath = "";
try
{
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "<valid username here>";
connection.Password = "<password here>";
connection.Authority = "ntlmdomain:<your domain name here>";
ManagementScope scope = new ManagementScope(#"\\" + Dts.Variables["User::FileServerName"].Value.ToString() + #"\root\CIMV2", connection);
scope.Connect();
/// Retrieve the local path of the network share from the file server
///
string queryStr = string.Format("SELECT Path FROM Win32_Share WHERE Name='{0}'", Dts.Variables["User::ShareName"].Value.ToString());
ManagementObjectSearcher mosLocalPath = new ManagementObjectSearcher(scope, new ObjectQuery(queryStr));
foreach (ManagementObject elements in mosLocalPath.Get())
{
localPath = elements["Path"].ToString();
}
queryStr = string.Format(
"SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent=\"Win32_Directory.Name='{0}{1}'\"",
localPath.Replace(#"\", #"\\"),
Dts.Variables["User::ImportPath"].Value.ToString().Replace(#"\", #"\\")); // query requires each seperator to be a double back slash
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, new WqlEventQuery(queryStr));
ManagementBaseObject eventObj = watcher.WaitForNextEvent();
// Cancel the event subscription
watcher.Stop();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (ManagementException err)
{
Dts.Events.FireError((int)err.ErrorCode, "WMI File Watcher", "An error occurred while trying to receive an event: " + err.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
Dts.Events.FireError((int)ManagementStatus.AccessDenied, "WMI File Watcher", "Connection error (user name or password might be incorrect): " + unauthorizedErr.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
I am using following method to save a recording of microphone in WP8 to a file:
private void SaveToIsolatedStorage()
{
// first, we grab the current apps isolated storage handle
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
// we give our file a filename
string strSaveName = "myFile.wav";
// if that file exists...
if (isf.FileExists(strSaveName))
{
// then delete it
isf.DeleteFile(strSaveName);
}
// now we set up an isolated storage stream to point to store our data
IsolatedStorageFileStream isfStream =
new IsolatedStorageFileStream(strSaveName,
FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(stream.ToArray(), 0, stream.ToArray().Length);
// ok, done with isolated storage... so close it
isfStream.Close();
}
The file is saved. However, I do not know where does it save it, and how can I access it.
I wish to permanently save it to the device so I can access it from outside the app (Let's say from a file explorer app, or from the music player app).
Thanks
Use this code to get saved file name from isolated storage and use this to read this file from stored loacation:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
String[] filenames=myIsolatedStorage.GetFileNames();
Following methods are not working properly.
Since GRID is used, capability is set as null here.
System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
DesiredCapabilities capability=null;
Method 1:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--user-data-dir=C:/Users /username/AppData/Local/Google/Chrome/User Data/Default"));
driver = new ChromeDriver(capabilities);
Method 2:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
String chromeProfile = "C:/Users/username/AppData/Local/Google/Chrome/Application /chrome.exe";
ArrayList<String> switches = new ArrayList<String>();
switches.add("C:/Users/username/AppData/Local/Google/Chrome/User Data/Default" + chromeProfile);
capabilities.setCapability("chrome.switches", switches);
driver = new ChromeDriver(capabilities);
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
If you face such error:
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally
Then try to create a new Chrome profile and execute tests.
Copy the folder, 'User Data'
Paste & Rename the folder on the same location. e.g., New User
Now, locate the directory, C:/Users/user_name/AppData/Local/Google/Chrome/New User
If you like to test the profile, then bookmark some of the sites & observe them on next run.
1 Set the chromedriver property in starting the node. My approach:
java -jar selenium-server-standalone-2.31.0.jar -role node -hub http://localhost:4444/grid/register -maxSession 15 -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=15 -Dwebdriver.chrome.driver=lib\chromedriver.exe
2 Inside the code my approach:
capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub"), capabilities);
3 loading the HTTP basic auth page:
String username = "Pavel";
String password = "Omgtoosecrettotellyou";
driver.get("http://" + username + ":" + password + "#" +"your-site.com");