I have the following method in my UserVerwaltungForm.java:
#FXML
private void clickBtnAdd() {
try {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/AddForm.fxml"));
Scene scene = new Scene(root,400,450);
Stage s = new Stage();
s.setScene(scene);
s.show();
} catch (Exception e) {
e.printStackTrace();
}
}
Here I open a new AddForm and add something there to the database. I do it this way:
#FXML
private void clickBtnAdd() {
try {
con = DBManager.getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("insert into tbl values (" + PLACEHOLDER_ID + ", '" + tfUsername.getText() + "', '"
+ tfFirstname.getText() + "', '" + tfLastname.getText() + "', '" + tfPassword.getText() + "', '"
+ tfEmail.getText() + "', " + tfBodyWeight.getText() + ", " + tfBodyHeight.getText() + ", "
+ tfActivityPoints.getText() + ", '" + tfBirthdate.getText() + "')");
stmt.execute("commit");
} catch (SQLException e) {
System.err.println("Error at stmt or rs: " + e.getMessage());
}
DBManager.close(stmt);
DBManager.close(con);
Stage stage = (Stage) btnAdd.getScene().getWindow();
stage.close();
}
If I press the button in the AddForm, I want to call this method from the UserVerwaltungForm:
public void loadDataFromDatabase() {
tbl.getItems().removeAll(tbl.getItems());
setCellConfigurations();
try {
con = DBManager.getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select b.* from user_bsd b");
} catch (SQLException e) {
System.err.println("Error at stmt or rs: " + e.getMessage());
}
if (rs != null) {
try {
while (rs.next()) {
factory = new Factory(rs);
u = factory.getUser();
tbl.getItems().add(u);
}
} catch (SQLException e) {
System.err.println("Error at rs.next(): " + e.getMessage());
}
}
DBManager.close(rs);
DBManager.close(stmt);
DBManager.close(con);
}
Do you know, where I should call the loadFromDatabase method in the AddFormController after pressing the button?
Related
Net. I need your favour Please help me. See my Code..
If My First job is finished then exit from btn_ok code behind and update to ASP.NET screen, but at the same time Job 2 must working (Bulk Email is processing)
protected void btn_ok(object sender, EventArgs e)
{
try
{
//**Job 1:**
CommonCls com = new CommonCls();
com.SaveRecord(**Parameter Values**);
//Note :after save this, it must exit from this function and update Message to web Application Screen
//**Job 2**
EmailDAL em = new EmailDAL();
.....
.....
try {
em.SendEmail(PTEmail, "Appointment Rescheduled ", "Dear " + PTName + "<br> Appointment with " + PName + " referred by " + GPName + " has been rescheduled " + Stime + ". <br> with Regards <br> <b>" + GPName + "</b>" + axolbl);
}
catch (Exception ex) { logger.Error(ex.ToString()); }
try
{
em.SendEmail(PEmail, "Appointment Rescheduled ", "Dear " + PName + "<br> Appointment for " + PTName + "(" + PTCode + ") referred by " + GPName + " has been rescheduled " + Stime + ". <br> with Regards <br> <b>" + GPName + "</b>" + axolbl);
}
catch (Exception ex) { logger.Error(ex.ToString()); }
try
{
em.SendEmail(GPEmail, "Appointment Rescheduled ", "Dear " + GPName + "<br> Appointment for " + PTName + "(" + PTCode + ") with " + PName + " has been rescheduled " + Stime + ". <br> with Regards <br> " + axolbl);
}
catch (Exception ex) { logger.Error(ex.ToString()); }
}
catch (Exception ex)
{ }
}
catch (Exception ex)
{ }
}
Email Data Access Layer
public class EmailDAL
{
internal string SMTP = ConfigurationManager.AppSettings["smtpServer"];
internal string MailAddress = ConfigurationManager.AppSettings["smtpUser"];
internal string Pwd = ConfigurationManager.AppSettings["smtpPass"];
internal int Port = Convert.ToInt16(ConfigurationManager.AppSettings["smtpPort"]);
internal bool ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
public string SendEmail(string toMail, string mailSubject, string Message)
{
SmtpClient SmtpServer = new SmtpClient(SMTP);
var mail = new MailMessage();
mail.From = new MailAddress(MailAddress);
mail.To.Add(toMail);
mail.Subject = mailSubject;
mail.IsBodyHtml = true;
mail.Body = "<p style='line-height: 30px;'>" + Message + "</p>";
SmtpServer.Port = Port;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential(MailAddress, Pwd);
SmtpServer.EnableSsl = ssl;
try
{
SmtpServer.Send(mail);
return "Send Sucessfully";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
}
**Edited Answer
After seeing your methods, it looks like you will need to make that EmailDAL.SendEmail() method of yours async. To do that you could do something like the following:
public async Task<string> SendEmailAsync(string toMail, string mailSubject, string Message) {
SmtpClient SmtpServer = new SmtpClient(SMTP);
var mail = new MailMessage();
mail.From = new MailAddress(MailAddress);
mail.To.Add(toMail);
mail.Subject = mailSubject;
mail.IsBodyHtml = true;
mail.Body = "<p style='line-height: 30px;'>" + Message + "</p>";
SmtpServer.Port = Port;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential(MailAddress, Pwd);
SmtpServer.EnableSsl = ssl;
try {
await SmtpServer.SendAsync(mail);
return "Send Successfully";
} catch(Exception ex) {
return ex.Message;
}
}
Then, btn_ok() might look like:
protected async void btn_ok(object sender, EventArgs e) {
try {
//**Job 1:**
CommonCls com = new CommonCls();
com.SaveRecord(**Parameter Values**);
//Note :after save this, it must exit from this function and update Message to web Application Screen
//**Job 2**
EmailDAL em = new EmailDAL();
.....
.....
try {
await em.SendEmailAsync(PTEmail, "Appointment Rescheduled ", "Dear " + PTName + "<br> Appointment with " + PName + " referred by " + GPName + " has been rescheduled " + Stime + ". <br> with Regards <br> <b>" + GPName + "</b>" + axolbl);
}
catch (Exception ex) { logger.Error(ex.ToString()); }
try {
await em.SendEmailAsync(PEmail, "Appointment Rescheduled ", "Dear " + PName + "<br> Appointment for " + PTName + "(" + PTCode + ") referred by " + GPName + " has been rescheduled " + Stime + ". <br> with Regards <br> <b>" + GPName + "</b>" + axolbl);
}
catch (Exception ex) { logger.Error(ex.ToString()); }
try {
await em.SendEmailAsync(GPEmail, "Appointment Rescheduled ", "Dear " + GPName + "<br> Appointment for " + PTName + "(" + PTCode + ") with " + PName + " has been rescheduled " + Stime + ". <br> with Regards <br> " + axolbl);
}
catch (Exception ex) { logger.Error(ex.ToString()); }
}
catch (Exception ex) { }
}
Check out the link below to read more about using the SmtpClient.SendAsync method and how to receive updates when the email has finished transmitting.
https://msdn.microsoft.com/en-us/library/x5x13z6h(v=vs.110).aspx
Now we still need to see what CommonCls.SaveRecord() looks like to make that one async.
**Original Answer
You may want to try using Task.WhenAny() along with async and await. It will return as soon as a single job finishes but then it will still continue to let the second job finish. Although I cannot tell what version of .NET you are working with.
Below is an MSDN article about it. Hope this helps:
https://msdn.microsoft.com/en-us/library/jj155756.aspx
I have a small ASP.NET registration page linked to a database. If the user enters the username that already exists in the database, then it should display "user already exists", but it is not doing that:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists!!");
}
conn.Close();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Country and age!");
}
else if(this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue != "-Select-")
{
Response.Write("Select Country!");
}
else if (this.DropDownListCountry.SelectedValue != "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Age!");
}
else
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
}
}
}
I think you should try first
If ( temp > 0)
{
}
also debug to see what is returned by the sql query
Few Things.
You need to check this before inserting the data.
You are not preventing entering the same data if the username still exists
You can check top 1 instead of count.
private bool IsUserExists()
{
bool UserExists = false;
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp >= 1)
{
UserExists = true;
Response.Write("User already exists!!");
}
conn.Close();
}
return UserExists ;
}
Check this before inserting the data.
try
{
if(UserExists())
return; //Skips further code when user exists.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
Hello,
I can't find out how to make it so i can save data to a txt. It works while I'm in eclipse but not when i export as a runnable Jar File.
My code is:
public void openFile()
File file = new File(System.getProperty("user.dir"), "src/save/Kube.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file.getAbsoluteFile());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x = new BufferedWriter(fw);
}
public void addRecords() {
try {
x.write(game.getTotalCoins() + "\n");
x.write(game.getHighScore() + "\n");
x.write(game.getBackround() + "\n");
x.write(game.getCube() + "\n");
x.write(game.isBlackselected() + "\n");
x.write(game.isBlueselected() + "\n");
x.write(game.isGreenselected() + "\n");
x.write(game.isBlueunlocked() + "\n");
x.write(game.isGreenunlocked() + "\n");
x.write(game.isDefaultselected() + "\n");
x.write(game.isSkyselected() + "\n");
x.write(game.isUnderwaterselected() + "\n");
x.write(game.isSkyunlocked() + "\n");
x.write(game.isUnderwaterunlocked() + "");
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeFile() {
try {
x.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When ran in eclipse it works fine but when made into runnable jar file does not save.
Thanks for your help!
The two events are
protected void btnuplaod_Click(object sender, EventArgs e)
{
string filepath = Server.MapPath(#"~/Admin/temp/");
Session["Image"] = Request.Files;
HttpFileCollection uploadedFiles = (HttpFileCollection)Session["Image"];
lblerror.Text = string.Empty;
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile userPostedFile = uploadedFiles[i];
try
{
if (userPostedFile.ContentLength > 0)
{
lblerror.Text += "<u>File #" + (i + 1) + "</u><br>";
lblerror.Text += "File Content Type: " + userPostedFile.ContentType + "<br>";
lblerror.Text += "File Size: " + userPostedFile.ContentLength + "kb<br>";
lblerror.Text += "File Name: " + userPostedFile.FileName + "<br>";
userPostedFile.SaveAs(filepath + Path.GetFileName(userPostedFile.FileName));
lblerror.Text += "Location where saved: " + filepath + "\\" + Path.GetFileName(userPostedFile.FileName) + "<p>";
}
repimages.DataSource = filepath;
Session["repimage"] = userPostedFile.FileName;
repimages.DataBind();
}
catch (Exception Ex)
{
lblerror.Text += "Error: <br>" + Ex.Message;
}
}
}
and
protected void repimages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string filepath = Server.MapPath(#"~/Admin/temp/");
lblerror.Text = string.Empty;
Image img = e.Item.FindControl("postedimage") as Image;
img.ImageUrl = filepath + Session["repimage"];
}
repimages_ItemDataBound(object sender, RepeaterItemEventArgs e) event is repeating 48 times for a single image
repimages_ItemDataBound is invoked when item in your repeater is bound from your datasource. How can it be invoked with a button click?
you have to bind repImages on button click which will internally call repImages_ItemDataBound provided in your aspx you have this OnItemDataBound="repImages_ItemDataBound"
I have installed Blackberry JDE and Eclipse. I want to create a SqLite database for my application. Should I install SqLite separately or does it come with BlackBerry JDE?
There is nothing to install separate for sqlite database. You have to create it programmatically and have to work with it. Use this.
Creating Database in SD Card :
Public void CreateDatabase()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.create(myURI);
d.close();
add(new RichTextField("DB created successfully"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Creating Table in Database:
Public void CreateTable()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/"+"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement( "CREATE TABLE 'testtable' ( " +"'id' INTEGER, " +"'name' TEXT ");
st.prepare();
st.execute();
st.close();
d.close();
add(new RichTextField("Table created successfully"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Inserting data’s in Table:
Public void InsertData ()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("INSERT INTO testtable(id,name) " + "VALUES (1,’Arun’)");
st.prepare();
st.execute();
st.close();
d.close();
add(new RichTextField("Values Inserted"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Retrieving Values from Database:
Public void RetriveValues()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT id,name FROM testtable");
st.prepare();
net.rim.device.api.database.Cursor c = st.getCursor();
Row r;
int i = 0;
while(c.next())
{
r = c.getRow();
i++;
add(new RichTextField(i + ". ID = " + r.getInteger(0)
+ " , "
+". Name = " + r.getString(1)));
}
if (i==0)
{
add(new RichTextField("No data in the table."));
}
st.close();
d.close();
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}