I have a console application that coded in C# that is used in my TFS release process, if this application encounters an error it will display the error then return a non-zero error code, looks like this:
try
{
//Does stuff...
return 0; //where 0 = success
}
catch (Exception ex)
{
Console.WriteLine("Error in Main: " + ex.Message + "\n" + ex.StackTrace);
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Value in args[" + i + "]: " + (i == 3 ? "**********" : args[i]));
}
//Return error state
return 1;
}
It is invoked by a PowerShell script in TFS that looks like this:
# (Does some parsing stuff...)
echo $abc
Start-Process -FilePath $abc-ArgumentList $arguments -NoNewWindow -PassThru -Wait
Now my problem is that sometime the console app fails, it prints the error and exits correctly, but for some reason TFS doesn't don't detect this and considers the step "done":
I'm not really sure what I'm missing, what does my PowerShell script/application need to do to indicate the the TFS that a failure has occurred? I thought the "PassThrough" tag in PowerShell should route the error code up, is that not correct?
Looks like I was confused about the PowerShell part of the equation, I need to capture the error and pass it up to TFS. I found the following solution helpful. Also solved here...
I did something like this:
$Output = Start-Process XYZ...
If($Output.Exitcode -ne 0)
{
Throw "Errorlevel $($Output.ExitCode)"
}
Related
Hi I've coded my MVC c# application and it's all fine, however there does seem to be a few bugs. This being one of my first applications, I'm not surprised.
The application though is internal and so I do get good feedback from the users.
They do give me the screens shots 'Server Error in ........ Application'
This gives me the controller action which does help narrow down the error.
However how do I turn the +number at end of the line to an actual line number.
I'm aware that this is some sort of byte offset, but getting a rough idea of the line number would be helpful. Is there a plugin or something I can use?
Or is there another way to handle these. I've got a Base controller that all the controllers extend from - I've seen some things that say you can use this to write to a file to give you information about the error. If I made it a generic file (similar to the php error file) then that would help me with any application I make.
You can handle server errors in Global.asax inside Application_Error() method. Create a well designed error page and save it somewhere inside your project. In global asax create a method and put error handling code inside it. See below for example code.
protected void Application_Error()
{
if (httpContext.AllErrors != null)
{
// you can handle message
var message = HttpUtility.HtmlEncode(httpContext.AllErrors[0]);
//you can redirect ugly server error page to the one you created
httpContext.Response.Redirect($"~/Error/Global");
}
}
Just developing on what hhh's answer here.
This is what I've got at the end.
protected void Application_Error()
{
if (this.Context.AllErrors != null)
{
var p = Path.Combine(Server.MapPath("~"), "Errors.log");
var message = DateTime.Now.ToString();
message = message + " " + this.Context.User.Identity.Name;
message = message + " " + this.Context.Request.Url;
message = message + Environment.NewLine;
message = message + "Post";
message = message + Environment.NewLine;
string[] keys = this.Context.Request.Form.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
message = message+keys[i] + ":" + this.Context.Request.Form[keys[i]];
message = message + Environment.NewLine;
}
message = message + Environment.NewLine;
// you can handle message
message = message+ HttpUtility.HtmlEncode(this.Context.AllErrors[0]);
message = message + Environment.NewLine;
message = message + "----------------------------------";
message = message + Environment.NewLine;
System.IO.File.AppendAllText(p, message);
//you can redirect ugly server error page to the one you created
}
}
Basically giving you a file with all the key variables in the there.
Feel free to modify as you wish.
I am having some trouble with this error in Visual Studio:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\aheij\Desktop\KinectOutput\swipe.txt' because it is being used by another process.
What I Have tried:
I have tried using these codes obtained from other solved StackOverflow questions similar to mine to try to solve the problem - but even that didn't seem to work?
Ive tried checking if the file is in use, but with no success.
I also run Visual Studio as administrator.
The file is not read-only.
The folder is not open, and the file is not being used in any other program when executing the code - at least not that I can see/know of.
The code:
So, to add some context to my code: I am writing some quick gesture detection code to the Kinect c# BodyBasics SDK v2 code freely available. This is a helper method that I added, that gets called in when a person is in view. If that person is executing the gesture, the method writes the frame time and gesture name to a text file.
Half the time, when the code does work, the gesture recognition works well. However, the other half of the time, the code breaks/stops because the writing to file bit causes the error.
Below is my code to see if the person is standing in the neutral position - its a bit waffly, so apologies about that. I have commented 'ERROR' where the error is (unsurprisingly):
private void Neutral_stance(VisualStyleElement.Tab.Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
CameraSpacePoint left_hand = joints[JointType.HandLeft].Position;
CameraSpacePoint left_elbow = joints[JointType.ElbowLeft].Position;
CameraSpacePoint left_shoulder = joints[JointType.ShoulderLeft].Position;
CameraSpacePoint left_hip = joints[JointType.HipLeft].Position;
CameraSpacePoint right_hand = joints[JointType.HandRight].Position;
CameraSpacePoint right_elbow = joints[JointType.ElbowRight].Position;
CameraSpacePoint right_shoulder = joints[JointType.ShoulderRight].Position;
CameraSpacePoint right_hip = joints[JointType.HipRight].Position;
double vertical_error = 0.15;
double shoulderhand_xrange_l = Math.Abs(left_hand.X - left_shoulder.X);
double shoulderhand_xrange_r = Math.Abs(right_hand.X - right_shoulder.X);
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_p = #"C:\Users\aheij\Desktop\KinectOutput\Punch.txt"; //write to punch file
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt"; //write to swipe file
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
File.AppendAllText(path_p, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
File.AppendAllText(path_p, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
}
}
}
Any solutions/ideas/suggestions to point me on the right track would be appreciated. I think that it would be good to use the 'using streamwriter' method as opposed to the method I am using here - but I am not sure how? Any help would be appreciated.
Additonal Info: Using Visual Studio 2015; Using windows 10.
Sidenote: I read somewhere that the Windows Search tool in Windows 10 can interfere and cause problems like this so I need to disable it?
As suggested to me I used the Filestream method & ensured the file was closed after use. But, even this still caused the same error.
Thus, I also got rid of having two file-writing actions in rapid succession of each other. I dont know if this is technically right or even true, but based off of this post here: link, my error could be coming up because I am trying to execute the second 'write to text file' line whilst the previous 'write to text file' line is still executing/writing to that same folder & location - hence the clash? Please someone, correct me if I am wrong.
Either way, this seems to have worked.
See below for my edited/corrected method:
private void Neutral_stance(Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
//cameraspace point joint stuff here again (see original post for this bit leading up to the if statements.)
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt";
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
FileStream fs_s = new FileStream(path_s, FileMode.Append); //swipe
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Neutral" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
FileStream fs_s = new FileStream(path_s, FileMode.Append);
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Unknown" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
Do let me know if there is any way I can make this more elegant or anything else I should be aware of w.r.t this answer.
The code is based off of the code found here: FileStream Tutorial website
I'm using C#.NET 4 and Selenium WebDriver 2.44.0.0 and chromeDriver.
When it cannot find element, Selenium throws error:
no such element
(Session info: chrome=38.0.2125.104)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64)
But I would like to know which element is missing. I see some articles said that it can show details like this:
OpenQA.Selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"hello"}
Could anyone tell me how to get the method and selector from NoSuchElementException?
Here is my code
try
{
for(int i=0; i<10; i++)
{
string className = "items-" + i;
IWebElement t = Driver.FindElement(By.CssSelector("[class$='" + className + "'] > span"));
t.Click();
}
}
catch (NoSuchElementException ex)
{
Logger.Error("Error: " + ex.Message);
Debug.WriteLine(ex.Message);
}
The .ToString() method of the By locator returns what you're asking for.
As far as I know the exception itself does not contain the information. However, it is straight forward to handle the exception and associate it with the locator function that was used in the FindElement() method that threw it.
For example, if the element in the 5th iteration cannot be found, the code below will produce this message
Error: no such element
Error: Unable to find element using function By.CssSelector: [class$='items-4'] > span
By locator; // need to declare this outside the scope of the try block
// so it can be accessed in the catch block
try
{
for(int i=0; i<10; i++)
{
string className = "items-" + i;
locatorFunction = By.CssSelector("[class$='" + className + "'] > span")
IWebElement t = Driver.FindElement(locatorFunction);
t.Click();
}
}
catch (NoSuchElementException ex)
{
Logger.Error("Error: " + ex.Message);
Logger.Error("Error: Unable to find element using function " + locatorFunction.ToString());
}
Refer to selenium API doc for .net found here.
But, I don't think it will give you what you want in terms of exception tracking. Print the selector you are using instead which can help you identify the element throwing the error
I have written a plugin system inspired from NotePad.NET, this plugin system read all DLL File in given folder and load them at runtime if they match my Interface using reflection. code is below
foreach (string file in System.IO.Directory.GetFiles(dir + "\\plugins\\", "*.dll", System.IO.SearchOption.AllDirectories))
if (file.EndsWith(".dll"))
{
Assembly dll = Assembly.LoadFrom(file);
foreach (Type t in dll.GetTypes())
{
try
{
log.WriteLine("Trying to match " + t.BaseType.FullName + " with " + typeof(Acoustical.PluginBase.FileFormatBase).FullName + " and " + typeof(Acoustical.PluginBase.ReportBase).FullName);
if (t.BaseType.FullName == typeof(FileFormatBase).FullName)
{
log.WriteLine(" we compare for " + t.BaseType.FullName);
try
{
fileformatPlugin.Add((dynamic)Activator.CreateInstance(t));
}
catch (Exception ex)
{
log.WriteLine("Error in loading File Plugin ::" + ex.Message + "\r\n" + ex.StackTrace);
}
continue;
}
else if (t.BaseType.FullName == typeof(ReportBase).FullName)
{
log.WriteLine(" we compare for " + t.BaseType.FullName);
reportPlugin.Add((dynamic)Activator.CreateInstance(t));
continue;
}
}
catch (Exception ex) {
log.WriteLine("Error in loading Plugin ::" + ex.Message + "\r\n" + ex.StackTrace);
}
}
dll = null;
}
Above code shows the part where Iterate over all found files in folder and than load them.
The above code works for me if I use the Windows Form or WCF interface application, it works on Windows service but doesn't guarantee that. It 60-70% of time on recompile doesn't load the plugin, then I after 10-15 attempts it sometime load plugins or sometime load only 1-2 plugins.
as you see I put Try catch on almost all lines to trace where the error is coming but no error is showing up. Since it is Windows SErvice it is not possible to debug when this code is written on ONStartup event.
I did see "We compare for" line in log, but when we try to see fileformatplugin got any element it's count remain 0 and error line is not there in log.
Any advice?
So I have a C# console app that goes through a huge list of files and copies missing files to a remote location using a WebDAV mapped drive.
In essence, I'm not using a custom client, I'm using windows built-in client.
net use j: http://127.69.69.69 /user:testme pass /persistent:yes
Everything seems to work just fine (I've increased the file size limits on the IIS 7.0 server, etc. ) EXCEPT occasionally I get a "Delayed Write Failure" popup from the OS.
My problem is that my application does not bail/throw an exception on the File.Copy() Method on the client-- How might I detect this?
I guess it's not a huge deal, but part of me wonders why no exception is thrown. It appears to move onto the next file without logging an error. My script checks if the remote file size is the same and can replace a partial file on the next cycle.
Pretty simple code where it actually copies:
Log("\n copying " + lf.FullName);
try
{
if (!Directory.Exists(Path.Combine(remotePath, localDir.Name)))
Directory.CreateDirectory(Path.Combine(remotePath, localDir.Name));
}
catch (Exception e)
{
Log("Cannot create remote directory " + Path.Combine(remotePath, localDir.Name) + " " + e.Message , "error");
}
try
{
File.Copy(lf.FullName, Path.Combine(new string[] { remotePath, localDir.Name, lf.Name }), true);
}
catch (Exception e)
{
Log("Cannot copy file to " + Path.Combine(new string[] { remotePath, localDir.Name, lf.Name }) + " " + e.Message, "error");
}