How to Asynchronous two job in asp.net - asp.net

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

Related

How to refresh table view from other form controller in javafx?

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?

Simple example reverse geocoding osmdroid

im looking for a simple example of reverse geocoding using osmdroid.
Do have i to use the nominatimAPI with JSON and more ?
i heard that using the Geocoder class do the same thing but it seems too easy...
Is it normal that the class RequestBuilder is not recognize when im attemping to do a request
to nominatim ?
Thanks
You can use OSMBonusPack GeocoderNominatim class.
Here is an example using OSMBonusPack:
// declare your map somewhere in the Activity
map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setMultiTouchControls(true);
// create a GeoPoint
final GeoPoint startPoint = new GeoPoint(36.716999, 3.042076);
// Retreive Geocoding data (add this code to an event click listener on a button)
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... voids) {
// Reverse Geocoding
GeocoderNominatim geocoder = new GeocoderNominatim(userAgent);
String theAddress;
try {
List<Address> addresses = geocoder.getFromLocation(startPoint.getLatitude(), startPoint.getLongitude(), 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int n = address.getMaxAddressLineIndex();
Log.d("Test", "CountryName: " + address.getCountryName());
Log.d("Test", "CountryCode: " + address.getCountryCode());
Log.d("Test", "PostalCode " + address.getPostalCode());
// Log.d("Test", "FeatureName " + address.getFeatureName()); //null
Log.d("Test", "City: " + address.getAdminArea());
Log.d("Test", "Locality: " + address.getLocality());
Log.d("Test", "Premises: " + address.getPremises()); //null
Log.d("Test", "SubAdminArea: " + address.getSubAdminArea());
Log.d("Test", "SubLocality: " + address.getSubLocality());
// Log.d("Test", "SubThoroughfare: " + address.getSubThoroughfare()); //null
// Log.d("Test", "getThoroughfare: " + address.getThoroughfare()); //null
Log.d("Test", "Locale: " + address.getLocale());
for (int i=0; i<=n; i++) {
if (i!=0)
sb.append(", ");
sb.append(address.getAddressLine(i));
}
theAddress = sb.toString();
} else {
theAddress = null;
}
} catch (IOException e) {
theAddress = null;
}
if (theAddress != null) {
Log.d("Test", "Address: " + theAddress);
}
return null;
}
}.execute();
More tutorials can be found in the wiki page:
https://github.com/MKergall/osmbonuspack/wiki
Hope this helps.

why my server.mappath() is not working in another pc?

i have project in my pc..but when i am saving my uploaded files in a folder inside my project.now when i am transferring my project in another pc the server.mappath() is not working..why??
my problem upload function
protected void addproblem_Click(object sender, EventArgs e)
{
string filepath;
if (problemupload.HasFile)
try
{
if(problemupload.PostedFile.ContentType=="application/pdf")
{
// problemupload.SaveAs("F:\\0\\My project website\\sgipc\\problems\\" + problemupload.FileName);
// filepath = "F:\\0\\My project website\\sgipc\\problems\\" + problemupload.PostedFile.FileName;
problemupload.SaveAs(Server.MapPath("\\sgipc\\problems\\" + problemupload.FileName));
filepath = Server.MapPath(problemupload.PostedFile.FileName);
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string userid = Convert.ToString(Session["userid"]);
SqlCommand cmd = new SqlCommand("INSERT INTO problemtable(problemname,problempath,userid,status) Values('" + probbox.Text + "','" + filepath + "','" + userid + "','" + "pending" + "')", objsqlconn);
cmd.ExecuteNonQuery();
objsqlconn.Close();
}
else
{
Response.Write("<script>alert('" + "Only pdf format is allowed..." + "')</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.ToString() + "')</script>");
}
else
{
Response.Write("<script>alert('" + "you have not specified a file..." + "')</script>");
}
}
i am getting this error
"System.InvalidOperationException: Failed to map the path '/sgipc/tutorials/v6-1446-1449.pdf'."
while uploading a file from another pc..but from my pc it works fine..
I think there is problem in Server.MapPath try with this syntax FileUploadControl.SaveAs(Server.MapPath("~/sgipc/problems/" + problemupload.FileName));
~ sign will automatic configure path from server and it is better then \\ sign for map path..

Regarding to not calling of enquiry.cs in app code

I am a newcomer in .net , my problem is related to email. This code is well performed on my localhost. This is code of my enquiry.aspx.cs:-
protected void Button1_Click(object sender, EventArgs e)
{
Mail mm = new Mail();
if (DropDownList3.SelectedItem.Text == "--Select--")
{
Label5.Text = "Please Select Course";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
}
else if (TextBox1.Text == "")
{
Label5.Text = "Please Enter Name";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
TextBox1.Focus();
}
else if (mm.checkValidemail(TextBox2.Text) == false)
{
Label5.Text = "Please Enter E-Mail ID";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter E-Mail ID');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter E-Mail ID'); </script>");
TextBox2.Focus();
}
else if (mm.checkValidmobile(TextBox3.Text) == false)
{
Label5.Text = "Please Enter Mobile Number";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Mobile Number');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Mobile Number'); </script>");
TextBox3.Focus();
}
else
{
myenquiry ee = new myenquiry();
//myenquiry ee=new myenquiry();
int i = ee.add_enquiry(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, "-", "-", "NORMAL ENQUIRY FROM SITE", TextBox11.Text, DropDownList3.SelectedItem.Text, TextBox12.Text,locationlst.SelectedItem.Text);
if (i == 1)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(" Enquiry " + "<shila#gmail.com> ");
message.To.Add(new MailAddress("shu#gmail.com"));
message.CC.Add(new MailAddress("va_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
}
catch
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
}
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
and this is my appcode folder enquiry.cs:-
public class myenquiry
{
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=group;Integrated Security=True");
SqlCommand comm = new SqlCommand();
int result = 0;
public int add_enquiry(string nam,string email,string mob,string adr,string cit,string state,string country,string zip,string college,string tech,string query,string loc)
{
try
{
comm.Connection = conn;
comm.CommandText = "insert into enquiry(name,email,mobile,address,city,state,country,zip,college,technology,query,edate,location) values('" + nam + "','" + email + "','" + mob + "','" + adr + "','" + cit + "','" + state + "','" + country + "','" + zip + "','" + college + "','" + tech + "','" + query + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','"+loc+"')";
conn.Open();
comm.ExecuteNonQuery();
result = 1;
}
catch(Exception ee)
{
result = 0;
}
finally
{
conn.Close();
}
return result;
}
}
this is well perform on local. But at the server the appcode enquiry.cs is not called on enquiry.aspx.cs and the value of int i is becoming 0, so the else part is executing. Why?
You seem to have a hard coded connection string in the myenquiry class. If you are not dynamically setting the connection string from a configuration file or otherwise, the insert method will try to use that string which points to your local. Assuming your server is a different domain/machine with no access to your local DB, the connection will definitely fail, giving you the result 0.
As Shree.pat18 says Don't make hardcodded connection string in class file.instead of this make your connection string in web.config file something like this in your configuration tag
<connectionStrings>
<add name="cn" connectionString="Data Source=USER-PC;Initial Catalog=group;Integrated Security=True"/>
</connectionStrings>

Could not find a part of the path when programatically mounting remote folder

I am using the following code to mount a remote drive:
public static void MapDrive()
{
try
{
if (System.IO.Directory.Exists(remoteFolder1)) //"Z:\\"
{
DisconnectDrive(remoteDriveLetter); //"Z:"
}
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "net.exe";
p.StartInfo.Arguments = #" use " + remoteDriveLetter + " " + remoteShareName + " " + userPwd + " /user:" + userName;
//EventLog.WriteEntry("Conversion Service", "Remote drive mapped successfully", EventLogEntryType.Information);
p.Start();
p.WaitForExit();
}
catch (Exception ex6_5)
{
WriteException(ex6_5, "Ex6.5");
}
}
I can verify that that the Z drive is available and am able to save files to it by dragging but the following code throws an DirectoryNotFoundException "Could not find a part of the path 'Z:\Default.pptx'."
AsyncFileUpload1.SaveAs(remoteFolder + fileName);
The value in remoteFolder is "Z:\" and fileName is "Default.pptx".
Can someone help me out please?
Thanks,
Risho

Resources