objusermodel not returning any value - c#

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

Related

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

how to boost my read emails c# web app speed

I wrote c# code to read emails from my gmail account, using openpop.net library, and save them into a database. Everything is going right but it is so slow in loading the emails. I tried a parallel.for loop but it gave the error:
write method can not begin while other write method is running
Is there any way to use parallel processing in this case?
This is my read emails function:
public void Read_Emails()
{
Pop3Client pop3Client;
if (Session["Pop3Client"] == null)
{
pop3Client = new Pop3Client();
pop3Client.Connect("pop.gmail.com", 995, true);
pop3Client.Authenticate(usermail, pwd, AuthenticationMethod.UsernameAndPassword);
Session["Pop3Client"] = pop3Client;
}
else
{
pop3Client = (Pop3Client)Session["Pop3Client"];
}
int count = pop3Client.GetMessageCount();
for (int i = count; i >= 1; i--)
{
Message message = pop3Client.GetMessage(i);
FFromAdress = message.Headers.From.Address;
ddate = message.Headers.DateSent;
MMessageNO = i; //message.Headers.MessageId;
List<MessagePart> attachments = message.FindAllAttachments();
DataTable dt = get_Health_Institutions();
DataTable dt1 = get_INTERIOR_Institutions();
foreach (DataRow row in dt.Rows){health_result = FFromAdress.Equals(row["mail"]);}
foreach (DataRow row in dt1.Rows){interior_result = FFromAdress.Equals(row["mail"]);}
bool result = FFromAdress.Equals("sersersetrerttrtail.com");
if (health_result == true) //|| interior_result == true)
{ SSubject = message.Headers.Subject.Split(':')[1];
MessagePart body = message.FindFirstHtmlVersion();
body = message.FindFirstPlainTextVersion();
if (body != null)
{
string BBody1 = body.GetBodyAsText();
BBody = BBody1.Replace(' ', '\n');
}
if (attachments.Count == 0)
{
atta_count = 0;
AAtachments_Path = SSubject;
if (CHKsubjectexist_Health_Date(SSubject) == 0)
{ insertmail_health_date(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
else
{ for (int m = 0; m < attachments.Count; m++)
{
atta_count = attachments.Count;
if (health_result == true & interior_result == false)
{ imagename = "healthRESULT_answer" + m+".jpg"; }
Foldername = SSubject.Trim();
AAtachments_Path = Foldername;
byte[] bdata = attachments[m].Body;
string folderpathh = "d:\\asdf\\" + Foldername;
System.IO.Directory.CreateDirectory(folderpathh);
string pathh = folderpathh + "\\" + imagename;
System.IO.File.WriteAllBytes(pathh, bdata);
////write image
String st = Server.MapPath(imagename);
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(bdata, 0, bdata.Length);
fs.Close();
}
if (CHKsubjectexist_Health_final(SSubject) == 0)
{ insertmail_Health_Final(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
}
else if (interior_result == true)
{
SSubject = message.Headers.Subject.Split(':')[1];
MessagePart body = message.FindFirstHtmlVersion();
body = message.FindFirstPlainTextVersion();
if (body != null)
{
string BBody1 = body.GetBodyAsText();
BBody = BBody1.Replace(' ', '\n');
}
if (attachments.Count == 0)
{
atta_count = 0;
AAtachments_Path = SSubject;
}
else
{
for (int m = 0; m < attachments.Count; m++)
{
atta_count = attachments.Count;
imagename = "Interior_answer" + m+".jpg";
Foldername = SSubject.Trim();
AAtachments_Path = Foldername;
byte[] bdata = attachments[m].Body;
string folderpathh = "d:\\asdf\\" + Foldername;
// System.IO.Directory.CreateDirectory(folderpathh);
string pathh = folderpathh + "\\" + imagename;
System.IO.File.WriteAllBytes(pathh, bdata);
////write image
String st = Server.MapPath(imagename);
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(bdata, 0, bdata.Length);
fs.Close();
}
}
if (CHKsubjectexist_Interior(SSubject) == 0)
{ insertmail_interior(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
else if (result == true)
{
SSubject = message.Headers.Subject;
if (CHKsubjectexist(SSubject) == 0)
{
MessagePart body = message.FindFirstHtmlVersion();
if (body != null)
{
BBody = body.GetBodyAsText();
}
else
{
body = message.FindFirstPlainTextVersion();
if (body != null)
{
BBody = body.GetBodyAsText();
}
}
if (attachments.Count == 0)
{
AAtachments_Path = " ";
}
else
{
foreach (MessagePart attachment in attachments)
{
atta_count = attachments.Count;
string filenameee = attachment.FileName;
imagename = filenameee.Split('/', '/')[3];
Foldername = SSubject;
AAtachments_Path = Foldername;
byte[] bdata = attachment.Body;
string folderpathh = "d:\\asdf\\" + Foldername;
System.IO.Directory.CreateDirectory(folderpathh);
string pathh = folderpathh + "\\" + imagename;
System.IO.File.WriteAllBytes(pathh, bdata);
////write image
String st = Server.MapPath(imagename);
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(bdata, 0, bdata.Length);
fs.Close();
}
}
if (CHKsubjectexist(SSubject) == 0)
{ insertmail(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
}
}
}

Email Works fine but got two emails at same time?

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.

exported excel sheet has no .xls file extension in Mozilla

I am using VS 2008,C#.net,asp.net.
I am exporting the data to excel 2003.
The exported excel is of the type .xls in IE and Chrome.
But it is not .xls type in mozilla.When open that file, it is asking which program you want to open?
What is the reason?
the program is mentioned below.
## Heading ##
private void ExportDataSetToExcel()
{
try
{
DataSet Ds = new DataSet();
DataTable DT = new DataTable();
string param = hidType.Get("Type").ToString();
string[] codes = param.Split('.');
if (codes.Length == 1)
FillGrid(Convert.ToString(param));
else
FillDrillDownGrid(codes[1], codes[0]);
if (hidType.Get("Type").ToString() == "2")
{
DT.Columns.Add("<b>Sub Group Code</b>");
DT.Columns.Add("<b>Account Sub Group</b>");
}
else if (hidType.Get("Type").ToString() == "3")
{
DT.Columns.Add("<b>Group Code</b>");
DT.Columns.Add("<b>Account Group</b>");
}
else
{
DT.Columns.Add("<b>Acc.Head Code</b>");
DT.Columns.Add("<b>Account Head</b>");
}
DT.Columns.Add("<b>Debit</b>");
DT.Columns.Add("<b>Credit</b>");
for (int j = 0; j < grdTrialBal.VisibleRowCount; j++)
{
DataRow DR;
DR = DT.NewRow();
if (hidType.Get("Type").ToString() == "2")
{
DR["<b>Sub Group Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Sub Group</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
else if (hidType.Get("Type").ToString() == "3")
{
DR["<b>Group Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Group</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
else
{
DR["<b>Acc.Head Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Head</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
if (Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt")) != 0)
{
DR["<b>Debit</b>"] = Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt"));
}
if (Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt")) != 0)
{
DR["<b>Credit</b>"] = Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt"));
}
CrAmount = CrAmount + Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt"));
DrAmount = DrAmount + Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt"));
DT.Rows.Add(DR);
}
DataRow Dr1;
Dr1 = DT.NewRow();
if (hidType.Get("Type").ToString() == "2")
{
Dr1["<b>Sub Group Code</b>"] = "";
Dr1["<b>Account Sub Group</b>"] = "<b>Total</b>";
}
else if (hidType.Get("Type").ToString() == "3")
{
Dr1["<b>Group Code</b>"] = "";
Dr1["<b>Account Group</b>"] = "<b>Total</b>";
}
else
{
Dr1["<b>Acc.Head Code</b>"] = "";
Dr1["<b>Account Head</b>"] = "<b>Total</b>";
}
Dr1["<b>Debit</b>"] = "<b>" + DrAmount.ToString("#0.#0") + "</b>";
Dr1["<b>Credit</b>"] = "<b>" + CrAmount.ToString("#0.#0") + "</b>";
DT.Rows.Add(Dr1);
DataGrid dg = new DataGrid();
dg.DataSource = DT;
dg.DataBind();
String strFileName = "Trial Balance Account Group Wise.xls";
if (hidType.Get("Type").ToString() == "2")
{
strFileName = "Trial Balance Account Sub Group Wise.xls";
}
else if (hidType.Get("Type").ToString() == "3")
{
strFileName = "Trial Balance Account Group Wise.xls";
}
else
{
strFileName = "Trial Balance Account Head Wise.xls";
}
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
CommonFunctions cf = new CommonFunctions();
String[] aTo = mskToDate1.Text.Split(new[] { '/', '-' });
String dTo;
dTo = aTo[0] + "/" + cf.getMonthName(Convert.ToInt32(aTo[1])) + "/" + aTo[2];
if (hidType.Get("Type").ToString() == "2")
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Sub Group Wise - As on :" + dTo + " </font></u></b>");
}
else if (hidType.Get("Type").ToString() == "3")
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Group Wise - As on :" + dTo + " </font></u></b>");
}
else
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Head Wise - As on : " + dTo + " </font></u></b>");
}
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
dg = null;
dg.Dispose();
}
catch (Exception ex)
{
}
}
set filename in double quotes
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + strFileName+ "\"");

inserting data into database for different object type at the same time?

Here is my code. I am trying to insert data by using this MyResponses(). This is my next click event.
nextclick event
{
Section surveySection = DataAccess.AccessSurveySectionByParameters(currentSurvey.EmplID, currentSurvey.UnitId, currentSurvey.SurveyId, currentSurvey.Sort.ToString(), NextStep, GetSurveyResponses());
PopulateSurveySection(currentSurvey, surveySection);
}
private string MyResponses()
{
string resp = "";
foreach (Control ctr in pnlSurveySection.Controls)
{
if (ctr is Table)
{
Table tbl = ctr as Table;
foreach (TableRow tr in tbl.Rows)
{
string sres = "";
string currid = tr.Cells[0].Attributes["ID"];
TableCell tc = tr.Cells[1];
if(currid.StartsWith("editable"))
{
currid.Substring(0, 14);
foreach (Control ctrc in tc.Controls)
{
if (ctrc is TextBox)
{
sres = currid + "||" + (ctrc as TextBox).Text.Trim();
}
else if (ctrc is RadioButtonList)
{
sres = currid + "||" + (ctrc as RadioButtonList).SelectedValue;
}
else if (ctrc is DropDownList)
{
sres = currid + "||" + (ctrc as DropDownList).SelectedValue;
}
else if (ctrc is CheckBoxList)
{
sres = currid + "||" + (ctrc as CheckBoxList).SelectedItem.ToString() + "|";
}
}
}
resp = resp + (string.IsNullOrEmpty(resp) ? "|||" : "") + sres;
}
}
It is not inserting data. and not giving me any error..Any suggestion appreciate
Thanks

Categories