I have a project where when user login wrong for 3 times in login form, the webcam will start capturing automatically. It successfully saves the image in the database but there is one error which is Object Reference not set to an instance of an object. I know that there are a lot of questions and answers to this but I still can't solve it. Another problem is, when I just debug from the webcam form, it runs perfectly without the error message but when I debug from login form, the error appears. Another thing is it doesn't show the line of the error but I am sure that it comes somewhere from here:
private void webcam_Load(object sender, EventArgs e)
{
if ((imagecapture == null))
{
try
{
imagecapture = new Emgu.CV.VideoCapture();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Application.Idle += new EventHandler(loadimage);
}
and this is the loadimage()
public void loadimage(object sender, EventArgs e)
{
try
{
Emgu.CV.Mat imageviewer = this.imagecapture.QueryFrame();
pictureBox1.Image = imageviewer.Bitmap;
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] picture = ms.ToArray();
connection.Open();
DateTime dtime = DateTime.Now;
string qry = "INSERT INTO WebcamPhoto (ImageData,DateAndTime) VALUES(#ImageData,#dt)";
//Initialize SqlCommand object for insert.
SqlCommand cmd = new SqlCommand(qry, connection);
cmd.Parameters.AddWithValue("#ImageData", picture);
cmd.Parameters.AddWithValue("#dt", dtime);
cmd.ExecuteNonQuery();
connection.Close();
imagecapture.Dispose();
//Close form and return to list or images.
this.Close();
}
catch (NullReferenceException ex)
{
MessageBox.Show(ex.Message);
}
}
I have tried to put return and the error message is gone but the image is not saved in the database even though the webcam is working.
private void webcam_Load(object sender, EventArgs e)
{
if ((imagecapture == null))
{
try
{
imagecapture = new Emgu.CV.VideoCapture();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return;
}
Application.Idle += new EventHandler(loadimage);
}
Okay after few days finaly I found the answer myself. How? I try to change the way I wrote the code line by line and test it everytime I change the code and finally I found the culprit. So the culprit is:
public void loadimage(object sender, EventArgs e)
{
//my other code.....
imagecapture.Dispose(); <<<----here
}
So I change it to
private void ReleaseData()
{
if (imagecapture !=null)
{
imagecapture.Dispose();
}
}
and now the problem is solved :)
Related
I keep getting a "Parameter is not valid" error or a memory leak (and the picture doesn't update) when I run my code. I am trying to get frames from a local IP camera using AForge.Net. The exact error code that I get is:
"An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
Parameter is not valid."
In my code, feed is the name of the winforms picture box.
private void Form1_Load(object sender, EventArgs e) {
Console.WriteLine(camaddress);
stream.Source = camaddress;
stream.Login = camUser;
stream.Password = camPass;
stream.Start();
//PictureBox.CheckForIllegalCrossThreadCalls = false;
CaptureCamera();
isCameraRunning = true;
}
private void CaptureCamera() {
try {
camera = new Thread(new ThreadStart(CaptureCameraCallback));
camera.Start();
} catch (Exception e) {
Debug.Write("Exception encountered trying to capture camera:\n" + e.ToString() + "\n");
}
}
private void CaptureCameraCallback() {
log.Information("Camera Opened", testID);
guiLogWrite("Camera Opened");
while (stream.IsRunning) {
stream.NewFrame += new NewFrameEventHandler(VideoStream_NewFrame);
}
}
private void VideoStream_NewFrame(object sender, NewFrameEventArgs eventArgs) {
try {
//Image FrameData = new Bitmap(eventArgs.Frame);
if (feed.Image != null) feed.Image.Dispose();
Bitmap FrameData = AForge.Imaging.Image.Clone(eventArgs.Frame);
SetPicture(FrameData);
FrameData.Dispose();
} catch { }
}
private void SetPicture(Image img) {
if (this.InvokeRequired) {
this.Invoke(new MethodInvoker(delegate { SetPicture(img); }));
} else {
this.feed.Image = img;
}
This is my first time posting on Stack Overflow so please let me know if I have forgotten something. I've spent hours looking at other stackoverflow threads and Google trying to find a solution.
I have a template of sqlconnection, and I have use this code before there was no problem. Until i want to use it in datagridview.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
try
{
SQLConn.sqL = "SELECT ProductID,PCode,PName FROM Products WHERE PCode='" + txtBarcode.DataGridView.CurrentCell.Value.ToString() + "'";
SQLConn.ConnDB();
SQLConn.cmd = new SqlCommand(SQLConn.sqL, SQLConn.conn);
SQLConn.dr = SQLConn.cmd.ExecuteReader();
while (SQLConn.dr.Read())
{
dataGridView1.Rows[e.RowIndex].Cells[1].Value = SQLConn.dr["ProductID"].ToString();
dataGridView1.Rows[e.RowIndex].Cells[2].Value = SQLConn.dr["PName"].ToString();
}
}
catch (Exception ex)
{
Interaction.MsgBox(ex.ToString());
}
finally
{
SQLConn.cmd.Dispose();
SQLConn.conn.Close();
}
}
}
I think multiple calls getting in this function for that event which causing the issue. Please add SQLConn.dr.Close() to close open reader in finally clause.
I am trying to use SharpSSH to use the "view" command in the shell to read a file remotely. I am able to access and view it, but it only returns about 120 lines or so before the form locks up with no exception being thrown. Here is my code:
SshStream Shell = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string host = "10.100.100.15";
string user = "root";
string password = "pass";
Shell = new SshStream(host, user, password);
}
private void button1_Click(object sender, EventArgs e)
{
if (Shell != null)
{
try
{
Shell.Write("cd /var/log");
Shell.Write("view info.log");
StreamReader reader = new StreamReader(Shell);
string inputLine = Shell.ReadResponse();
while ((inputLine = reader.ReadLine()) != null)
{
lstLines.Items.Add(inputLine);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I am still learning to use this code, so I am just trying to display the lines that it returns in a listbox. There are about 2200 lines in the file, but it only returns about 100.
I've found a solution for my problem. Instead of using "view info.log", and am using "cat info.log". It shows all lines without prompting to continue. Thanks for your help!
I have a combobox and want to save the changes in the database.
What I want to do is if the combobox is selected and it is true it must run the code below. If it is false it must then skip the code and go further.
The code below is checking if the combobox is enabled. But when I'm compiling it's saying true when not selected
private void Log()
{
if (kaartburgerlijkestand.Enabled)
{
veranderingBurgelijkestaat();
}
}
The code below is saving the data in the database
private string veranderingBurgerlijkestaat()
{
string gebruiker = curMedewerker.Behandelnaam;
string bekeken = prodermaform.pKaart();
string tabblad = tabControl1.SelectedTab.Text;
string pat = CPatient.GeefPatientNaam(patient.Id);
string wijz = "Burgerlijkestaat: " + kaartBurgerlijkestand.Text;
CDb dcon = new CDb();
try
{
if (dcon.Open())
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.loggen(Gebruiker, Bekeken, Tabblad, Patientnaam, Wijziging, Datum) VALUES(#gebruiker, #bekeken, #tabblad, #pat, #wijz, #datum)", dcon.Conn);
cmd.Parameters.AddWithValue("#gebruiker", gebruiker);
cmd.Parameters.AddWithValue("#bekeken", bekeken);
cmd.Parameters.AddWithValue("#tabblad", tabblad);
cmd.Parameters.AddWithValue("#pat", pat);
cmd.Parameters.AddWithValue("#wijz", wijz);
cmd.Parameters.AddWithValue("#datum", DateTime.Now);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dcon.Close();
}
return wijz;
}
Could someone show me a example how to do it
I Found the solution
I have made a check
private void doCheck(object sender, EventArgs e)
{
cmbox = false;
if (kaartBurgerlijkestaat.Focused)
{
veranderingBurgerlijkestand();
}
cmbox = true;
}
Then I used the SelectedValueChanged Event
private void kaartBurgerlijkestand_SelectedValueChanged(object sender, EventArgs e)
{
if (cmbox)
doCheck(sender, e);
}
And it works fine.
I want to thank you all for helping me!
Add an Event Listener, the kaartburgerlijkestand.Enabled only check your combobox is enabled to select or not.
Add this line after your InitializeComponent(); line of Form.cs file
kaartburgerlijkestand.SelectedIndexChanged += new System.EventHandler
(this.kaartburgerlijkestand_SelectedIndexChanged);
Also add a function for above code :
private void kaartburgerlijkestand_SelectedIndexChanged(object sender, EventArgs e)
{
veranderingBurgelijkestand();
}
I want to merge two .png images. but when I ga to save them there occurred an error called a generic error occurred in gdi+. I want to continue my project as soon as possible. please help me. Thanks
private void MergeImages(string ImageBack,string ImageFore)
{
try
{
System.Drawing.Graphics myGraphic = null;
Image imgB;// =new Image.FromFile(ImageBack);
imgB = Image.FromFile(ImageBack);
//FileInfo fileInfoBack = new FileInfo(ImageBack);
Image imgF;// =new Image.FromFile(ImageBack);
imgF = Image.FromFile(ImageFore);
//Bitmap tempBitmap = new Bitmap(imgB.Width, imgB.Height,imgB.PixelFormat );
// tempBitmap.Save("a"+fileInfoBack.Extension);
Image m;
m = Image.FromFile(ImageBack);
// m = Image.FromFile("a" + fileInfoBack.Extension);
myGraphic = System.Drawing.Graphics.FromImage(m);
myGraphic.DrawImageUnscaled(imgB,0,0);
myGraphic.DrawImageUnscaled(imgF,posX,posY);
myGraphic.Save();
m.Save(ImageBack.Replace(".jpg",".jpeg"),System.Drawing.Imaging.ImageFormat.Jpeg);
//m.Save(ImageBack, System.Drawing.Imaging.ImageFormat.Png);
// m.Save("d.png", System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnFileProtector_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
txtFileProtector.Text=openFileDialog1.FileName;
}
}
private void btnFilesToProtect_Click(object sender, System.EventArgs e)
{
listFilesToProtect.Items.Clear();
if (openFileDialog2.ShowDialog()==DialogResult.OK)
{
if (openFileDialog2.FileNames.Length>0)
{
for(int i=0;i<openFileDialog2.FileNames.Length;i++)
{
listFilesToProtect.Items.Add(openFileDialog2.FileNames[i]);
}
}
}
}
private void btnLoad2_Click(object sender, System.EventArgs e)
{
posX = int.Parse(textBox1.Text);
posY = int.Parse(textBox2.Text);
// heightBackImage = int.Parse(textBox3.Text);
// widthBackImage = int.Parse(textBox4.Text);
if (listFilesToProtect.Items.Count>0)
{
foreach(object it in listFilesToProtect.Items)
{
MergeImages(it.ToString(), txtFileProtector.Text);
}
}
}
You didn't show us at which line this exception is thrown, So I am going to guess here. This error usually occurs when the path of the image that you are trying to load/save is not correct, so check the path for both ImageBack and ImageFore.
Also make sure that the file you are trying to load/save to is not open by another process including your application.
It is worth to mentioned here that you should dispose the images/graphics when you finish from using them, for instance by use using. like
using(Image imgB = Image.FromFile(ImageBack))
{
//the code that is using the imgB here
}