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.
Related
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 have a very very strange issue going on with SSIS and wanted to know if anyone else has had something similar.
In a Data Flow I have a Source that gets data from a MSSQL table and then feeds it to a data transformation Script Task.
The script task is as follows:
Script Task
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string SecurityHeader = (string)Variables.SecurityHeader;
string APIToken = (string)Variables.APIToken;
var AppFormID = (string)Row.AppFormID;
var AppClassName = (string)Row.AppClassName;
var Lat = Row.Latitude;
var Long = Row.Longitude;
var data = new
{
record = new
{
status = Row.Status.ToString(),
latitude = Row.Latitude,
longitude = Row.Longitude,
form_values = new Dictionary<string, string>()
}
};
if (Row.CreatedBy_IsNull == false) { data.record.form_values["1a09"] = Row.CreatedBy.ToString(); }
string jsonstring = JsonConvert.SerializeObject(data);
var client = new RestClient(AppURLRef);
var request = new RestRequest(Method.POST);
request.AddHeader(SecurityHeader, APIToken);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", jsonstring, ParameterType.RequestBody);
try
{
IRestResponse dataresponse = client.Execute(request);
if (dataresponse.StatusCode.ToString() == "Created")
{
var listobject = JsonConvert.DeserializeObject<Lists>(dataresponse.Content);
}
else
{
Row.OErrorMsg = dataresponse.ErrorMessage.ToString();
};
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " Data: " + ex.Data + " Inner Exception: " + ex.InnerException);
}
}
The Issue
When I run this without any break points I get a Message Box with the error "Input string was not in correct format"
Where this gets really weird is that when I put a break point in the code works perfectly, thus making getting a line error impossible.
Has anyone ever come across an issue like this before and if so how did you fix it?
Update
After following some advice I moved the try catch block up to the start of the script, this resulted in no change the try catch block was never hit.
I attempted to but a MessageBox.Show("") at the very top of the input process row and again this was not hit. Something is happening at a higher level than both of these thought I am unable to find out where or how this is occurring.
Again to reiterate the error is in a MessageBox, not in the output and nothing gets logged in the process tab. So this means no line numbers, no useful error messages that discusses where this error is occurring.
I managed to solve this, after commenting EVERYTHING out and removing all of the input columns the error was still occurring.
I put it down to another way Microsoft wants to punish me, I copied the code deleted the script task, added a new script task and copied the old code back in. Worked perfectly...
Thanks Microsoft!!
Put delay in catch block in next line to MessageBox.Show
you able to view message box .
Some time message box goes in back ground ( USe ALT +TAB to find it).
I have an application that runs from a batch file using parameters in said file to pull PDF email attachments from an email inbox. It takes those and saves them onto drive so our web app can display them to a user. Essentially it is an incoming email handler.
Anyway, I am getting this error:
System.StackOverflowException was unhandled
{Cannot evaluate expression because the current thread is in a stack
overflow state.}
Here is the code:
static List<string> SplitPDF(string PDFPath)
{
try
{
List<string> retval = new List<string>();
ExpertPdf.PDFSplit.PDFSplitManager pds = new PDFSplitManager();
pds.LicenseKey = "XXXXXXXXXXXX";
int Pages = pds.GetPdfPageCount(PDFPath);
for (int i = 0; i < Pages; i++)
{
pds.ExtractPagesFromFileToFile(PDFPath, PDFPath + i.ToString() + ".pdf", i + 1, 1);
retval.Add(PDFPath + i.ToString() + ".pdf");
}
retval.Add(PDFPath);
return retval;
}
catch (Exception ex)
{
throw ex;
}
}
This method throws the error on
int Pages = pds.GetPdfPageCount(PDFPath);
Don't know why or how. The funny thing is, it only happens with one of three batch files. The other two work fine (Production fails, dev and test work fine).
We think it may have to do with the file folders, maybe something is happening in there, but I am unsure...
Any suggestions? Need any other code? I know I only provided one method, but that is where the error is.
Thanks!
EDIT: here is the stack trace, if it helps
IncomingFax.exe!IncomingFax.Program.SplitPDF(string PDFPath = "D:\www\443\PBIN\fax\inbox\preproc\3lz3npbd2sy") Line 726 + 0x17 bytes
IncomingFax.exe!IncomingFax.Program.ProcessMessage(ForAspNet.POP3.EmailMessage Message = {ForAspNet.POP3.EmailMessage}) Line 326 + 0x9 bytes
IncomingFax.exe!IncomingFax.Program.Main(string[] args = {string[6]}) Line 78 + 0x9 bytes
I have a function which have a long execution time.
public void updateCampaign()
{
context.Session[processId] = "0|Fetching Lead360 Campaign";
Lead360 objLead360 = new Lead360();
string campaignXML = objLead360.getCampaigns();
string todayDate = DateTime.Now.ToString("dd-MMMM-yyyy");
context.Session[processId] = "1|Creating File for Lead360 Campaign on " + todayDate;
string fileName = HttpContext.Current.Server.MapPath("campaigns") + todayDate + ".xml";
objLead360.createFile(fileName, campaignXML);
context.Session[processId] = "2|Reading The latest Lead360 Campaign";
string file = File.ReadAllText(fileName);
context.Session[processId] = "3|Updating Lead360 Campaign";
string updateStatus = objLead360.updateCampaign(fileName);
string[] statusArr = updateStatus.Split('|');
context.Session[processId] = "99|" + statusArr[0] + " New Inserted , " + statusArr[1] + " Updated , With " + statusArr[2] + " Error , ";
}
So to track the Progress of the function I wrote a another function
public void getProgress()
{
if (context.Session[processId] == null)
{
string json = "{\"error\":true}";
Response.Write(json);
Response.End();
}else{
string[] status = context.Session[processId].ToString().Split('|');
if (status[0] == "99") context.Session.Remove(processId);
string json = "{\"error\":false,\"statuscode\":" + status[0] + ",\"statusmsz\":\"" + status[1] + "\" }";
Response.Write(json);
Response.End();
}
}
To call this by jQuery post request is used
reqUrl = "AjaxPages/lead360Campaign.aspx?processid=" + progressID + "&action=updatecampaign";
$.post(reqUrl);
setTimeout(getProgress, 500);
get getProgress is :
function getProgress() {
reqUrl = "AjaxPages/lead360Campaign.aspx?processid=" + progressID + "&action=getProgress";
$.post(reqUrl, function (response) {
var progress = jQuery.parseJSON(response);
console.log(progress)
if (progress.error) {
$("#fetchedCampaign .waitingMsz").html("Some error occured. Please try again later.");
$("#fetchedCampaign .waitingMsz").css({ "background": "url(common/images/ajax_error.jpg) no-repeat center 6px" });
return;
}
if (progress.statuscode == 99) {
$("#fetchedCampaign .waitingMsz").html("Update Status :"+ progress.statusmsz );
$("#fetchedCampaign .waitingMsz").css({ "background": "url(common/images/ajax_loded.jpg) no-repeat center 6px" });
return;
}
$("#fetchedCampaign .waitingMsz").html("Please Wait... " + progress.statusmsz);
setTimeout(getProgress, 500);
});
}
But the problem is that I can't see the intermediate message. Only the last message is been displayed after a long lime of ajax loading message
Also on the browser console I just see that after a long time first requested is completed and after that the second request is completed. but there should be for getProgress ?
I have checked jquery.doc and it says that $post is an asynchronous request.
Can anyone please explain what is wrong with the code or logic?
You are in a situation discussed here:
ASP.net session request queuing
While a request for a given user's session is processed, other requests for the same session are waiting. You need to run your long function in a background thread and let the request that initiates it finish. However, the background thread will not have access to session, and you will need a different mechanism to communicate its progress.
From the information you've provided, I would suspect that it's not your javascript code that's being synchronous, but rather the server-side code. You can test this by using Firebug or Chrome's dev tools to look at the start and end times of the two AJAX requests. If I'm right, you'll see that the second request begins after half a second, but doesn't complete until after the first one.
If that's the case, possible causes are:
Running in a dev environment in Visual Studio, especially in debug mode, seems to reduce the amount of asynchronicity. The dev environment seems to like to process one request at a time.
See Igor's answer about session request queueing.
You may have code that explicitly locks resources and causes the second request to block until the long-running request is done.
One other possible culprit is the fact that most browsers only allow a limited number of concurrent requests to a particular domain. If you have a few requests pending at any given moment, the browser may just be queuing up the remaining requests until they return.
I am writing to a file, that is created for each date of the year, through code below. This code runs whenever, an unhandled exception occurs in an ASP.Net app. My problem is when many users are using the website, then this code could be hit due to several errors occurring at the same time, which could result in multiple requests to create or write to same file. What is the solution in this case so only one request executes the code related to writing to a file?
private void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
string errorGuid = Guid.NewGuid().ToString("D");
if (HttpContext.Current.Server.GetLastError() != null)
{
Exception err = HttpContext.Current.Server.GetLastError();
string header = String.Format("/*****\t\t{0}:{1}\t\t*****/", "Start", errorGuid);
string footer = String.Format("/*****\t\t{0}:{1}\t\t*****/", "End", errorGuid);
string errorText = String.Format("{0}{5}Exception DateTime: {1}{5}Reference #: {2}{5}Exception:{5}=========={5}{3}{5}{4}{5}", header, System.DateTime.Now, errorGuid, err.ToString(), footer, Environment.NewLine);
// '~/ErrorReports/Logs/ErrorLog.log' must exist, else we will get an error
using (System.IO.TextWriter write = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/ErrorReports/Logs/ErrorLog_" + DateTime.Now.ToShortDateString() + ".log"), true, System.Text.Encoding.UTF8))
{
write.WriteLine(errorText);
write.Close();
}
}
}
1 - you can use the singleton pattern and create a class that will handle this file creation/append or
2 - use "lock"
3 - as suggested, use elmah