I am trying to run automated selenium tests remotely using Browser stack local interacting with localhost. I get the following error:
Eror while executing BrowserStackLocal start {"state":"disconnected","pid":7512,"message":{"genre":"error","message":"Could not connect to Files!"}}
then I specify a log file, it then says:
BrowserStackLocal start {"state":"disconnected","pid":18308,"message":{"genre":"error","message":"Could not connect to -logFile!"}}
It hangs on this line with no further progress:
browserStackLocal.start(localArgs);
My code is as follows:
var capability = GetBrowserStackCapabilities();
SetBrowserStackLocal(capability);
webDriver = new RemoteWebDriver(new Uri("http://" + ConfigurationManager.AppSettings.Get("BrowserStackServer") + "/wd/hub/"), capability);
private static DesiredCapabilities GetBrowserStackCapabilities()
{
var profile = ConfigurationManager.AppSettings.Get("BrowserStackProfile");
NameValueCollection caps = ConfigurationManager.GetSection(string.Format("capabilities/{0}", profile)) as NameValueCollection;
var environment = ConfigurationManager.AppSettings.Get("BrowserStackEnvironment");
NameValueCollection settings = ConfigurationManager.GetSection(string.Format("environments/{0}", environment)) as NameValueCollection;
DesiredCapabilities capability = new DesiredCapabilities();
if (caps != null)
{
foreach (string key in caps.AllKeys)
{
capability.SetCapability(key, caps[key]);
}
}
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
capability.SetCapability(key, settings[key]);
}
}
string username = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME") ?? ConfigurationManager.AppSettings.Get("BrowserStackUser");
string accesskey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY") ?? ConfigurationManager.AppSettings.Get("BrowserStackKey");
capability.SetCapability("browserstack.user", username);
capability.SetCapability("browserstack.key", accesskey);
return capability;
}
private static void SetBrowserStackLocal(DesiredCapabilities capability)
{
if (capability.GetCapability("browserstack.local") != null && capability.GetCapability("browserstack.local").ToString() == "true")
{
var browserStackLocal = new Local();
string accesskey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY") ?? ConfigurationManager.AppSettings.Get("BrowserStackKey");
List<KeyValuePair<string, string>> localArgs = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("key", accesskey),
new KeyValuePair<string, string>("logFile", "C:/Temp/logfile.txt"),
new KeyValuePair<string, string>("force", "true")
};
browserStackLocal.start(localArgs);
FeatureContext.Current.SetBrowserStackLocal(browserStackLocal);
}
}
My config is as follows:
<appSettings>
<add key="BrowserStackUser" value="<redacted>" />
<add key="BrowserStackKey" value="<redacted>/>
<add key="BrowserStackServer" value="hub-cloud.browserstack.com" />
<add key="BrowserStackProfile" value="single" />
<add key="BrowserStackEnvironment" value="ie11" />
</appSettings>
<capabilities>
<single>
<add key="browserstack.debug" value="true" />
<add key="browserstack.local" value="true" />
</single>
</capabilities>
<environments>
<ie11>
<add key="os" value="Windows" />
<add key="os_version" value="8.1" />
<add key="browser" value="IE" />
<add key="browser_version" value="11.0" />
<add key="resolution" value="1024x768" />
</ie11>
</environments>
How can I get past browser stack local hanging and start remote testing with a local server?
The error "Could not connect to -logFile!" is due to incorrect parameter "logFile". The correct parameter is "logfile" (all in lower case). You should check BrowserStack's documentation here - https://github.com/browserstack/browserstack-local-csharp#logfile.
Here is a working snippet for Browserstack local C# bindings:
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using BrowserStack;
using System.Collections.Generic;
using OpenQA.Selenium.Chrome;
using System.Threading;
namespace BrowserStackLocalSample
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
var browserStackLocal = new Local();
List<KeyValuePair<string, string>> bsLocalArgs = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("key", "<access_key>"),
new KeyValuePair<string, string>("logfile", "path_To_log/log.txt"),
//new KeyValuePair<string, string>("binarypath", "/Tools/local/BrowserStackLocal"),
new KeyValuePair<string, string>("force", "true"),
};
browserStackLocal.start(bsLocalArgs);
Thread.Sleep(15000);
DesiredCapabilities capability = new DesiredCapabilities();
capability.SetCapability("browser", "Chrome");
capability.SetCapability("browser_version", "62.0");
capability.SetCapability("os", "Windows");
capability.SetCapability("os_version", "7");
capability.SetCapability("resolution", "1024x768");
capability.SetCapability("browserstack.local", "true");
capability.SetCapability("browserstack.user", "<username>");
capability.SetCapability("browserstack.key", "<access_key>");
driver = new RemoteWebDriver(
new Uri("http://hub.browserstack.com/wd/hub/"), capability
);
driver.Navigate().GoToUrl("http://localhost:45691/check");
Console.WriteLine(driver.Title);
driver.Quit();
browserStackLocal.stop();
}
}
}
Related
Config that I set connectionstring to:
<connectionStrings>
<add name="default" connectionString="data source=database\data.db;" providerName="System.Data.SQLite" />
</connectionStrings>
But in myDbContext I change my database location to :
base.Database.Connection.ConnectionString = #"data source=" + AppVariable.myPath + #"database\data.db;";
After that when my app launch my tables are not created, where is the problem?
extract from my code with nuget package...no need of connection string and datasource...
using SQLite;
public string SQLitePath => Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "xxxxx.sqlite");
try
{
using (var db = new SQLiteConnection(SQLitePath) { Trace = IsDebug })
{
List<TargetModel> test = db.Table<TargetModel>().Select(p => p).ToList();
return test;
}
}
catch (Exception ex)
{
BusinessLogger.Manage(ex);
return null;
}
I got this assignment where my assignment is to reboot a remote computer which isn't in any AD nor on my local network/ Domain.
Currently I am capable of checking whether or not the IP-address and port is active. What I want is to be able to call a shutdown function directly on the remote computer. However it appears as if most of the solutions on the web, which I'm capable of finding, isn't working when the computer isn't in your local network or domain.
Here's the current code used:
Program.cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CPMSMonitor
{
class Program
{
static void Main(string[] args)
{
TestConnection();
Console.ReadKey();
}
static IEnumerable<String> GetConfig()
{
var list = new List<String>();
for (int i = 1; i < 10; i++)
{
var settingValue = ConfigurationManager.AppSettings[$"PC{i}"];
if (string.IsNullOrWhiteSpace(settingValue))
{
break;
}
else
{
list.Add(settingValue);
}
}
return list;
}
private static HttpClient BuildHttpClient(string endPoint)
{
var client = new HttpClient { BaseAddress = new Uri("http://" + endPoint) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
static void TestConnection()
{
var timer = 1000;
if (!int.TryParse(ConfigurationManager.AppSettings.Get("IntervalTimer"), out timer))
{
timer = 1000;
}
var machines = GetConfig();
var client = BuildHttpClient(machines.First());
while (true)
{
foreach (var item in machines)
{
try
{
client.BaseAddress = new Uri("http://" + item);
var httpResponse = client.GetAsync("/").GetAwaiter().GetResult();
var html = httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine(item + " | Status: Online");
}
catch {
Process.Start("Shutdown.exe", "-r");
// use PsShutdown to reboot machine
// call to IP failed
}
}
Thread.Sleep(timer);
}
}
}
}
App.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/>
</startup>
<appSettings>
<add key="PC1" value="192.168.195.65:8080"/>
<add key="PC2" value="192.168.195.65:8081"/>
<add key="IntervalTimer" value="500"/>
</appSettings>
</configuration>
Do you guys have any idea how to call a system function in which the administrative access is granted and the computer afterwards reboots?
PsShutdown, PsExec and even Azure apps has been attempted, though failing.
Any ideas?
Thanks!
Update:
As suggested I changed my Startup.auth.cs to code below
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
public static readonly string Authority = aadInstance + tenantId;
// This is the resource ID of the AAD Graph API. We'll need this to request a token to call the Graph API.
string graphResourceId = "https://graph.windows.net";
public void ConfigureAuth(IAppBuilder app)
{
ApplicationDbContext db = new ApplicationDbContext();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
AuthenticationResult result =
authContext.AcquireTokenByAuthorizationCode(
code,
new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
credential,
graphResourceId);
return Task.FromResult(0);
},
RedirectToIdentityProvider = context =>
{
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
string currentUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.Path;
context.ProtocolMessage.RedirectUri = currentUrl;
context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
return Task.FromResult(0);
}
}
});
}
}
And now I have this:
Sometimes a DbEntityValidationException happens on my ApplicationDbContext (used to store ADALTokenCache)
When coding a web application using Azure AD ou Office 365 for user authentication you need to create a application key and configure an url for Azure redirect to your application after login.
This url should be configured in web.config, but Azure AD ignores URI parameter that your application sends and redirects you to production URI instead of development URI.
my development url: https://localhost:44315/
production url: http://timesheet.tecnun.com.br/
the application ignores web.config and redirects to production url always
web.config:
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:ClientId" value="xxxxx" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="ida:ClientSecret" value="xxxx" />
<add key="ida:Domain" value="tecnun.com.br" />
<add key="ida:TenantId" value="xxx" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:44315/" />
</appSettings>
my azure configuration:
Id like to work with two environments, development and production/real. But I can't find out how to do this without creating two applications.
To make the same application works for the different redirect URL, we can change it dynamically before the web app redirect to the identity data provider.
Here is the code sample for your reference:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider=context=>
{
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
string currentUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.Path;
context.ProtocolMessage.RedirectUri = currentUrl;
context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
return Task.FromResult(0);
}
}
});
I have 3 different folders in TFS : tables, scripts and objects.
I Want to loop through three folders to get the file contents and execute them in the SQL server in the order tables, scripts and objects using C#. Want to make it configuration based.
Can anybody help me out with this?
Code:
class Program
{
public void DownloadFiles()
{
string teamProjectCollectionUrl = "";
string serverPath = ConfigurationManager.AppSettings["key2"];
string localPath = ConfigurationManager.AppSettings["key1"];
TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamProjectCollectionUrl));
VersionControlServer versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
foreach (Item item in versionControlServer.GetItems(serverPath, VersionSpec.Latest, RecursionType.Full, DeletedState.NonDeleted, ItemType.File, true).Items)
{
string target = Path.Combine(localPath, item.ServerItem.Substring(2));
if (item.ItemType == ItemType.Folder && !Directory.Exists(target))
{
Directory.CreateDirectory(target);
Console.WriteLine("Created the target folder");
}
else if (item.ItemType == ItemType.File)
{
item.DownloadFile(target);
}
}
Console.WriteLine("Downloaded files from TFS");
ExecuteFiles();
}
public void ExecuteFiles()
{
var connectionString = ConfigurationManager.ConnectionStrings["Conn1"].ToString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
foreach (string file in Directory.GetFiles(ConfigurationManager.AppSettings["key1"], "*.sql", SearchOption.AllDirectories))
{
string contents = File.ReadAllText(file);
Console.WriteLine(file);
Console.WriteLine(contents);
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = contents;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
static void Main(string[] args)
{
Program obj = new Program();
obj.DownloadFiles();
Console.ReadLine();
}
}
Config File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="key1" value="C:\downloads"/>
<add key="key2" value="$/App1/Application"/>
</appSettings>
<connectionStrings>
<add name="Conn1" connectionString="Data Source=Server_Name;Initial Catalog=db_Name;Integrated Security=True"/>
</connectionStrings>
</configuration>
I'm developing android app on Xamarin Android in c#.
Is there any way to change dynamically URL of SOAP web service? I want to store url in some kind of config file but I have no idea how do it.
correct me, if i'm wrong
but the second constructor of an xamarin - soap webservice class has a property for URL.
Here's an example of my webservice:
public partial class Service : System.Web.Services.Protocols.SoapHttpClientProtocol
{
public Service()
{
this.Url = "http://xxx/service.asmx";
}
public Service(string url)
{
this.Url = url;
}
}
you've added the webreference in xamarin and then use your webservice - instance.
Just call the second constructor and give them an other url as source.
You could manually create your required connection using Channelfactory that changes as it needs to. You'll need the proper connections in the web.config file.
Here's a way you could set it up.
In your web.config.
<appSettings>
<add key="Identity" value="machineidentity" />
<add key="Binding" value="WSHttpBinding_IService" />
<add key="Endpoint" value="http://Devservice/Service.svc" />
<add key="Identity2" value="localmachine" />
<add key="Binding2" value="WSHttpBinding_IService" />
<add key="Endpoint2" value="http://Devservice/Service.svc" />
<add key="devIdentity" value="localmachine" />
<add key="devBinding" value="WSHttpBinding_IService" />
<add key="devEndpoint" value="http://Devservice/Service.svc" />
</appSettings>
C# code
a configuration class to hold values from the web.config
public static Dictionary<int, Connections> EndpointConnections = new Dictionary<int, Connections>
{
{1, new Connections(){Identity = ConfigurationManager.AppSettings["Identity"],Binding = ConfigurationManager.AppSettings["Binding"], Endpoint = ConfigurationManager.AppSettings["Endpoint"]}},
{2, new Connections(){Identity = ConfigurationManager.AppSettings["Identity2"],Binding = ConfigurationManager.AppSettings["Binding2"], Endpoint = ConfigurationManager.AppSettings["Endpoint2"]}},
{3, new Connections(){Identity = ConfigurationManager.AppSettings["devIdentity"],Binding = ConfigurationManager.AppSettings["devBinding"], Endpoint = ConfigurationManager.AppSettings["devEndpoint"]}},
};
Now a static class for creating the endpoint
private ChannelFactory<IService> SetChannelFactory(int configInput)
{
var identity = EndpointIdentity.CreateDnsIdentity(Configuration.EndpointConnections[configInput].Identity);
var myBinding = new WSHttpBinding(Configuration.EndpointConnections[configInput].Binding);
var myuri = new Uri(Configuration.EndpointConnections[configInput].Endpoint);
var myEndpoint = new EndpointAddress(myuri, identity);
return new ChannelFactory<IService>(myBinding, myEndpoint);
}
Now calling and using the endpoint
public async Task<Result> SomeAction(int selection)
{
IService client = null;
Result result = null;
Response response = null;
using (var myChannelFactory = SetChannelFactory(selection))
{
try
{
client = myChannelFactory.CreateChannel();
response = await client.TheServiceFunction().ConfigureAwait(false);
((ICommunicationObject)client).Close();
}
catch
{
if (client != null)
{
((ICommunicationObject)client).Abort();
return new result ( failure = true);
}
}
}
if (response != null)
{
//Whatever you want to do with the response here
return new result ( failure = false);
}
}