what happens when you stop VS debugger? - asp.net

If I have a line like this
ContentRepository.Update(existing);
that goes into datastore repository to update some object and I have a try..catch block in this Update function like this:
string file = XmlProvider.DataStorePhysicalPath + o.GetType().Name + Path.DirectorySeparatorChar + o.Slug + ".xml";
DataContractSerializer dcs = new DataContractSerializer(typeof (BaseContentObject));
using (
XmlDictionaryWriter myWriter =
XmlDictionaryWriter.CreateTextWriter(new FileStream(file, FileMode.Truncate, FileAccess.Write),
Encoding.UTF8))
{
try
{
dcs.WriteObject(myWriter, o);
myWriter.Close();
}
catch (Exception)
{
// if anything goes wrong, delete the created file
if (File.Exists(file))
File.Delete(file);
if(myWriter.WriteState!=WriteState.Closed)
myWriter.Close();
}
}
then why would Visual Studio go on with calling Update() if I click "Stop" in debugging session on the above line?
For instance, I came to that line by going line by line pressing F10 and now I'm on that line which is colored yellow and I press Stop.
Apparently what happens is, VS goes to execute the Update() method and somehow figures out something gone wrong and goes into "catch" and deletes the file, which is wrong, because I want my catch to work when there is a true exception not when I debug a program and force to stop it.

It depends if the debugger detaching ends the process. If it doesn't, then the program will continue to run. If it does, then it won't.

Related

Project hangs on QProcess::start when starting QtAssistant

I am using QProcess::start to launch Qt Assistant with my custom help project file. It works fine until i load project(not help project file) to my programm. Programm generates images from specific data using custom library. Even when all processes ends and i see generated images and nothing else happens, when i trying to launch Qt Assistant, my programm hangs at QProcess:start function when trying to start process. The code is:
show() function(public):
if (!run())
return false;
QByteArray ba("setSource ");
ba.append("qthelp://insyn_help/doc/");
proc->write(ba + page.toLocal8Bit() + '\n');
return true;
run() function(private):
if (!proc)
proc = new QProcess();
if (proc->state() == QProcess::Running)
return true;
QString app = QString(QT_BIN_DIR) + QDir::separator() + QString("assistant");
QString path = QString(PREFIX) + QString(HELP_INSTALL_PATH) + QString("/help_project.qhc");
QStringList args;
args << QLatin1String("-collectionFile")
<< QLatin1String(path.toLatin1())
<< QLatin1String("-enableRemoteControl");
QFileInfo help_project(path);
if (help_project.exists()) {
proc->start(app,args);
if (!proc->waitForStarted()) {
m_exitCode = 1;
emit closed();
return false;
}
}
This code is a part of AssistantLauncher class which was registered using qmlRegisterType and added to main.qml as a member of application window. My programm doesn't touch it anywhere (except calling a method show()). It is separate object (except it is a part of appWindow). The question is why does the process can not start only after my programm did some work? And why QProcess::start even dont have timeout.
UPD: I moved proc->start(app,args); to the child process, which i getting by using fork() and now my programm hangs on pid_t child = fork(). So the problem is that new process can not be created.
The answer is to do not use fork() because it is dangerous in big projects. More at http://www.evanjones.ca/fork-is-dangerous.html . posix_spawn also hangs my project. Now i decided to fork() new process at the beginning and send commands to it through the pipe.

Using Vert.x to read file line by line (AsyncFile and RecordParser help)

I'm trying to use Vert.x to read a large file from the file system and process it line by line. From the Core docs, I think the way to do this is through an AsyncFile and a RecordParser. Ideally, I'd like to Pump the data (to avoid back-pressure), but RecordParser is not a WriteStream:
AsyncFile asyncFile = vertx.fileSystem().openBlocking(/*path and options*/);
RecordParser recordParser = RecordParser.newDelimited("\n", bufferedLine -> {
// Do something per line
});
Pump.pump(asyncFile, recordParser).start(); // Error - RecordParser cannot be converted to WriteStream
So I guess I have to do my own pumping? I tried something like:
RecordParser recordParser = RecordParser.newDelimited("\n", bufferedLine -> {
// Do something per line
// I can see this code get run
})
.exceptionHandler(cause -> {
// Do I need this? What are the repercussions if I don't have this handler? Are exceptions just lost?
})
.endHandler(_void -> {
// This never gets called!
});
asyncFile.handler(recordParser); // Crazy Java8 syntax passes recordParser.handle to this handler :)
However, I'm not sure my file is being closed as the recordParser.endHandler never gets called (although I can see the line handler being called).
What am I doing wrong? Is the file not being closed? I tried adding an endHandler to asyncFile and closing it, but that didn't work.
Ideally, I'd rather get Pump to work. Is there any way to use Pump in this scenario?
Thanks in advance!
P.S.: Excuse the "crosspost".
You can do with AsyncFile and RecordParser as you said.
RecordParser recordParser = RecordParser.newDelimited("\n", bufferedLine -> {
System.out.println("bufferedLine = " + bufferedLine);
});
asyncFile.handler(recordParser)
.endHandler(v -> {
asyncFile.close();
System.out.println("Done");
});
If you go this way, you should set an exception handler on the AsyncFile, not on the RecordParser.
With the code above, the file will be closed properly.
However, I'm not sure my file is being closed as the recordParser.endHandler never gets called (although I can see the line handler being called).
Actually, the endHandler and the exceptionHandler will only get called if the RecordParser is created by wrapping another ReadStream. In your case, they are not necessary.
Also, regarding your comment:
// Crazy Java8 syntax passes recordParser.handle to this handler :)
This is not a Java 8 trick, it's just that AsyncFile.handler() expects a Handler<Buffer> and RecordParser implements this interface.

FileUpload control in asp.net throwing exception

I am trying to read an Excel sheet using C# which is to be loaded by end user from fileUpload control.
I am writing my code to save the file on server in event handler of another button control(Upload). But when I click on Upload Button I am getting this exception:
The process cannot access the file 'E:\MyProjectName\App_Data\sampledata.xlsx' because it is being used by another process.
Here is the code that I have used in event handler:
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
Even deleting the file is not working, throwing the same exception.
Make sure, some other process is not accessing that file.
This error might occurs whenever you are trying to upload file, without explicitly removing it from memory.
So try this:
try
{
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
}
catch (Exception ex)
{
throw ex.Message;
}
finally
{
file_upload.PostedFile.InputStream.Flush();
file_upload.PostedFile.InputStream.Close();
file_upload.FileContent.Dispose();
//Release File from Memory after uploading
}
The references are hanging in memory, If you are using Visual Studio try with Clean Solution and Rebuild again, if you are in IIS, just do a recycle of your application.
To avoid this problems try to dispose the files once you used them, something like:
using(var file= new FileInfo(path))
{
//use the file
//it will be automatically disposed after use
}
If i have understood the scenario properly.
For Upload control, I don't think you have to write code for Upload Button. When you click on your button,your upload control has locked the file and using it so it is already used by one process. Code written for button will be another process.
Prior to this, check whether your file is not opened anywhere and pending for edit.

runtime error in running asp.net application

Am running asp.net application with access database using gridview application..while running i got the run time error as
Object reference not set to an instance of an object.
Line 41: RadioButtonList rblGender = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("rbGenderEdit");
Line 42:DropDownList ddlStatus = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlStatusEdit");
Line 43:SqlDataSource1.UpdateParameters["Sex"].DefaultValue = rblGender.SelectedValue;
Line 44:SqlDataSource1.UpdateParameters["MaritalStauts"].DefaultValue = ddlStatus.SelectedValue;
Line 45: }
I got this error specially in line 43..
So rblGender.SelectedValue or rblGender is null...
Perhaps the problen is with rblGender
Make assignment as follows:
RadioButtonList rblGender = GridView1.Rows[e.RowIndex].FindControl("rbGenderEdit") as RadioButtonList;
And then check for nullability:
if (rblGender == null)
{
//show error
}
RadioButtonList rblGender = (RadioButtonList)GridView1.Rows[e.RowIndex].TemplateControl.FindControl("rbGenderEdit");
if it is in template field.
it can't find rbGenderEdit.
When you have a runtime error like this one, you should use your debugger to actually see what is going on behind the scene. Just put your breakpoint at the line 43 for instance, run your program in debug mode and start investigate to see what object has a null reference and try to fix it.
For instance take a look at the line 41, rblGender might be null...
EDIT
You must check if the objects that you are manipulating are null, this is part of the defensive programming techniques.
In your example, as others have said you can do it this way:
if(rblGender == null) {
// If you are running your program with a console
// Otherwise you should display this anywhere you can or in a log file.
Console.WriteLine("rblGender is null");
}
else if(rblGender.SelectedValue == null) {
Console.WriteLine("rblGender.SelectedValue is null");
}
Run your program and check what is being written! This is not going to solve your problem, but it is just going to tell you where your null reference is which will help you figure out what should be fixed!
But as I said earlier you can also debug your program properly by putting a breakpoint (you know the red ball when you click on the side of the window) at the line 43, and then run your program in debug mode! When the runtime error will fireup you will be able to check whether rblGender or rblGender.SelectedValue is null.
Also, from a more general point of view, checking your object against null references will prevent your application from crashing suddenly by managing the case where an objet might have a null reference at any given time. For instance you can say:
if(my_object is null)
{
myValue = "default";
}
else
{
myValue = my_objet.getValue();
}
This is just an example it could be done in a better way, using exceptions (try/catch/finally) for instance but the general idea is: check against null references!

FileReference.download() not working

I'm building a Flex app which requires me to download files.
I have the following code:
public function execute(event:CairngormEvent) : void
{
var evt:StemDownloadEvent = event as StemDownloadEvent;
var req:URLRequest = new URLRequest(evt.data.file_path);
var localRef:FileReference = new FileReference();
localRef.addEventListener(Event.OPEN, _open);
localRef.addEventListener(ProgressEvent.PROGRESS, _progress);
localRef.addEventListener(Event.COMPLETE, _complete);
localRef.addEventListener(Event.CANCEL, _cancel);
localRef.addEventListener(Event.SELECT, _select);
localRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _securityError);
localRef.addEventListener(IOErrorEvent.IO_ERROR, _ioError);
try {
localRef.download(req);
} catch (e:Error) {
SoundRoom.logger.log(e);
}
}
As you can see, I hooked up every possible event listener as well.
When this executes, I get the browse window, and am able to select a location, and click save. After that, nothing happens.
I have each event handler hooked up to my logger, and not a single one is being called! Is there something missing here?
The problem seems to be with my command being destroyed before this could finish.
For a proof of concept, I set my localRef variable to be static instead of an instance variable, and everything went through successfully! I guess Cairngorm commands kill themselves asap!

Resources