I modified some code and set a breakpoint, but when the debugger hits that breakpoint, it goes nuts and runs the old code anyway!
Here is the original code:
/// <summary>
/// Creates a new <see cref="CommaSeparatedValue"/> for the specified values.
/// </summary>
/// <param name="values"></param>
public CommaSeparatedValue(params object[] values)
{
List<string> list = new List<string>();
foreach (var value in values)
{
if (value is IEnumerable)
{
foreach (var item in (IEnumerable)value)
{
list.Add(Scrub(item));
}
}
else
{
list.Add(Scrub(value));
}
}
_List = list;
}
And what I changed it to:
/// <summary>
/// Creates a new <see cref="CommaSeparatedValue"/> for the specified values.
/// </summary>
/// <param name="values"></param>
public CommaSeparatedValue(params object[] values)
{
List<string> list = new List<string>();
foreach (var value in values)
{
if (value is IEnumerable && !(value is string)) // !!! - I changed this line here
{
foreach (var item in (IEnumerable)value)
{
list.Add(Scrub(item));
}
}
else
{
list.Add(Scrub(value));
}
}
_List = list;
}
I set the breakpoint on the line that I modified (checking for a string value) and when the debugger hits that line it ignores the part that I added and continues running into the "if" block even when the value variable is a string.
If it matters, this code is being run from a MSTest unit test.
This can happen when for some reason your project is not being built before you run it, so that the code the debugger is running is no longer the same as the source you are looking at. Look in the Configuration Manager and make sure 'Build' is checked for the configuration you're using.
Related
I am trying to get the line number associated with the Instruction object in the method below. SequencePoint.StartLine is supposed to give me the information I need, but in the commented out section of the method seqPoint is always null.
/// <summary>
/// Finds all places in code where one or more methods are called.
/// </summary>
/// <param name="classOfMethods">Full name of the class that contains the methods to find.</param>
/// <param name="methodNames">Names of the methods to find in code.</param>
public MethodCall[] FindAllMethodCalls(Type classOfMethods, params string[] methodNames)
{
#region Use Mono.Cecil to find all instances where methods are called
var methodCalls = new List<MethodCall>();
var ad = AssemblyDefinition.ReadAssembly(binaryFileToSearch, new ReaderParameters { ReadSymbols = true });
foreach (var module in ad.Modules)
{
foreach (var type in module.GetTypes())
{
foreach (var method in type.Methods.Where(x => x.HasBody))
{
var instrs = method.Body.Instructions.Where(x => x.OpCode == OpCodes.Call).ToArray();
foreach (var instr in instrs)
{
var mRef = instr.Operand as MethodReference;
if (mRef != null && mRef.DeclaringType.FullName == classOfMethods.FullName && methodNames.Contains(mRef.Name))
{
// this does not work -- always returns null
//var seqPoint = method.DebugInformation.GetSequencePoint(instr);
//if (seqPoint != null)
//{
//}
methodCalls.Add(new MethodCall
{
CodeFile = method.DebugInformation.SequencePoints.First().Document.Url,
MethodRef = mRef,
});
}
}
}
}
}
...
return methodCalls.ToArray();
}
The binary files I am calling AssemblyDefinition.ReadAssembly() on have corresponding .pdb files, and I am using the ReadSymbols = true option. What am I doing wrong?
Your code is OK.
Cecil read PDB file when he should. In the read process, he is populating all PDB functions: (this is not the complete real code but for demonstration, although the real code is similar)
private bool PopulateFunctions()
{
PdbFunction[] array = PdbFile.LoadFunctions(.....);
foreach (PdbFunction pdbFunction in array)
{
this.functions.Add(pdbFunction.token, pdbFunction);
}
}
Then when he reading MethodBody, he populate the sequence points:
private void ReadSequencePoints(PdbFunction function, MethodDebugInformation info)
{
foreach (PdbLines lines in function.lines)
{
this.ReadLines(lines, info);
}
}
And,
private static void ReadLine(PdbLine line, Document document, MethodDebugInformation info)
{
SequencePoint sequencePoint = new SequencePoint(ine.offset, document);
sequencePoint.StartLine = line.lineBegin;
sequencePoint.StartColumn = line.colBegin;
sequencePoint.EndLine = line.lineEnd;
sequencePoint.EndColumn = line.colEnd;
info.sequence_points.Add(sequencePoint);
}
If you can't find a specific sequence point, it means that it does not exist in the sequence points collection of the method debug information.
Anyway, I'm in doubt that you are getting always null.
Please write this:
method.DebugInformation.GetSequencePointMapping()
And compare it with your instrs collection.
method.DebugInformation.GetSequencePointMapping() is the sequence points that Cecil know about them, and for each of them you can see the instruction that it maps to it, so you can check which call instruction in your method has a sequence point.
This is most likely a error of logic in my code.
In first place, what i'm trying to do is:
go to the respective page of my website which is in this case link and collect the data, with my public void GDataPicker.
now where i want you to help me is, i use the following code to see if the button next exists in the webpage, and collect it's respective data, but always give me the same error:
OpenQA.Selenium.StaleElementReferenceException: 'stale element reference: element is not attached to the page document
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.15063 x86_64)' , i think it's probably because i donĀ“t update my NextButtonElement.
Code:
Boolean ElementDisplayed;
try
{
Gdriver.Navigate().GoToUrl("http://www.codigo-postal.pt/");
IWebElement searchInput1 = Gdriver.FindElement(By.Id("cp4"));
searchInput1.SendKeys("4710");//4730
IWebElement searchInput2 = Gdriver.FindElement(By.ClassName("cp3"));
searchInput2.SendKeys("");//324
searchInput2.SendKeys(OpenQA.Selenium.Keys.Enter);
IWebElement NextButtonElement = Gdriver.FindElement(By.XPath("/html/body/div[4]/div/div/div[2]/ul/li[13]/a"));
GDataPicker();
while (ElementDisplayed = NextButtonElement.Displayed)
{
GDataPicker();
Gdriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2000));
NextButtonElement.SendKeys(OpenQA.Selenium.Keys.Enter);
}
}
catch (NoSuchElementException i)
{
ElementDisplayed = false;
GDataPicker();
}
I cant help you with C#, however StaleElementReferenceException occurs when the element you act upon is still in the dom but has been replaced with an identical one. what i would do is catch that exception and find the element again
catch (StaleElementReferenceException i)
{
IWebElement NextButtonElement = Gdriver.FindElement(By.XPath("/html/body/div[4]/div/div/div[2]/ul/li[13]/a"));
}
http://www.seleniumhq.org/exceptions/stale_element_reference.jsp
I would use ExpectedConditions.ElementToBeClickable with the dynamic wait feature selenium has.
var wait = new WebDriverWait(GDriver, TimeSpan.FromSeconds(5));
IWebElement NextButtonElement = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("/html/body/div[4]/div/div/div[2]/ul/li[13]/a")));
ExpectedConditions.ElementToBeClickable does exactly what you want it to do, wait a little bit until the element is displayed and not stale.
/// <summary>
/// An expectation for checking an element is visible and enabled such that you
/// can click it.
/// </summary>
/// <param name="locator">The locator used to find the element.</param>
/// <returns>The <see cref="IWebElement"/> once it is located and clickable (visible and enabled).</returns>
public static Func<IWebDriver, IWebElement> ElementToBeClickable(By locator)
{
return (driver) =>
{
var element = ElementIfVisible(driver.FindElement(locator));
try
{
if (element != null && element.Enabled)
{
return element;
}
else
{
return null;
}
}
catch (StaleElementReferenceException)
{
return null;
}
};
}
From https://github.com/SeleniumHQ/selenium/blob/master/dotnet/src/support/UI/ExpectedConditions.cs
Is there a way to write to this event log:
Or at least, some other Windows default log, where I don't have to register an event source?
Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.
*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.
I used this code to write directly to the event log Application:
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}
As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources # Windows Dev Center (I bolded the part which refers to source name):
Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.
You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):
var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");
However, you'll need to configure this source "MySource" using administrative privileges:
Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.
As stated in MSDN (eg. https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog(v=vs.110).aspx ), checking an non existing source and creating a source requires admin privilege.
It is however possible to use the source "Application" without.
In my test under Windows 2012 Server r2, I however get the following log entry using "Application" source:
The description for Event ID xxxx from source Application cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
{my event entry message}
the message resource is present but the message is not found in the string/message table
I defined the following method to create the source:
private string CreateEventSource(string currentAppName)
{
string eventSource = currentAppName;
bool sourceExists;
try
{
// searching the source throws a security exception ONLY if not exists!
sourceExists = EventLog.SourceExists(eventSource);
if (!sourceExists)
{ // no exception until yet means the user as admin privilege
EventLog.CreateEventSource(eventSource, "Application");
}
}
catch (SecurityException)
{
eventSource = "Application";
}
return eventSource;
}
I am calling it with currentAppName = AppDomain.CurrentDomain.FriendlyName
It might be possible to use the EventLogPermission class instead of this try/catch but not sure we can avoid the catch.
It is also possible to create the source externally, e.g in elevated Powershell:
New-EventLog -LogName Application -Source MyApp
Then, using 'MyApp' in the method above will NOT generate exception and the EventLog can be created with that source.
This is the logger class that I use. The private Log() method has EventLog.WriteEntry() in it, which is how you actually write to the event log. I'm including all of this code here because it's handy. In addition to logging, this class will also make sure the message isn't too long to write to the event log (it will truncate the message). If the message was too long, you'd get an exception. The caller can also specify the source. If the caller doesn't, this class will get the source. Hope it helps.
By the way, you can get an ObjectDumper from the web. I didn't want to post all that here. I got mine from here: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xanico.Core.Utilities;
namespace Xanico.Core
{
/// <summary>
/// Logging operations
/// </summary>
public static class Logger
{
// Note: The actual limit is higher than this, but different Microsoft operating systems actually have
// different limits. So just use 30,000 to be safe.
private const int MaxEventLogEntryLength = 30000;
/// <summary>
/// Gets or sets the source/caller. When logging, this logger class will attempt to get the
/// name of the executing/entry assembly and use that as the source when writing to a log.
/// In some cases, this class can't get the name of the executing assembly. This only seems
/// to happen though when the caller is in a separate domain created by its caller. So,
/// unless you're in that situation, there is no reason to set this. However, if there is
/// any reason that the source isn't being correctly logged, just set it here when your
/// process starts.
/// </summary>
public static string Source { get; set; }
/// <summary>
/// Logs the message, but only if debug logging is true.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="debugLoggingEnabled">if set to <c>true</c> [debug logging enabled].</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogDebug(string message, bool debugLoggingEnabled, string source = "")
{
if (debugLoggingEnabled == false) { return; }
Log(message, EventLogEntryType.Information, source);
}
/// <summary>
/// Logs the information.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogInformation(string message, string source = "")
{
Log(message, EventLogEntryType.Information, source);
}
/// <summary>
/// Logs the warning.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogWarning(string message, string source = "")
{
Log(message, EventLogEntryType.Warning, source);
}
/// <summary>
/// Logs the exception.
/// </summary>
/// <param name="ex">The ex.</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogException(Exception ex, string source = "")
{
if (ex == null) { throw new ArgumentNullException("ex"); }
if (Environment.UserInteractive)
{
Console.WriteLine(ex.ToString());
}
Log(ex.ToString(), EventLogEntryType.Error, source);
}
/// <summary>
/// Recursively gets the properties and values of an object and dumps that to the log.
/// </summary>
/// <param name="theObject">The object to log</param>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Xanico.Core.Logger.Log(System.String,System.Diagnostics.EventLogEntryType,System.String)")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public static void LogObjectDump(object theObject, string objectName, string source = "")
{
const int objectDepth = 5;
string objectDump = ObjectDumper.GetObjectDump(theObject, objectDepth);
string prefix = string.Format(CultureInfo.CurrentCulture,
"{0} object dump:{1}",
objectName,
Environment.NewLine);
Log(prefix + objectDump, EventLogEntryType.Warning, source);
}
private static void Log(string message, EventLogEntryType entryType, string source)
{
// Note: I got an error that the security log was inaccessible. To get around it, I ran the app as administrator
// just once, then I could run it from within VS.
if (string.IsNullOrWhiteSpace(source))
{
source = GetSource();
}
string possiblyTruncatedMessage = EnsureLogMessageLimit(message);
EventLog.WriteEntry(source, possiblyTruncatedMessage, entryType);
// If we're running a console app, also write the message to the console window.
if (Environment.UserInteractive)
{
Console.WriteLine(message);
}
}
private static string GetSource()
{
// If the caller has explicitly set a source value, just use it.
if (!string.IsNullOrWhiteSpace(Source)) { return Source; }
try
{
var assembly = Assembly.GetEntryAssembly();
// GetEntryAssembly() can return null when called in the context of a unit test project.
// That can also happen when called from an app hosted in IIS, or even a windows service.
if (assembly == null)
{
assembly = Assembly.GetExecutingAssembly();
}
if (assembly == null)
{
// From http://stackoverflow.com/a/14165787/279516:
assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
}
if (assembly == null) { return "Unknown"; }
return assembly.GetName().Name;
}
catch
{
return "Unknown";
}
}
// Ensures that the log message entry text length does not exceed the event log viewer maximum length of 32766 characters.
private static string EnsureLogMessageLimit(string logMessage)
{
if (logMessage.Length > MaxEventLogEntryLength)
{
string truncateWarningText = string.Format(CultureInfo.CurrentCulture, "... | Log Message Truncated [ Limit: {0} ]", MaxEventLogEntryLength);
// Set the message to the max minus enough room to add the truncate warning.
logMessage = logMessage.Substring(0, MaxEventLogEntryLength - truncateWarningText.Length);
logMessage = string.Format(CultureInfo.CurrentCulture, "{0}{1}", logMessage, truncateWarningText);
}
return logMessage;
}
}
}
try
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
appLog.Source = "This Application's Name";
appLog.WriteEntry("An entry to the Application event log.");
I have class working with excel worksheet.
How to you write test to prove that Merge method gets called.
/// <summary>
/// Merges the cells together.
/// </summary>
/// <param name="ws">The worksheet.</param>
/// <param name="cellsToMerge">The cells to merge.</param>
/// <exception cref="System.ArgumentNullException">ws;Worksheet has to be defined</exception>
/// <exception cref="System.ArgumentException">Cells cannot contain null or empty string;cellsToMerge</exception>
public void MergeCellsTogether(Worksheet ws, string cellsToMerge)
{
if(ws==null) throw new ArgumentNullException("ws","Worksheet has to be defined");
if(string.IsNullOrEmpty(cellsToMerge))throw new ArgumentException("Cells cannot contain null or empty string", "cellsToMerge");
var cells = ws.Cells[cellsToMerge]; // failing to setup
ws.Range[cells].Merge();
}
now my test is using MOQ
[TestMethod]
public void TestForMergingCellsTogether()
{
// assign
var cellsToMerge = "A1:C3";
// mock
var ws = new Mock<Worksheet>();
var range = new Mock<Range>();
ws.Setup(x => x.get_Range(It.IsAny<object>(), It.IsAny<object>())).Returns(range.Object);
// this is part that is giving my headake
ws.Setup(x => x.Cells[It.IsAny<object>(),It.IsAny<object>()]).Returns(range.Object);
range.Setup(x => x.Merge(It.IsAny<object>()));
// act
var ps = new RenderProcess("fileName");
ps.MergeCellsTogether(ws.Object, cellsToMerge);
// assert
range.VerifyAll();
}
I have found solution to my question.
My approach was incorrect.
My updated(simplified) code
/// <summary>
/// Merges the cells together.
/// </summary>
/// <param name="worksheet">The worksheet.</param>
/// <param name="cellsToMerge">The cells to merge.</param>
/// <exception cref="System.ArgumentNullException">ws;Worksheet has to be defined</exception>
/// <exception cref="System.ArgumentException">Cells cannot contain null or empty string;cellsToMerge</exception>
public void MergeCellsTogether(Worksheet worksheet, string cellsToMerge)
{
if(worksheet==null) throw new ArgumentNullException("worksheet","Worksheet has to be defined");
if(string.IsNullOrEmpty(cellsToMerge))throw new ArgumentException("Cells cannot contain null or empty string", "cellsToMerge");
worksheet.Range[cellsToMerge].Merge();
}
And my tests method:
// assign
var cellsToMerge = "A1:C3";
// mock
var ws = new Mock<Worksheet>();
var range = new Mock<Range>();
ws.Setup(x => x.get_Range(It.IsAny<object>(), It.IsAny<object>())).Returns(range.Object);
range.Setup(x => x.Merge(It.IsAny<object>()));
// act
var process = new RenderExcel();
process.CreateExcelWorkSheet("fileName");
process.MergeCellsTogether((Worksheet)ws.Object, cellsToMerge);
// assert
range.VerifyAll();
I am using a xml web service on my web app and sometimes remote server fails to respond in time. I came up with the idea of re-request if first attempt fails. To prevent loop I want to limit concurrent request at 2. I want to get an opinion if what I have done below is ok and would work as I expect it.
public class ScEngine
{
private int _attemptcount = 0;
public int attemptcount
{
get
{
return _attemptcount;
}
set
{
_attemptcount = value;
}
}
public DataSet GetStat(string q, string job)
{
try
{
//snip....
attemptcount += attemptcount;
return ds;
}
catch
{
if (attemptcount>=2)
{
return null;
}
else
{
return GetStat(q, job);
}
}
}
}
public class ScEngine
{
public DataSet GetStat(string q, string job)
{
int attemptCount;
while(attemptCount < 2)
{
try
{
attemptCount++;
var ds = ...//web service call
return ds;
}
catch {}
}
//log the error
return null;
}
}
You forgot to increment the attemptcount. Plus, if there's any error on the second run, it will not be caught (thus, becomes an unhandled exception).
I wouldn't recurse in order to retry. Also, I wouldn't catch and ignore all exceptions. I'd learn which exceptions indicate an error that should be retried, and would catch those. You will be ignoring serious errors, as your code stands.
You don't want to solve it this way. You will just put more load on the servers and cause more timeouts.
You can increase the web service timeout via httpRuntime. Web services typically return a lot of data in one call, so I find myself doing this pretty frequently. Don't forget to increase how long the client is willing to wait on the client side.
Here's a version that doesn't use recursion but achieves the same result. It also includes a delay so you can give the server time to recover if it hiccups.
/// <summary>
/// The maximum amount of attempts to use before giving up on an update, delete or create
/// </summary>
private const int MAX_ATTEMPTS = 2;
/// <summary>
/// Attempts to execute the specified delegate with the specified arguments.
/// </summary>
/// <param name="operation">The operation to attempt.</param>
/// <param name="arguments">The arguments to provide to the operation.</param>
/// <returns>The result of the operation if there are any.</returns>
public static object attemptOperation(Delegate operation, params object[] arguments)
{
//attempt the operation using the default max attempts
return attemptOperation(MAX_ATTEMPTS, operation, arguments);
}
/// <summary>
/// Use for creating a random delay between retry attempts.
/// </summary>
private static Random random = new Random();
/// <summary>
/// Attempts to execute the specified delegate with the specified arguments.
/// </summary>
/// <param name="operation">The operation to attempt.</param>
/// <param name="arguments">The arguments to provide to the operation.</param>
/// <param name="maxAttempts">The number of times to attempt the operation before giving up.</param>
/// <returns>The result of the operation if there are any.</returns>
public static object attemptOperation(int maxAttempts, Delegate operation, params object [] arguments)
{
//set our initial attempt count
int attemptCount = 1;
//set the default result
object result = null;
//we've not succeeded yet
bool success = false;
//keep trying until we get a result
while (success == false)
{
try
{
//attempt the operation and get the result
result = operation.DynamicInvoke(arguments);
//we succeeded if there wasn't an exception
success = true;
}
catch
{
//if we've got to the max attempts and still have an error, give up an rethrow it
if (attemptCount++ == maxAttempts)
{
//propogate the exception
throw;
}
else
{
//create a random delay in milliseconds
int randomDelayMilliseconds = random.Next(1000, 5000);
//sleep for the specified amount of milliseconds
System.Threading.Thread.Sleep(randomDelayMilliseconds);
}
}
}
//return the result
return result;
}