Email Works fine but got two emails at same time? - c#

I try to send email, below code works fine but email sends twice at a time. I tried a lot but I don't know where I made a mistake.
RTElapsedTime.cs:
public void Elapsed()
{
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
T1.Interval = 60000;
T1.Enabled = true;
}
public void T1_Elapsed(object source, ElapsedEventArgs e)
{
try
{
MatchingTime = DateTime.Now.ToString("HH:mm");
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable dt = EmailMgr.EmailServiceScheduleTimeIntervalRunTime(MatchingTime.ToString());
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count : " + dt.Rows.Count);
foreach (DataRow r in dt.Rows)
{
T1.Enabled = false;
RTEmailManagement(r);
T1.Enabled = true;
}
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Tasks are completed.");
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message);
}
}
DataTable dataRPT1 = new DataTable();
public DataTable ReportGeneration2(EmailDTO EETO)
{
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
dataRPT1 = EmailMgr.EmailLatearrivalReport(EETO.Departments, "0", EETO.ReportType);
return dataRPT1;
}
public void RTEmailManagement(DataRow dr)
{
EDTO = null;
EDTO = new EmailDTO();
MatchingTime = DateTime.Now.ToString("HH:mm");
EDTO.SecondTime = MatchingTime;
EDTO.ScheduleTime = dr["rshtime"].ToString();
EDTO.ToEmails = dr["rsh_altrntmail"].ToString();
EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');
EDTO.Subject = dr["rsh_subjct"].ToString();
EDTO.ReportID = dr["reportid"].ToString();
EDTO.Departments = dr["rsh_dept"].ToString();
EDTO.ReportType = Convert.ToInt32(dr["rsh_typly"].ToString());
EDTO.weekly = dr["rsh_day"].ToString();
EDTO.Monthly = dr["rsh_dayofmnth"].ToString();
EDTO.Day = dr["xday"].ToString();
EDTO.Body = dr["rsh_body"].ToString();
EDTO.langcode = Convert.ToInt32(dr["langcode"].ToString());
CompanyID = Int32.Parse(dr["Company_id"].ToString());
dataRPT1 = ReportGeneration2(EDTO);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count---- : " + dataRPT1.Rows.Count);
foreach (DataRow r in dataRPT1.Rows)
{
EDTO.CcEmails = new List<string>(EDTO.CcEmails) { r["Manager"].ToString() }.ToArray();
EDTO.CcEmails = EDTO.CcEmails.Distinct().ToArray();
//EDTO.CcEmails[EDTO.CcEmails.Length-1] = dataRPT1.Rows[k]["Manager"].ToString();
EDTO.ToEmails1 = r["email_addr"].ToString();
EDTO.LateArrival = r["LateArrivals"].ToString();
if (EDTO.ScheduleTime == EDTO.SecondTime)
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "time matched");
switch (Convert.ToInt32(EDTO.ReportType))
{
case 0:
case 1:
EmailConfiguration(CompanyID, EDTO);
break;
case 2:
//TraceImplogs.TraceLTService("tyoe 2 new");
EmailConfiguration(CompanyID, EDTO);
break;
case 3:
// TraceImplogs.TraceLTService("tyoe 3 new");
EmailConfiguration(CompanyID, EDTO);
break;
default:
break;
}
}
}
// else TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "not matching");
}
public void EmailConfiguration(int compid, EmailDTO EDTO)
{
try
{
ConfigDTO mlDTO = new ConfigDTO();
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable EmailConfigDT = EmailMgr.SelectAllCompanyEmailConfiguration(compid);
RTMailProcessing Mprocess = new RTMailProcessing();
mlDTO.ConfigMail = EmailConfigDT.Rows[0]["comp_email"].ToString();
mlDTO.ConfigPwd = EmailConfigDT.Rows[0]["comp_pwd"].ToString();
mlDTO.ConfigHost = EmailConfigDT.Rows[0]["host_name"].ToString();
mlDTO.ConfigPort = Convert.ToInt32(EmailConfigDT.Rows[0]["host_port"].ToString());
Mprocess.EmailProcessing(mlDTO, EDTO);
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message + " Email Error");
}
}
Email processing cs code.
RtMailprocessing.cs:
public void EmailProcessing(ConfigDTO conDTO, EmailDTO EDTO)
{
RTMsg.language(EDTO.langcode);
conDTO.ConfigPwd = utility.Decrypt_Secure_Keylock(conDTO.ConfigPwd);
// TraceImplogs.TraceLTService("Entered Config file" + conDTO.ConfigPwd);
SmtpClient smtp = new SmtpClient
{
Host = conDTO.ConfigHost,
Port = conDTO.ConfigPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(conDTO.ConfigMail, conDTO.ConfigPwd)
// Timeout = 30000,
};
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// TraceImplogs.TraceLTService("Entered inside");
if (EDTO.ToEmails != "")
{
using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(conDTO.ConfigMail, EDTO.ToEmails1, EDTO.Subject, EDTO.Body))
{
for (int k = 0; k < EDTO.CcEmails.Length; k++)
{
if (EDTO.CcEmails[k] != "")
{
message.CC.Add(EDTO.CcEmails[k].TrimEnd(';'));
}
else
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Ccmails are empty");
}
}
message.CC.Add(EDTO.ToEmails);
message.Subject = ""; message.Body = "";
message.Subject = EDTO.Subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// ReportGeneration(EDTO);
string EmailBody = "";
if (attach != null)
{
message.Attachments.Add(attach);
string[] RepBody = EDTO.Body.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
/*****with attachment***/
foreach (string lines in RepBody)
{
EmailBody += "<p style='font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; margin-left: 10px'>" + lines + "</p>";
}
message.Body = "Email Testing";
message.BodyEncoding = System.Text.Encoding.UTF8;
//message.Attachments.Dispose();
//message.Dispose();
}
if (dataRPT.Rows.Count < 1)
{
message.Body ="Test Email";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Attachments.Clear();
}
message.IsBodyHtml = true; //Send this as plain-text
smtp.Send(message);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + NameRPT + " sent successfully.");
message.CC.Clear();
//((IDisposable)smtp).Dispose();
//message.Attachments.Dispose();
//message.Dispose();
}
}
}
When I debug with breakpoint loop run single time only but I got two email. I don't know where I made exactly mistake.
Thanks in advance.

I'm going to take a guess, you're not unsubscribing the event:
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
You need to unsubscribe it:
T1.Elapsed -= new ElapsedEventHandler(T1_Elapsed);
The email server processed both messages and delivered them at the same time.

Related

objusermodel not returning any value

I am new to c# and web api and was having a problem. There is an emailtemplate that I am running in the method however when I run this the return is empty . If I comment this section then the return has values
This is my code:
[Route("InsertorUpdate")]
public IHttpActionResult InsertorUpdate(string jwt, string
Pno, string stage, string
rowno, UserModel objUserModel)
{
//var stage = objUserModel.Stage;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
SecurityProtocolType.Tls | SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
objUserModel.SAPUpdate = "";
objUserModel.Stage = 1;
objUserModel.Active = "Y";
objUserModel.CreatedBy = Pno;
objUserModel.CreatedOn = DateTime.Now;
objUserModel.UpdatedBy = Pno;
objUserModel.UpdatedOn = DateTime.Now;
// }
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.InsertorUpdate(stage, rowno,
objUserModel);
if (sqlDataTable != "Error")
{
var MailTo = string.Empty;
var EmailCC = string.Empty;
if (objUserModel.ZoneCode == "1")
{
DataTable DtSMPAG = ObjManageUserData.GetUserListforEmail("14");// For SMPAG
DataTable DtServiceQualityTeamList = ObjManageUserData.GetUserListforEmail("13");// For Service Quality Team
if (DtSMPAG.Rows.Count > 0)
{
ApiHRServiceController Obj = new ApiHRServiceController();
CommonHelper ObjCommonHelper = new CommonHelper();
EmailService ObjEmailService = new EmailService();
ObjEmailService.SmtpHost = AppConstants.smtphost;
ObjEmailService.FromEmail = AppConstants.frommail;
var EmpData = Obj.GetUserInfoByPNO(Pno.ToString().Trim());
string RequesterInfo = EmpData.UserDetails + " [" + Pno + "]";
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
MailTo = EmpData.UserEmailID.Trim();
}
foreach (DataRow rows in DtSMPAG.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (MailTo == "")
{
MailTo = EmpData.UserEmailID.Trim();
}
else
{
MailTo = MailTo + ";" + EmpData.UserEmailID.Trim();
}
}
}
if (DtServiceQualityTeamList.Rows.Count > 0)
{
foreach (DataRow rows in DtServiceQualityTeamList.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (EmailCC == "")
{
EmailCC = EmpData.UserEmailID.Trim();
}
else
{
EmailCC = EmailCC + ";" + EmpData.UserEmailID.Trim();
}
}
}
}
string EmailTitle = "Request for Special vehicle -pending for approval by Regional Head PAG";
string br = "<br>";
string EmailBody =
$#"Request no.- ('{objUserModel.ID}') has been raised for special{br}
vehicle by requester-( '{RequesterInfo}').{br}
ORG_Unit:'{objUserModel.OrgUnit}'{br}
TDC:'{objUserModel.TDC}'{br}
Customer Name:'{objUserModel.CustName}'{br}
Supply Plant:'{objUserModel.SPCode}'{br}
Link:<a href='https://tsccorpqa.corp.tatasteel.com/svrs'>SVRS</a>";
ObjEmailService.SendEmail(EmailTitle, EmailBody, MailTo, null, EmailCC);
}
}
if (objUserModel.ZoneCode == "2")
{
DataTable DtSMPAG = ObjManageUserData.GetUserListforEmail("15");// For SMPAG
DataTable DtServiceQualityTeamList = ObjManageUserData.GetUserListforEmail("13");// For Service Quality Team
if (DtSMPAG.Rows.Count > 0)
{
ApiHRServiceController Obj = new ApiHRServiceController();
CommonHelper ObjCommonHelper = new CommonHelper();
EmailService ObjEmailService = new EmailService();
ObjEmailService.SmtpHost = AppConstants.smtphost;
ObjEmailService.FromEmail = AppConstants.frommail;
var EmpData = Obj.GetUserInfoByPNO(Pno.ToString().Trim());
string RequesterInfo = EmpData.UserDetails + " [" + Pno + "]";
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
MailTo = EmpData.UserEmailID.Trim();
}
foreach (DataRow rows in DtSMPAG.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (MailTo == "")
{
MailTo = EmpData.UserEmailID.Trim();
}
else
{
MailTo = MailTo + ";" + EmpData.UserEmailID.Trim();
}
}
}
if (DtServiceQualityTeamList.Rows.Count > 0)
{
foreach (DataRow rows in DtServiceQualityTeamList.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (EmailCC == "")
{
EmailCC = EmpData.UserEmailID.Trim();
}
else
{
EmailCC = EmailCC + ";" + EmpData.UserEmailID.Trim();
}
}
}
}
string EmailTitle = "Request for Special vehicle -pending for approval by Regional Head PAG";
string br = "<br>";
string EmailBody =
$#"Request no.- ('{objUserModel.ID}') has been raised for special{br}
vehicle by requester-( '{RequesterInfo}').{br}
ORG_Unit:'{objUserModel.OrgUnit}'{br}
TDC:'{objUserModel.TDC}'{br}
Customer Name:'{objUserModel.CustName}'{br}
Supply Plant:'{objUserModel.SPCode}'{br}
Link:<a href='https://tsccorpqa.corp.tatasteel.com/svrs'>SVRS</a>";
ObjEmailService.SendEmail(EmailTitle, EmailBody, MailTo, null, EmailCC);
}
}
if (objUserModel.ZoneCode == "3")
{
DataTable DtSMPAG = ObjManageUserData.GetUserListforEmail("16");// For SMPAG
DataTable DtServiceQualityTeamList = ObjManageUserData.GetUserListforEmail("13");// For Service Quality Team
if (DtSMPAG.Rows.Count > 0)
{
ApiHRServiceController Obj = new ApiHRServiceController();
CommonHelper ObjCommonHelper = new CommonHelper();
EmailService ObjEmailService = new EmailService();
ObjEmailService.SmtpHost = AppConstants.smtphost;
ObjEmailService.FromEmail = AppConstants.frommail;
var EmpData = Obj.GetUserInfoByPNO(Pno.ToString().Trim());
string RequesterInfo = EmpData.UserDetails + " [" + Pno + "]";
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
MailTo = EmpData.UserEmailID.Trim();
}
foreach (DataRow rows in DtSMPAG.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (MailTo == "")
{
MailTo = EmpData.UserEmailID.Trim();
}
else
{
MailTo = MailTo + ";" + EmpData.UserEmailID.Trim();
}
}
}
if (DtServiceQualityTeamList.Rows.Count > 0)
{
foreach (DataRow rows in DtServiceQualityTeamList.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (EmailCC == "")
{
EmailCC = EmpData.UserEmailID.Trim();
}
else
{
EmailCC = EmailCC + ";" + EmpData.UserEmailID.Trim();
}
}
}
}
string EmailTitle = "Request for Special vehicle -pending for approval by Regional Head PAG";
string br = "<br>";
string EmailBody =
$#"Request no.- ('{objUserModel.ID}') has been raised for special{br}
vehicle by requester-( '{RequesterInfo}').{br}
ORG_Unit:'{objUserModel.OrgUnit}'{br}
TDC:'{objUserModel.TDC}'{br}
Customer Name:'{objUserModel.CustName}'{br}
Supply Plant:'{objUserModel.SPCode}'{br}
Link:<a href='https://tsccorpqa.corp.tatasteel.com/svrs'>SVRS</a>";
ObjEmailService.SendEmail(EmailTitle, EmailBody, MailTo, null, EmailCC);
}
}
if (objUserModel.ZoneCode == "4")
{
DataTable DtSMPAG = ObjManageUserData.GetUserListforEmail("17");// For SMPAG
DataTable DtServiceQualityTeamList = ObjManageUserData.GetUserListforEmail("13");// For Service Quality Team
if (DtSMPAG.Rows.Count > 0)
{
ApiHRServiceController Obj = new ApiHRServiceController();
CommonHelper ObjCommonHelper = new CommonHelper();
EmailService ObjEmailService = new EmailService();
ObjEmailService.SmtpHost = AppConstants.smtphost;
ObjEmailService.FromEmail = AppConstants.frommail;
var EmpData = Obj.GetUserInfoByPNO(Pno.ToString().Trim());
string RequesterInfo = EmpData.UserDetails + " [" + Pno + "]";
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
MailTo = EmpData.UserEmailID.Trim();
}
foreach (DataRow rows in DtSMPAG.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (MailTo == "")
{
MailTo = EmpData.UserEmailID.Trim();
}
else
{
MailTo = MailTo + ";" + EmpData.UserEmailID.Trim();
}
}
}
if (DtServiceQualityTeamList.Rows.Count > 0)
{
foreach (DataRow rows in DtServiceQualityTeamList.Rows)
{
EmpData = Obj.GetUserInfoByPNO(rows["UserList"].ToString().Trim());
if (ObjCommonHelper.IsValidEmail(EmpData.UserEmailID.Trim()))
{
if (EmailCC == "")
{
EmailCC = EmpData.UserEmailID.Trim();
}
else
{
EmailCC = EmailCC + ";" + EmpData.UserEmailID.Trim();
}
}
}
}
string EmailTitle = "Request for Special vehicle -pending for approval by Regional Head PAG";
string br = "<br>";
string EmailBody =
$#"Request no.- ('{objUserModel.ID}') has been raised for special{br}
vehicle by requester-( '{RequesterInfo}').{br}
ORG_Unit:'{objUserModel.OrgUnit}'{br}
TDC:'{objUserModel.TDC}'{br}
Customer Name:'{objUserModel.CustName}'{br}
Supply Plant:'{objUserModel.SPCode}'{br}
Link:<a href='https://tsccorpqa.corp.tatasteel.com/svrs'>SVRS</a>";
ObjEmailService.SendEmail(EmailTitle, EmailBody, MailTo, null, EmailCC);
}
}
}
return Ok(objUserModel);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
}
So when I comment out
if(sqlDataTable != "Error"){
//Email Logic here
}
the return returns value if I uncomment it it doesnot. What Am I doing wrong here?
The email Logic I have added for full clarity if I remove the if error loop as a whole then I get value in my return return Ok(objUserModel); otherwise I do not. Please help

Suddenly getting the error Failure Sending Mail in ASP.Net

I am continuously getting this error failure sending mail. I have already tried by changing port 465/25/587 but nothing worked. My credentials are also correct. All these configurations are for outlook. Checked all the ports they are also not blocked. The same code was working fine before but from last couple of days getting this error. Unable to get what's happening in this code.
Below is my code-
protected void btnSubmitClick(object sender, EventArgs e)
{
try
{
if (ddlSubCategory.SelectedIndex > 0)
{
if (Session["sessionID"] != null && Session["sessionID"].ToString().ToUpper().Trim() == "SUBMITTED")
{
// string textForMessage = #"<script language='javascript'> alert('Request Already Submitted for the same...!');</script>";
// ClientScript.RegisterClientScriptBlock(this.GetType(), "Stop", textForMessage); return;
}
if (fupAttachment.HasFile) { ViewState["file1"] = "0"; }
if (ViewState["file1"].ToString() == "0")
{
IssuesCommon issueCommon = new IssuesCommon();
issueCommon.IssueCateId = Convert.ToInt32(ddlSubCategory.SelectedValue);
issueCommon.Status = "OPEN";
issueCommon.LogBy = issueCommon.EmpId = Convert.ToInt32(getEmpDetail().Split('$')[0]);
issueCommon.Description = txtDesc.Text.Trim();
issueCommon.WorkStation = txtWorkStation.Text.Trim();
issueCommon.IPAddress = hfIP.Value;
issueCommon.Contact = txtphn.Text.Trim();
issueCommon.DepartmentId = Convert.ToInt32(Request.QueryString["help"]);
issueCommon.Supervisor = hfSuperId.Value;
string ticket = lblDeskName.Text + "#00" + Convert.ToString(Convert.ToInt32(objBal.getMaxIssueID()) + 1);
issueCommon.TicketNo = ticket;
issueCommon.Priority = (ddlPriority.SelectedValue == "Low" ? ddlSubPriority.SelectedValue : ddlPriority.SelectedValue);
issueCommon.attachmentName = fupAttachment.HasFile ? Server.MapPath("~/image/") + fupAttachment.FileName : null;
if (trSelectClient.Visible == true)
{
issueCommon.clientName = ddlClientList.SelectedValue.ToString() == "--Select--" ? "" : ddlClientList.SelectedValue.ToString();
}
else
{
issueCommon.clientName = "";
}
objBal.InsertIssue(issueCommon);
#region Mail Section
MailMessage mM = new MailMessage();
mM.From = new MailAddress("no-reply#xxxxxxx.com");
mM.To.Add(getDapartmentEmailId());
if (txtAddRecipient.Text != "" && txtAddRecipient.Text != null && trAddRecipient.Visible == true)
{
mM.CC.Add(txtAddRecipient.Text);
}
if (Session["help"] != null)
{
if (Convert.ToString(Session["help"]) == "1")
{
mM.Bcc.Add("abc#xxxxxx.com");
}
}
if (fupAttachment.HasFile)
{
string filename = fupAttachment.FileName;
fupAttachment.SaveAs(Server.MapPath("~/images/") + filename);
Attachment attach = new Attachment(Server.MapPath("~/images/") + filename);
mM.Attachments.Add(attach);
}
mM.Subject = "Issue Ticket#: " + issueCommon.TicketNo + " [Priority: " + issueCommon.Priority + "]";
string mailBody = "Hello," +
"<br/> I am having the below issue: <br/><br> Issue Category : " + ddlSubCategory.SelectedItem.Text
+ " <br/> <br/> Workstation: " + txtWorkStation.Text + " <br/><br/> IP Address : " + txtIP.Text
+ "<br /><br /> Client Name: " + ddlClientList.SelectedValue.ToString().Replace("--Select--", "N/A")
+ "<br /><br /> My ContactNo: " + txtphn.Text
+ "<br/><br/> Description : " + txtDesc.Text.Trim() + "<br/><br/> Thanks, <br/>" + hfEmpid.Value + "/" + username.Text;
mM.Body = mailBody;
mM.IsBodyHtml = true;
mM.Priority = MailPriority.High;
SmtpClient sC = new SmtpClient("smtp.office365.com");
sC.Port = 587;
sC.EnableSsl = true;
sC.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sC.Credentials = new NetworkCredential("email", "password");
sC.Send(mM);
SendMailtoUser(issueCommon.TicketNo, lblUserName.Text.Trim());
Session["sessionID"] = "Submitted"; ViewState["file1"] = "0"; clearView();
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Your request has been submitted successfully');", true);
#endregion
}
else
{
string textForMessage = #"<script language='javascript'> alert('Select Attachment ');</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "UserPopup", textForMessage);
}
}
else { Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Select Issue Category');", true); }
}
catch (Exception ex) {
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('" + ex.Message.Replace("'", "") + "');", true); }
}
Please see the exception screenshot here
enter image description here
if you try this i think sending mail will be successful
var smtpClient = new SmtpClient(hostname, 25);
// userNameShort = "ab", domain = "outlook" for example
var networkCredential = new NetworkCredential(userNameShort, password, domain);
smtpClient.Credentials = networkCredential;
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtpClient.EnableSsl = true;
smtpClient.Send(message);
Please can you trying:
SmtpClient sC = new SmtpClient("smtp.office365.com");
after adding
sC.Credentials = new NetworkCredential("email", "password");
then
sC.Port = 587;
//your codes

Exception from HRESULT: 0x80004004 (E_ABORT) at Outlook.Mailitem.getHtmlBody()

I have a custom add-in which gets the body on clicking a button when it got installed. so I am getting this error on a customer machine. code is working fine on my side and for other customers but one customer is facing this problem.
this is my code
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
Explorer olExp = olApp.ActiveExplorer();
Selection olSel = olExp.Selection;
string msg = "";
int iterate = 1;
MAPIFolder inbox = null;
if (olSel.Count > 1)
{
MessageBox.Show("Sorry! You can't report more then 1 email at a time", "Report Email");
return;
}
foreach (_MailItem mail in olSel)
{
inbox = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
mail.GetInspector.Display(false);
Thread.Sleep(2100);
string screenShot = getScreenShot(mail);
mail.GetInspector.Close(OlInspectorClose.olDiscard);
String msgToShow = "Are you sure you want to report this email as suspicious?";
if (mail != null && mail.Subject != null)
msgToShow += "\n\nSubject : " + mail.Subject.ToString();
DialogResult dr = MessageBox.Show(msgToShow, "Please Confirm", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation);
if (dr == DialogResult.Yes)
{
msg += reportMail(mail, screenShot, e);
}
else {
return;
}
iterate++;
break;
}
if (!msg.Equals(""))
MessageBox.Show(msg, "Report Email");
else
return;
if (!msg.Contains("Success"))
return;
MailItem moveMail = null;
MAPIFolder subfolder = null;
try
{
subfolder = inbox.Folders["Reported Emails"];
}
catch (System.Exception ex) {
subfolder = inbox.Folders.Add("Reported Emails", OlDefaultFolders.olFolderInbox);
}
foreach (MailItem eMail in olSel)
{
try
{
moveMail = eMail;
if (moveMail != null)
{
string titleSubject = (string)moveMail.Subject;
moveMail.Move(subfolder);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private string reportMail(_MailItem mail, string screenShot, RibbonControlEventArgs e)
{
try
{
var m = Globals.ThisAddIn.Application.GetNamespace("MAPI");
var mailitem = mail;
if (mailitem != null)
{
// Console.WriteLine("Email body ::: " + mailitem.HTMLBody);
String reporterEmail = getReporterEmail(mailitem);
String senderEmailAddress = "";
String senderName = "";
AddressEntry mailsender;
if (reporterEmail.Equals(""))
{
MessageBox.Show("Sorry! This email can't be reported because you are not included in Recipients.", "Report Email");
}
else
{
if (mailitem.SenderEmailType == "EX")
{
mailsender = mailitem.Sender;
if (mailsender != null)
{
if (mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
ExchangeUser exchUser = mailsender.GetExchangeUser();
if (exchUser != null)
{
senderEmailAddress = exchUser.PrimarySmtpAddress;
senderName = exchUser.Name;
}
}
}
}
else
{
senderEmailAddress = mailitem.SenderEmailAddress;
senderName = mailitem.SenderName;
}
String emailHeader = mailitem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E");
String emailBody = mailitem.Body.Replace("%"," percent").Replace("#","").Replace("|", "");
//String res = HttpPost(Properties.Settings.Default.address, "ReporterEmail=" + reporterEmail + "&suspectedName=" + senderName + "&FromEmail=" + senderEmailAddress
// + "&ToEmail=" + mailitem.To + "&Subject=" + mailitem.Subject + "&EmailBody=" + emailBody + "&AttachmentName=" + GetAttachments(mailitem)
// + "&reporter=" + reporterEmail + "&emailHeader=" + emailHeader + "&mailImage=" + screenShot);
String htmlBody = mail.HTMLBody;
MessageBox.Show(htmlBody);
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("ReporterEmail", reporterEmail);
postParameters.Add("suspectedName", senderName);
postParameters.Add("FromEmail", senderEmailAddress);
postParameters.Add("ToEmail", mailitem.To);
postParameters.Add("Subject", mailitem.Subject);
postParameters.Add("EmailBody", emailBody);
List<String> attachmentDetails = GetAttachments(mailitem);
postParameters.Add("AttachmentName", attachmentDetails[0]);
postParameters.Add("reporter", reporterEmail);
postParameters.Add("emailHeader", emailHeader);
postParameters.Add("mailImage", screenShot);
string res = HttpPost(Properties.Settings.Default.serverAddress+ "/PhishRod-portlet/reporter", postParameters, htmlBody,attachmentDetails[1]);
return res + "\n";
}
}
}
catch (System.Exception ex)
{
log.Error(ex);
return "Error: " + ex + "-- - " + ex.StackTrace.ToString() + "\n";
}
return "";
}
In the event handler of your button I see the following lines of code:
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
There is no need to create a new Outlook Application instance in the add-in. Instead, you need to use the Application property which doesn't trigger a security issue when dealing with OOM from external applications:
var app = Globals.ThisAddIn.Application

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

Reading txt files using task concept working slow

my requirement was reading some 300 text files each of around 40-70 MB line by line to perform some kind of checks . As the files are huge so I thought of using TPL concept i.e. tasks. if I am not using task concept, it is taking around 7 minutes but if I am doing it by using task , it is taking long time don't know why. I will be so thankful if someone please review my code and tell me where I am doing wrong in using task. Any help would be appreciated. Below is my code :
private void browse_Click(object sender, EventArgs e)
{
try
{
string newFileName1 = "";
string newFileName2 = "";
week = textBox2.Text;
if (week == null || week == "")
{
MessageBox.Show("Week cannot be null.");
return;
}
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
DateTime starttime = DateTime.Now;
string folderPath = Path.GetDirectoryName(folderBrowserDialog1.SelectedPath);
string folderName = Path.GetFileName(folderPath);
DirectoryInfo dInfo = new DirectoryInfo(folderPath);
foreach (DirectoryInfo folder in dInfo.GetDirectories())
{
newFileName1 = "Files_with_dates_mismatching_the_respective_week_" + folder.Name + ".txt";
newFileName2 = "Files_with_wrong_date_format_" + folder.Name + ".txt";
if (File.Exists(folderPath + "/" + newFileName1))
{
File.Delete(folderPath + "/" + newFileName1);
}
if (File.Exists(folderPath + "/" + newFileName2))
{
File.Delete(folderPath + "/" + newFileName2);
}
FileInfo[] folderFiles = folder.GetFiles();
if (folderFiles.Length != 0)
{
List<Task> tasks = new List<Task>();
foreach (var file in folderFiles)
{
var task = Task.Factory.StartNew(() =>
{
bool taskResult = ReadFile(file.FullName, folderPath, folderName, week);
return taskResult;
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
DateTime stoptime = DateTime.Now;
TimeSpan totaltime = stoptime.Subtract(starttime);
label6.Text = Convert.ToString(totaltime);
textBox1.Text = folderPath;
DialogResult result2 = MessageBox.Show("Read the files successfully.", "Important message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
catch (Exception)
{
throw;
}
}
public bool ReadFile(string file, string folderPath, string folderName, string week)
{
int LineCount = 0;
string fileName = Path.GetFileNameWithoutExtension(file);
using (FileStream fs = File.Open(file, FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
for (int i = 0; i < 2; i++)
{
sr.ReadLine();
}
string oline;
while ((oline = sr.ReadLine()) != null)
{
LineCount = ++LineCount;
string[] eachLine = oline.Split(';');
string date = eachLine[30].Substring(1).Substring(0, 10);
DateTime dt;
bool valid = DateTime.TryParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
if (!valid)
{
Filecount = ++Filecount;
StreamWriter sw = new StreamWriter(folderPath + "/" + "Files_with_wrong_date_format_" + folderName + ".txt", true);
sw.WriteLine(fileName + " " + "--" + " " + "Line number :" + " " + LineCount);
sw.Close();
}
else
{
DateTime Date = DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture);
int calculatedWeek = new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(Date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Saturday);
if (calculatedWeek == Convert.ToInt32(week))
{
}
else
{
Filecount = ++Filecount;
StreamWriter sw = new StreamWriter(folderPath + "/" + "Files_with_dates_mismatching_the_respective_week_" + folderName + ".txt", true);
sw.WriteLine(fileName + " " + "--" + " " + "Line number :" + " " + LineCount);
sw.Close();
}
}
}
}
return true;
}
Since you are using Task.WaitAll(tasks.ToArray()). Wait will synchronously block until the task completes. But can you try with await (Not in TPL), await will asynchronously wait until the task completes

Categories