specifying the log path for IE driver - c#

I am trying to specify the IE Driver log path for this I used the Command-Line.Code as follows
var optionsIe32 = new InternetExplorerOptions
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
EnsureCleanSession = true,
BrowserCommandLineArguments = "--log-file=\"C:\\IE.log\"
};
var _webDriver = new InternetExplorerDriver(pathContainingIE32DriverServer, optionsIe32);
But the log file is not getting updated when an error occurs.
What am I doing wrong here? Thanks in advance

You are mostly there. It is specified in the InternetExplorerService class:
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = "C:\IE.log";
service.LoggingLevel = InternetExplorerDriverLogLevel.Trace;
Modify the LoggingLevel to what you actually want, you should see the possibilities are Debug, Error, Warn, Info, Fatal and Trace. I believe Trace level logging is the most comprehensive.
Remove the BrowserCommandLineArguments from the optionsIe32, and then pass the InternetExplorerService into the Driver construction like normal, along with your already made options:
var driver = new InternetExplorerDriver(service, optionsIe32);

Related

How can i access the console logs on chrome and assert if a line exists?

Quite new to selenium, have been looking to find an answer to this question, but so far, all the times I have tried I was not able to get my desired result.
I followed other answers to access the chrome console logs but i get an exception:
ChromeOptions options = new ChromeOptions();
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
var driver = new ChromeDriver(options);
driver.Manage().Window.Maximize();
driver.Url = "https://test.test";
var homePage = new HomePage(driver); //POM
homePage.SignIn().Click();
homePage.Email("email");
homePage.Password("pw");
homePage.LogIn();
var logs = driver.Manage().Logs.GetLog(LogType.Browser);
foreach (var log in logs)
{
Console.WriteLine(log.ToString());
}
the exception is thrown on : var logs = driver.Manage().Logs.GetLog(LogType.Browser);
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I haven't been able to understand why it is thrown.
After that, i would like to assert the console logs to see if a specific entry is present. Is it possible?
So, this is a dirty workaround. If you get any good answer, please don't use mine.
Modify the default console.log method to store data in a newly introduced global variable:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
//Multiline string used for readability. Write it in single line
js.ExecuteScript("
window.oldConsoleLog = window.console.log;
window.logCalls = [];
window.console.log = function(){
oldConsoleLog.apply(window.console, arguments);
window.logCalls.push(arguments);
}
");
Now you'll be able to get all calls using the next code:
var calls = js.ExecuteScript("return window.logCalls");
If you need a cleanup:
js.ExecuteScript("delete window.logCalls;window.console.log = window.oldConsoleLog;")

Specflow BeforeTestRun Logging

[BeforeFeature]
public static void BeforeFeature()
{
featureTitle = $"{FeatureContext.Current.FeatureInfo.Title}";
featureRollFileAppender = new RollingFileAppender
{
AppendToFile = true,
StaticLogFileName = true,
Threshold = Level.All,
Name = "FeatureAppender",
File = "test.log",
Layout = new PatternLayout("%date %m%newline%exception"),
};
featureRollFileAppender.ActivateOptions();
log.Info("test");
}
I am attempting to use log4net to output a simple string, however, once the file has been generated, it does not contain any data.
No errors are thrown and the test does complete successfully.
It turns out that the previously selected RollingFileAppender was still open and I needed to select another RollingFileAppender. This is one of the issues when using multiple log files. Once this was resolved, the Info() method would output to my desired log file.
I was able to resolve my issue by adding the following code:
BasicConfigurator.Configure(nameRunRollFileAppender);
log = LogManager.GetLogger(typeof(Tracer));
log.Info("Output some data");

Modify programatically csproj files with Microsoft.Build.Evaluation (instead of Engine)

I would like to read, modify and write back csproj files.
I've found this code, but unfortunately Engine class is depreciated.
Engine engine = new Engine()
Project project = new Project(engine);
project.Load("myproject.csproj");
project.SetProperty("SignAssembly", "true");
project.Save("myproject.csproj");
So I've continued based on the hint I should use Evaluation.ProjectCollection instead of Engine:
var collection = new ProjectCollection();
collection.DefaultToolsVersion = "4.0";
var project = new Project(collection);
// project.Load("myproject.csproj") There is NO Load method :-(
project.FullPath = "myproject.csproj"; // Instead of load? Does nothing...
// ... modify the project
project.Save(); // Interestingly there is a Save() method
There is no Load method anymore. I've tried to set the property FullPath, but the project still seems empty. Missed I something?
(Please note I do know that the .csproj file is a standard XML file with XSD schema and I know that we could read/write it by using XDocument or XmlDocument. That's a backup plan. Just seeing the .Save() method on the Project class I think I missed something if I can not load an existing .csproj. thx)
I've actually found the answer, hopefully will help others:
Instead of creating a new Project(...) and trying to .Load(...) it, we should use a factory method of the ProjectCollection class.
// Instead of:
// var project = new Project(collection);
// project.FullPath = "myproject.csproj"; // Instead of load? Does nothing...
// use this:
var project = collection.LoadProject("myproject.csproj")
Since i can't comment:
This won't work in .net core without first setting the MSBuild.exe path variable. The code to do so can be found here
https://blog.rsuter.com/missing-sdk-when-using-the-microsoft-build-package-in-net-core/
and is written here
private static void SetMsBuildExePath()
{
try
{
var startInfo = new ProcessStartInfo("dotnet", "--list-sdks")
{
RedirectStandardOutput = true
};
var process = Process.Start(startInfo);
process.WaitForExit(1000);
var output = process.StandardOutput.ReadToEnd();
var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]")
.OfType<Match>()
.Select(m => System.IO.Path.Combine(m.Groups[2].Value, m.Groups[1].Value, "MSBuild.dll"));
var sdkPath = sdkPaths.Last();
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", sdkPath);
}
catch (Exception exception)
{
Console.Write("Could not set MSBUILD_EXE_PATH: " + exception);
}
}

A failing minimal example of executing JS in Win 8.1 Chakra with C#

I'm attempting to execute a tiny piece of JS via the following code (utilising the Native class from the Chakra Host example from MSDN):
var runtime = default(JavaScriptRuntime);
Native.ThrowIfError(Native.JsCreateRuntime(JavaScriptRuntimeAttributes.None, JavaScriptRuntimeVersion.VersionEdge, null, out runtime));
var context = default(JavaScriptContext);
Native.ThrowIfError(Native.JsCreateContext(runtime, (Native.IDebugApplication64)null, out context));
Native.ThrowIfError(Native.JsSetCurrentContext(context));
var script = #"var bob = 1;";
var result = default(JavaScriptValue);
var contextCookie = default(JavaScriptSourceContext);
Native.ThrowIfError(Native.JsRunScript(script, contextCookie, "source", out result));
The problem is that it returns a "ScriptCompile" error with no additional details that I'm able to spot.
Is anyone able to reveal what I've missed / done dumb / gotten confused over?
I doubt you're still wrestling with this... but I just did and figured out the answer.
If you look in jsrt.h you'll see that all the native functions use a wchar_t when using string parameters, however the DllImport attribute doesn't specify the charset, so it defaults to ANSI.
I did a find/replace in the Native.cs file and changed all the DllImport attributes to read...
[DllImport("jscript9.dll", CharSet = CharSet.Unicode)]
... and now my code works fine. I've sent a pull request to the sample owner on GitHub to get this fixed up. The update is currently in my fork at https://github.com/billti/chakra-host
Try adding this to your AssemblyInfo.cs file:
[module: DefaultCharSet(CharSet.Unicode)]
I modified my implementation of Native.ThrowIfError to, in the case of a ScriptCompile error, get some values out of the errorObject. Like so:
var message = errorObject
.GetProperty("message")
.ToString();
var source = errorObject
.GetProperty("source")
.ToString();
var line = (int)errorObject
.GetProperty("line")
.ToDouble();
var column = (int)errorObject
.GetProperty("column")
.ToDouble();
var length = (int)errorObject
.GetProperty("length")
.ToDouble();
throw new JavaScriptParseException(error, message, source, line, column, length);
This should get you more information at least.

How to detect the error raised on a particular codeline?

[Please edit the title if you find its not good enough]
I have code which triggers XSL-transformation:
objMemoryStream = new MemoryStream();
xslTransform = new XslCompiledTransform();
xpathXmlOrig = new XPathDocument("E:\\xslt error\\Simulation_of_error\\input.xml");
xslSettings = new XsltSettings();
xslSettings.EnableScript = true;
xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver());
xslTransform.Transform(xpathXmlOrig, null, objMemoryStream);
objMemoryStream.Position = 0;
StreamReader objStreamReader = new StreamReader(objMemoryStream);
The method xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); is a victim, which fails some times due to some time-out issue.
I want to detect the failure of this codeline and execute again until it successfully executes!
I tried using "TRY CATCH and WHILE methods":
bool flag = true;
do
{
try
{
xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver());
flag = false;
}
catch
{
flag = true;
}
} while (flag);
but the problem is "error is getting logged in the log file", Well. The whole code is under one more try statement, which I suspect is writing to log. Which is what I don't want... I don't want end user to know about the failure of this codeline.
Is there anyway to get it done?
The appearance of error is completely Random. First time when it fails, I try to retrigger the code, which may result in the successful transformation (on next attempt)! This is the reason why I came to conclusion that recall of Load() method would fix the problem.
Did you try to remove the inline scripts and to pass an extension object to the transformation?
I believe this will most probably solve the problem.
Otherwise you should catch XsltException and its properties LineNumber and LinePosition give you the location in the code where the exception happened.
Update: A simple example of writing an extension function (part of an extension object) passed to the transformation, and its usage within the XSLT transformation is provided here.
try using one of the Constructor overloads. It will allow you to step though your transform.
//public XslCompiledTransform(bool enableDebug);
var xslTransform = new XslCompiledTransform(true);

Categories

Resources