Saucelabs Selenium not using proxy details for RemoteWebDriver (C#) - c#

I'm using the Saucelabs Selenium implementation to automate my testing across multiple devices and platforms.
Using the demo code from SauceLabs (below) doesn't work behind a proxy.
I've tried adding the proxy details to the DesiredCapibilities but this doesn't seem to do anything
[TestMethod]
public void TestSauceLabs()
{
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("browserName", "Safari");
caps.SetCapability("platform", "macOS 10.13");
caps.SetCapability("version", "11.1");
caps.SetCapability("username", _sauceUserName);
caps.SetCapability("accessKey", _sauceAccessKey);
caps.SetCapability("name", _name);
var tags = new List<string> {"demoTest", "sauceDemo"};
caps.SetCapability("tags", tags);
caps.SetCapability("maxDuration", 3600);
caps.SetCapability("commandTimeout", 600);
caps.SetCapability("idleTimeout", 1000);
caps.SetCapability("build", "SauceDemo");
/****************************************
* Edited demo code here
* Added proxy config to DesiredCapabilities **
*/
var proxy = new Proxy
{
IsAutoDetect = false,
HttpProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}",
SslProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}",
FtpProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}"
};
caps.SetCapability(CapabilityType.Proxy, proxy);
/*
*****************************************/
var uri = new Uri("https://ondemand.eu-central-1.saucelabs.com/wd/hub");
_driver = new RemoteWebDriver(uri,
caps, TimeSpan.FromSeconds(600));
_javascriptExecutor = ((IJavaScriptExecutor) _driver);
_javascriptExecutor.ExecuteScript("sauce:context=Open SauceDemo.com");
_driver.Navigate().GoToUrl(_url);
_javascriptExecutor.ExecuteScript("sauce:context=Sleep for 10000ms");
Thread.Sleep(10000);
Assert.IsTrue(true);
var passed = true;
_javascriptExecutor.ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}

Found the solution was to use the HttpCommandExecutor when using the RemoteWebDriver behind a proxy.
Here is my example code:
[TestMethod]
public void TestSauceLabs_Chrome()
{
var remoteOptions = new Dictionary<string, object>
{
{ "username", _sauceUserName },
{ "accessKey", _sauceAccessKey },
{ "name", _name },
{ "maxDuration", 3600 },
{ "commandTimeout", 600 },
{ "idleTimeout", 1000 }
};
var options = new ChromeOptions()
{
PlatformName = "Windows 10",
BrowserVersion = "latest"
};
//Remote options need to be global
options.AddAdditionalCapability("sauce:options", remoteOptions, true);
var caps = options.ToCapabilities();
/*
Using the HttpCommandExecutor persists the proxy details
and allows you to pass in credentials if required
*/
var executor = new HttpCommandExecutor(
new Uri("https://ondemand.eu-central-1.saucelabs.com/wd/hub"),
TimeSpan.FromSeconds(600))
{
Proxy = GenerateProxy()
};
_driver = new RemoteWebDriver(executor, caps);
_javascriptExecutor = ((IJavaScriptExecutor)_driver);
_javascriptExecutor.ExecuteScript($"sauce:context=Open {_url}");
_driver.Navigate().GoToUrl(_url);
_javascriptExecutor.ExecuteScript("sauce:context=Sleep for 10000ms");
Thread.Sleep(10000);
Assert.IsTrue(true);
var passed = true;
_javascriptExecutor.ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
public WebProxy GenerateProxy()
{
var proxy = new WebProxy
{
Address = new Uri($"{_proxyScheme}://{_proxyHost}:{_proxyPort}"),
BypassProxyOnLocal = false,
UseDefaultCredentials = _networkCredential != null,
Credentials = _networkCredential
};
return proxy;
}

Related

How to create k8s deployment using kubernetes-client in c#?

I'm getting Microsoft.Rest.HttpOperationException: 'Operation returned an invalid status code 'BadRequest'' on this line.
var result = client.CreateNamespacedDeployment(deployment, namespace);
Kubernetes-client has a small number of good resources and most of them is written in other language such as java and python. So i'm referring to these documentations.
this is my implementation so far.
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "extensions/v1beta1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "...",
NamespaceProperty = env,
Labels = new Dictionary<string, string>()
{
{ "app", "..." }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "...",
Image = "...",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
var result = client.CreateNamespacedDeployment(deployment, namespace);
I want to know the proper way on how to create kubernetes deployment using kubernetes-client, and also i want to know the cause of this issue.
For the full clarity and future visitors, it's worth to mention, what is exactly behind this bad request error (code: 400) returned from API server, when using your code sample:
"the API version in the data (extensions/v1beta1) does not match the expected API version (apps/v1)"
Solution:
ApiVersion = "extensions/v1beta1" -> ApiVersion = "apps/v1"
Full code sample:
private static void Main(string[] args)
{
var k8SClientConfig = new KubernetesClientConfiguration { Host = "http://127.0.0.1:8080" };
IKubernetes client = new Kubernetes(k8SClientConfig);
ListDeployments(client);
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "apps/v1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "nepomucen",
NamespaceProperty = null,
Labels = new Dictionary<string, string>()
{
{ "app", "nepomucen" }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "nginx",
Image = "nginx:1.7.9",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
Closing this issue (Resolved)
Reference: https://github.com/Azure/autorest/issues/931
Cause of issue: incorrect version of Kubernetes ApiVersion.
Solution: get and replace ApiVersion from kubernetes api.
Can also handle the exception using:
try
{
var result = client.CreateNamespacedDeployment(deployment, namespace);
}
catch (Microsoft.Rest.HttpOperationException httpOperationException)
{
var phase = httpOperationException.Response.ReasonPhrase;
var content = httpOperationException.Response.Content;
}

iewebdriverserver. Internet Explorer changes system proxy instead of browser proxy

IE changes the system proxy instead of the browser proxy, what can go wrong?
I tried changing the property UsePerProcessProxy, but it did not fix it.
Please see the code below
public InternetExplorerOptions GetOptions()
{
InternetExplorerOptions options = new InternetExplorerOptions
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
InitialBrowserUrl = "about:blank",
EnableNativeEvents = true,
EnsureCleanSession = true,
EnablePersistentHover = false,
PageLoadStrategy = InternetExplorerPageLoadStrategy.Normal,
};
options.UsePerProcessProxy = true;
options.Proxy = GetProxy();
return options;
}
public override IWebDriver CreateRemoteDriver()
{
var options = GetOptions();
foreach (var capability in CapabilityProperties)
{
options.AddAdditionalCapability(capability.Name, capability.Value);
}
return new RemoteWebDriver(new Uri(GridUri), options.ToCapabilities());
}
public Proxy GetProxy()
{
if (Proxy != null || ProxyAutoConfigUrl != null)
{
var proxy = new Proxy();
proxy.AddBypassAddresses("localhost", "127.0.0.1");
if (ProxyAutoConfigUrl != null)
{
proxy.Kind = ProxyKind.ProxyAutoConfigure;
proxy.ProxyAutoConfigUrl = ProxyAutoConfigUrl;
}
if (Proxy != null)
{
proxy.Kind = ProxyKind.Manual;
proxy.HttpProxy = Proxy;
proxy.SslProxy = Proxy;
}
return proxy;
}
return null;
}
Selenium Standalone Server version 3.10.0
iewebdriverserver 3.9.0 32 bit

bad request - request too long

I use IdentityServer3. My startup class is bellow.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/identity", idsrvApp =>
{
var corsPolicyService = new DefaultCorsPolicyService()
{
AllowAll = true
};
var idServerServiceFactory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get());
//.UseInMemoryUsers(Users.Get());
idServerServiceFactory.CorsPolicyService = new Registration<IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService);
idServerServiceFactory.ViewService = new Registration<IViewService, CustomViewService>();
idServerServiceFactory.UserService = new Registration<IUserService>(resolver => new CustomUserService());
var options = new IdentityServerOptions
{
EnableWelcomePage = false,
Factory = idServerServiceFactory,
SiteName = "Justice Identity Server",
IssuerUri = IdentityConstants.ecabinetIssuerUri,
PublicOrigin = IdentityConstants.ecabinetSTSOrigin,
AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions() {
CookieOptions = {
AllowRememberMe=false,
Prefix="IC"
},
EnablePostSignOutAutoRedirect = true,
},
SigningCertificate = LoadSertificate(),
CspOptions = new CspOptions()
{
Enabled = true,
ScriptSrc = "'unsafe-inline'",
ConnectSrc = "*",
FrameSrc = "*"
},
};
idsrvApp.UseIdentityServer(options);
});
}
X509Certificate2 LoadSertificate()
{
return new X509Certificate2(string.Format(#"{0}\certificates\cert.pfx", AppDomain.CurrentDomain.BaseDirectory), "123", X509KeyStorageFlags.MachineKeySet);
}
}
After sometimes I have got "bad request-request too long" ,when I clear cookie it works. I have seen in console a lot of nonce cookies.
Anyone could help me?
thanks you
This is a known issue.
There is more info there: https://github.com/IdentityServer/IdentityServer3/issues/1124

How to create AutoScale Settings programmatically with C# for Windows Azure Web App using Microsoft.WindowsAzure.Management.Monitoring?

What Do I have:
var subscriptionId = "xxx";
var thumbprint = "xxx";
var certificate = GetCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint);
var autoscaleClient = new AutoscaleClient(new CertificateCloudCredentials(subscriptionId, certificate));
var createParams = new AutoscaleSettingCreateOrUpdateParameters
{
Setting = new AutoscaleSetting
{
Enabled = true,
Profiles = new List<AutoscaleProfile>
{
new AutoscaleProfile
{
Capacity = new ScaleCapacity
{
Default ="1",
Maximum="10",
Minimum="1"
},
Name = "anurag",
Recurrence= new Recurrence
{
Frequency=RecurrenceFrequency.Week,
Schedule = new RecurrentSchedule
{
Days = new List<string>{"Monday", "Thursday", "Friday"},
Hours = {7, 19},
Minutes=new List<int>{0},
TimeZone = "Pacific Standard Time"
}
},
Rules=new List<ScaleRule>
{
new ScaleRule
{
MetricTrigger =new MetricTrigger
{
MetricName="Test Metric",
MetricNamespace="",
MetricSource=
AutoscaleMetricSourceBuilder.BuildWebSiteMetricSource("???", "???"),
Operator=ComparisonOperationType.GreaterThan,
Threshold=2000,
Statistic=MetricStatisticType.Average,
TimeGrain=TimeSpan.FromMinutes(5),
TimeAggregation=TimeAggregationType.Average,
TimeWindow=TimeSpan.FromMinutes(30)
},
ScaleAction = new ScaleAction
{
Direction = ScaleDirection.Increase,
Cooldown = TimeSpan.FromMinutes(20),
Type=ScaleType.ChangeCount,
Value = "4"
}
}
}
}
}
}
};
var resourceId = AutoscaleResourceIdBuilder.BuildWebSiteResourceId("???", "???");
var autoscaleResponse = autoscaleClient.Settings.CreateOrUpdate(resourceId, createParams);
I am confused about two API calls:
AutoscaleResourceIdBuilder.BuildWebSiteResourceId(string webspace, string serverFarmName)
AutoscaleMetricSourceBuilder.BuildWebSiteMetricSource(string webspaceName, string websiteName)
What is a webspace, server farm name, webspace name and web site name? Where Do I get them?

Programmatically setting up a static website using Amazon S3 and Route 53 APIs

Assume I already have purchased a domain example.com with IP address 203.0.113.2. Using C# and the The Amazon Web Services SDK for .NET 2.0.2.2, I'd like to create a static website using a custom domain using Amazon S3 and Route 53. The manual process is described in the Amazon documentation.
When trying to create an alias, I get an exception with the message:
Invalid XML ; cvc-complex-type.2.4.a: Invalid content was found starting with element 'AliasTarget'.
One of '{"https://route53.amazonaws.com/doc/2012-12-12/":ResourceRecords}' is expected.
First, I created or updated a bucket (e.g. "example.com") in Amazon S3. If it already existed, content is deleted.
using (var client = AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.USWest1))
{
if (!S3BucketExists(name, client))
{
client.PutBucket(new PutBucketRequest
{
BucketName = name,
BucketRegion = S3Region.USW1,
CannedACL = S3CannedACL.PublicRead
});
}
else
{
var request = new ListObjectsRequest
{
BucketName = name
};
var objects = client.ListObjects(request).S3Objects;
foreach (var o in objects)
{
client.DeleteObject(new DeleteObjectRequest
{
BucketName = name,
Key = o.Key
});
}
client.PutACL(new PutACLRequest
{
CannedACL = S3CannedACL.PublicRead,
BucketName = name
});
}
client.PutBucketWebsite(new PutBucketWebsiteRequest
{
BucketName = name,
WebsiteConfiguration = new WebsiteConfiguration
{
ErrorDocument = "404.html",
IndexDocumentSuffix = "index.html"
}
});
CreateObject(name, client, "index.html", "text/html", "<p>The site is under maintenance</p>");
CreateObject(name, client, "404.html", "text/html", "<p>Not Found</p>");
}
S3BucketExists returns whether a bucket exist or not, and CreateObject creates a simple page and uploads it to the bucket. Its omitted for brevity sake. I'm able to connect to the S3 hosted site without any problems.
Then I use the Route 53 API to update an existing hosted zone or create one for "example.com". All resources, except for the SOA and NS entries are deleted.
using (var client = AWSClientFactory.CreateAmazonRoute53Client())
{
var hostedZone = FindHostedZoneByName(client, domainName);
if (hostedZone != null)
{
var resourceRecordSets = client.ListResourceRecordSets(new ListResourceRecordSetsRequest
{
HostedZoneId = hostedZone.Id,
});
bool hasElements = false;
var request1 = new ChangeResourceRecordSetsRequest
{
HostedZoneId = hostedZone.Id,
ChangeBatch = new ChangeBatch
{
Changes = new List<Change>()
}
};
foreach (var resourceRecordSet in resourceRecordSets.ResourceRecordSets)
{
switch (resourceRecordSet.Type)
{
case "SOA":
case "NS":
continue;
}
var change = new Change
{
Action = "DELETE",
ResourceRecordSet = resourceRecordSet
};
request1.ChangeBatch.Changes.Add(change);
hasElements = true;
}
if (hasElements)
{
var response = client.ChangeResourceRecordSets(request1);
}
}
else
{
hostedZone = CreateHostedZone(client, domainName);
}
var hostedZoneId = hostedZone.Id;
var request = new ChangeResourceRecordSetsRequest
{
HostedZoneId = hostedZoneId,
ChangeBatch = new ChangeBatch
{
Changes = new List<Change>
{
new Change
{
Action = ChangeAction.CREATE,
ResourceRecordSet = new ResourceRecordSet
{
Name = GetQualifiedName(domainName),
Type = RRType.A,
TTL = 300,
AliasTarget = new AliasTarget()
{
HostedZoneId = "Z2F56UZL2M1ACD",
DNSName = "s3-website-us-west-1.amazonaws.com.",
},
},
},
}
}
};
client.ChangeResourceRecordSets(request);
}
The hosted zone id ("Z2F56UZL2M1ACD") and DNS names ("s3-website-us-west-1.amazonaws.com.") are public knowledge and documented on Amazon's website.
The call to ChangeResourceRecordSets throws the exception. I created an empty ResourceRecords list, with a A record of "203.0.113.2", but have not had any luck creating an alias.
That said, I can manually create the alias to the Amazon S3 site afterwards using the "Route 53 Management Console". I'm sure it's something small I'm missing.
After re-reading the documentation, it turns out that one cannot specify the TTL when specifying an alias. The following change works. Replace the code that creates an instance of ChangeResourceRecordSetsRequest to the following:
var request = new ChangeResourceRecordSetsRequest
{
HostedZoneId = hostedZoneId,
ChangeBatch = new ChangeBatch
{
Changes = new List<Change>
{
new Change
{
Action = ChangeAction.CREATE,
ResourceRecordSet = new ResourceRecordSet
{
Name = GetQualifiedName(domainName),
Type = RRType.A,
AliasTarget = new AliasTarget
{
HostedZoneId = "Z2F56UZL2M1ACD",
DNSName = "s3-website-us-west-1.amazonaws.com.",
EvaluateTargetHealth = false,
},
},
},
}
}
};
The difference was evident when the output produced by System.Net tracing was compared to the request specified in the Amazon example.

Categories

Resources