public async Task <ActionResult <Mail> > Post([FromBody] MailDetails mailDetails) { _db.Mails.Add(new Mail(mailDetails)); await _db.SaveChangesAsync(); return(Ok(mailDetails)); }
public bool SendeMailItem(MailDetails mail, bool workBegin) { if (Properties.Settings.Default.Email == "") { MessageBox.Show("Please add supervisior mail"); return(false); } if (Properties.Settings.Default.MailPrompt) { DialogResult result = MessageBox.Show("Could I send mail with subject " + mail.Subject, "Work Monit", MessageBoxButtons.YesNo); if (result == DialogResult.No) { return(false); } } Outlook.MailItem mailItem = (Outlook.MailItem) this.Application.CreateItem(Outlook.OlItemType.olMailItem); mailItem.Subject = mail.Subject; mailItem.To = Properties.Settings.Default.Email; mailItem.RTFBody = mail.Body; mailItem.Importance = Outlook.OlImportance.olImportanceLow; mailItem.Send(); if (workBegin) { Properties.Settings.Default.OnWorkBeginTime = DateTime.Today; } return(true); }
private List <MailDetails> ReturnAllMailsDetails() { List <MailDetails> mailDetailsList = new List <MailDetails>(); List <string> names = new List <string>(); foreach (MAPIFolder f in nameSpace.Folders) { MAPIFolder inboxFolder = f.Store.GetDefaultFolder(OlDefaultFolders.olFolderInbox); Items items = inboxFolder.Items; foreach (var item in inboxFolder.Items) { MailItem tmp = item as MailItem; if (tmp != null) { MailDetails mailDetails = new MailDetails() { EntryID = tmp.EntryID, Subject = tmp?.Subject ?? string.Empty, FolderID = f.StoreID }; mailDetailsList.Add(mailDetails); } } } return(mailDetailsList); }
private static void prepareLoadingConfirmationMailToCustomer(Common.Agent agent) { List <Common.Order> resultList = new List <Common.Order>(); string outputFileName = string.Empty; // filter only needed customer (all the customers in the list) foreach (Common.Customer customer in Common.customerList) { resultList.AddRange(filterCustomersByName(customer.name, customer.alias)); } // filter only tomorrow's loading dates // filter only loadings sent from the country of the agent // order by consignee resultList = resultList.Where(x => agent.countries.Contains(x.fromCountry) && x.loadingDate.Date == DateTime.Now.AddDays(1).Date) .OrderBy(x => x.consignee) .Distinct() .ToList(); // check if customer has orders if (resultList.Count == 0) { OrdersParser._Form.log(string.Format("no new loadings tomorrow for {0}", agent.name)); return; } OrdersParser._Form.log(string.Format("{0} loading for tomorrow found for {1}", resultList.Count, agent.name)); // not all the columns are needed in the report - remove some List <Common.LoadingReport> targetResList = resultList.ConvertAll(x => new Common.LoadingReport { jobNo = x.jobNo, consignee = x.consignee, loadingDate = x.loadingDate, fromCountry = x.fromCountry, }); string htmlTableStr = addHtmlTable <Common.LoadingReport>(targetResList); // send mail to customer MailDetails mailDetails = new MailDetails(); mailDetails.mailRecepient = agent; mailDetails.mailType = Common.MailType.LoadingConfirmation; mailDetails.bodyParameters = new Dictionary <string, string>() { { "table", htmlTableStr }, { "date", DateTime.Now.AddDays(1).ToString(Common.DATE_FORMAT) }, { "day", DateTime.Now.AddDays(1).DayOfWeek.ToString() }, { "agent", agent.name }, }; mailDetails.subject = "Loading confirmation for tomorrow"; mailDetails.attachments = new List <string>() { }; mailDetails.bHighImportance = false; // send mail sendMail(mailDetails); }
/// <summary> /// Sends a mail to a given user or set of users using System.Net.Mail SmtpClient /// </summary> /// <param name="mailDetails"></param> public void SendMail(MailDetails mailDetails) { var mailMessage = new MailMessage(); var smtpClient = new SmtpClient(); try { //Adds each email in Receivers to the MailAddressCollection foreach (string receiver in mailDetails.Recievers) { mailMessage.To.Add(new MailAddress(receiver)); } //Configures the sender, receiver(s), title and body of the message to be sent mailMessage.From = new MailAddress(_mailSettings.Mail); mailMessage.Subject = mailDetails.MessageTitle; mailMessage.IsBodyHtml = true; mailMessage.Body = mailDetails.MessageBody; smtpClient.Port = _mailSettings.Port; smtpClient.Host = _mailSettings.Server; smtpClient.UseDefaultCredentials = false; smtpClient.EnableSsl = true; smtpClient.Credentials = new NetworkCredential(_mailSettings.Mail, _mailSettings.Password); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Send(mailMessage); } catch (Exception e) { } }
public void NotValidEmail() { //Arrange var mailDetails = new MailDetails(); const string mailAddress = "john.smith.company.com"; //Act bool isValid = mailDetails.IsValidAddress(mailAddress); //Assert Assert.False(isValid, $"The email {mailAddress} is valid, but it shouldn’t"); }
public static bool SendMail(MailDetails MailDetails) { bool flag = false; System.Net.Mail.SmtpClient objMail = new System.Net.Mail.SmtpClient(); System.Net.Mail.MailMessage msgMail = new System.Net.Mail.MailMessage(); msgMail.To.Clear(); try { var fromAddress = new MailAddress(ConfigurationManager.AppSettings["MailUID"].ToString().Trim(), ConfigurationManager.AppSettings["MailUName"].ToString().Trim()); string fromPassword = ConfigurationManager.AppSettings["MailPassword"].ToString().Trim(); if (!string.IsNullOrEmpty(MailDetails.ToMailIDs)) { foreach (var MailID in MailDetails.ToMailIDs.Split(',')) { if (!string.IsNullOrEmpty(MailID.Trim())) { msgMail.To.Add(new System.Net.Mail.MailAddress(MailID.Trim())); } } } var smtp = new SmtpClient { Host = Convert.ToString(ConfigurationManager.AppSettings["Host"].ToString().Trim()),//"smtp.gmail.com", Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"].ToString().Trim()), EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"].ToString().Trim()), DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress.Address, msgMail.To.ToString()) { Subject = MailDetails.Subject, IsBodyHtml = MailDetails.HTMLBody, Body = MailDetails.Body, }) { smtp.Send(message); flag = true; } } catch (Exception ex) { ExecptionLogger.FileHandling("BALMail(sendMail)", "Error_014", ex, "BALMail"); flag = false; } return(flag); }
// function goes over the selected rows from the data grid and sends mails to agents private static void prepareDocumentsReceiptsMailToAgent(Common.Agent agent, List <Common.SailsReport> report) { string outputFileName = string.Empty; // filter only shipping sent from the country of the agent // order by consignee report = report.Where(x => agent.countries.Contains(x.fromCountry)) .OrderBy(x => x.sailingDate) .ToList(); // check if customer has orders if (report.Count == 0) { return; } OrdersParser._Form.log(string.Format("Documents receipts are needed from {0} on {1} sailings", agent.name, report.Count)); // not all the columns are needed in the report - remove some List <Common.SailsReport> targetResList = report.ConvertAll(x => new Common.SailsReport { jobNo = x.jobNo, shipper = x.shipper, consignee = x.consignee, tankNum = x.tankNum, fromCountry = x.fromCountry, sailingDate = x.sailingDate, }); string htmlTableStr = addHtmlTable <Common.SailsReport>(targetResList); // send mail to customer MailDetails mailDetails = new MailDetails(); mailDetails.mailRecepient = agent; mailDetails.mailType = Common.MailType.DocumentsReceipts; mailDetails.bodyParameters = new Dictionary <string, string>() { { "table", htmlTableStr }, { "agent", agent.name }, }; mailDetails.subject = "BL is missing"; mailDetails.attachments = new List <string>() { }; mailDetails.bHighImportance = false; // send mail sendMail(mailDetails); }
private string generatefiles(DataSet ds, DataTable dt1, string fromdate, string todate, string FirstPath, DataTable mailsetting) { try { DataView dv = new DataView(ds.Tables[0]); string strAttachFirst = string.Empty; string strAttachSecond = string.Empty; bool isSendData = false; System.Collections.ArrayList objList = new ArrayList(); objList.Add(MailSetting(mailsetting)); CrystalDecisions.CrystalReports.Engine.ReportDocument crystalReport; foreach (DataRow Row in dt1.Rows) { MailDetails objMails = new MailDetails(); dv.RowFilter = "SuperZoneID = " + Row["SuperZoneID"].ToString(); crystalReport = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); crystalReport.Load(Server.MapPath("../Report/MissingRecieptNo.rpt")); crystalReport.SetDataSource(dv.ToTable()); crystalReport.SetParameterValue("FromDP", Convert.ToDateTime(fromdate)); crystalReport.SetParameterValue("TODp", Convert.ToDateTime(todate)); isSendData = dv.ToTable().Rows.Count > 0 ? true : false; strAttachFirst = Server.MapPath(FirstPath + "MissingRecieptNo_" + Convert.ToDateTime(fromdate).ToString("dd-MMM-yyyy") + "_" + Convert.ToDateTime(todate).ToString("dd-MMM-yyyy") + "_" + Row["SuperZoneID"].ToString() + ".pdf"); crystalReport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, strAttachFirst); crystalReport.Close(); crystalReport.Dispose(); crystalReport = null; objMails.Attachment = strAttachSecond != "" ? strAttachFirst + "," + strAttachSecond : strAttachFirst; objMails.Name = Row["SuperZoneName"].ToString(); objMails.EmailId = Row["Email"].ToString(); string makesubject = "Missing Receipts from " + Convert.ToDateTime(fromdate).ToString("dd-MMM-yyyy") + " TO " + Convert.ToDateTime(todate).ToString("dd-MMM-yyyy"); objMails.Subject = makesubject; objMails.Desc = makesubject; if (isSendData) { objList.Add(objMails); } objMails = null; } return(JsonConvert.SerializeObject(objList)); } catch (Exception ex) { throw; } }
public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model) { if (!ModelState.IsValid) { return(View(model)); } //Validates existense of user var user = await _userMngr.FindByEmailAsync(model.EmailAddress); if (user == null) { ModelState.AddModelError("", $"User with email address {model.EmailAddress} does not exist!"); return(View(model)); } //Generates password recovery token var token = _userMngr.GeneratePasswordResetTokenAsync(user); //Generates an action link to route a user to a recovery page with token var resetLink = Url.Action("ResetPassword", "Account", new { token, user.Email }, Request.Scheme); //sends the reset link as a mail to the user var mailDetails = new MailDetails { MessageTitle = "PASSWORD RESET", MessageBody = $"Click the link to reset your password. {resetLink}", Recievers = new List <string> { user.Email } }; try { _mailService.SendMail(mailDetails); ViewBag.SuccessMsg = "Email sent. Check your inbox"; } catch (Exception e) { _logger.LogError(e.Message); } return(View()); }
private SendMailResponse SendPasswordChangedNotificationEmail(string email, string userName) { SendMailResponse result = null; MailDetails datails = new MailDetails(); datails.MessageType = "PasswordChangedConfirmation"; datails.ToAddress = email; datails.Parameters.Add("UserName", userName); SendMail sendMailRequest = new SendMail(); sendMailRequest.SessionToken = ConfigurationManager.AppSettings["MailServiceSessionToken"]; sendMailRequest.Details.Add(datails); Client.Mail.ServiceClient client = new Client.Mail.ServiceClient(); result = client.PostSendMail(sendMailRequest); return(result); }
public JsonResult GetOTP(string UID) { BALCommon obj = new BALCommon(ConStr); bool res = false; string message = ""; try { string OTP = Utility.GetRendomString(6, "N"); res = obj.SetOTP(UID, OTP); #region SendMail if (res) { BALCommon CSvc = new BALCommon(ConStr); UserMasters userMasters = CSvc.getUserProfile(UID); MailDetails _MailDetails = new MailDetails(); _MailDetails.ToMailIDs = userMasters.EMAILID; _MailDetails.HTMLBody = true; _MailDetails.Subject = "Reset OTP"; _MailDetails.Body = BALMail.TemplateResetOTP(userMasters, AESEncrytDecry.EncryptStringAES(OTP)); if (BALMail.SendMail(_MailDetails)) { message = "OTP has been sent to your registered mail id."; } else { message = "Please contact technical team"; } } else { message = "Please contact technical team"; } #endregion SendMail } catch (Exception ex) { res = false; } return(Json(message, JsonRequestBehavior.AllowGet)); }
private SendMailResponse SendAccountConfirmEmail(string email, string accountKey, string userName) { SendMailResponse result = null; MailDetails datails = new MailDetails(); datails.MessageType = "AccountCreatedConfirmation"; datails.ToAddress = email; datails.Parameters.Add("UserName", userName); datails.Parameters.Add("AccountKey", accountKey); datails.Parameters.Add("Login", email); SendMail sendMailRequest = new SendMail(); sendMailRequest.SessionToken = ConfigurationManager.AppSettings["MailServiceSessionToken"]; sendMailRequest.Details.Add(datails); Client.Mail.ServiceClient client = new Client.Mail.ServiceClient(); result = client.PostSendMail(sendMailRequest); return(result); }
private List <MailDetails> ReturnAllFoundMailsDetails(List <MailDetails> mailDetailList, string search) { int howManySubjectsFound = mailDetailList.Where(x => x.Subject.Contains(search)).Count(); List <MailDetails> foundMailDetailsList = new List <MailDetails>(); if (howManySubjectsFound > 0) { foreach (var item in mailDetailList) { if (item.Subject.Contains(search)) { MailDetails foundMailDetails = new MailDetails() { EntryID = item.EntryID, Subject = item.Subject, FolderID = item.FolderID }; foundMailDetailsList.Add(foundMailDetails); } } } return(foundMailDetailsList); }
// basic template function to send mail to specific customer private static void sendMail(MailDetails mailDetails) { OutlookInterop._MailItem oMailItem = null; OutlookInterop.Attachment attachment = null; string bodyMsg = string.Empty; string signatureName = SIGNATURE_LOGO_NAME; string signatureFilePath = Path.Combine(Directory.GetCurrentDirectory(), signatureName); string tempMsg = string.Empty; // generate logo file from embedded resource (image) if (File.Exists(signatureFilePath) == false) { ImageConverter converter = new ImageConverter(); byte[] tempByteArr = (byte[])converter.ConvertTo(Anko.Properties.Resources.logo, typeof(byte[])); File.WriteAllBytes(signatureFilePath, tempByteArr); } // outlook can be null in the first time if (outlookApp == null) { init(); } try { // initiate outlook parameters oMailItem = (OutlookInterop._MailItem)outlookApp.CreateItem(OutlookInterop.OlItemType.olMailItem); } catch (Exception e) { OrdersParser._Form.log(string.Format("Failed to create mail. Error: {0}", e.Message), OrdersParser.LogLevel.Error); dispose(); return; } OutlookInterop.Recipient mailTo; OutlookInterop.Recipient mailCc; OutlookInterop.Recipients toList = oMailItem.Recipients; OutlookInterop.Recipients ccList = oMailItem.Recipients; // TO foreach (String recipient in mailDetails.mailRecepient.to) { mailTo = toList.Add(recipient); mailTo.Type = (int)OutlookInterop.OlMailRecipientType.olTo; mailTo.Resolve(); } // CC foreach (String recipient in mailDetails.mailRecepient.cc) { mailCc = ccList.Add(recipient); mailCc.Type = (int)OutlookInterop.OlMailRecipientType.olCC; mailCc.Resolve(); } // add Subject oMailItem.Subject = mailDetails.subject; // add attachment excel file foreach (string filePath in mailDetails.attachments) { oMailItem.Attachments.Add(filePath, OutlookInterop.OlAttachmentType.olByValue, 1, Path.GetFileName(filePath)); } // verify that signature file exists if (File.Exists(signatureFilePath) == true) { // prepare body attachment = oMailItem.Attachments.Add(signatureFilePath, OutlookInterop.OlAttachmentType.olEmbeddeditem, null, string.Empty); attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", signatureName); } else { OrdersParser._Form.log(string.Format("Cannot find signature logo in {0}", signatureFilePath), OrdersParser.LogLevel.Error); } bodyMsg += addHtmlPreffix(); // message (based on templates from mailType) bodyMsg += addMailBodyMsg(mailDetails.mailType, mailDetails.bodyParameters); // signature bodyMsg += addMailSignature(signatureName); oMailItem.BodyFormat = OutlookInterop.OlBodyFormat.olFormatHTML; oMailItem.HTMLBody = bodyMsg; // mark as high importance if (mailDetails.bHighImportance) { oMailItem.Importance = OutlookInterop.OlImportance.olImportanceHigh; } // async - display mail and proceed oMailItem.Display(false); }
// function prepares booking mail to shipping company private static void prepareBookingMailToAgent(Common.ShippingCompany shippingCompany) { List <Common.Order> resultList = new List <Common.Order>(); string outputFileName = string.Empty; int bookingDays = 5; // filter only needed customer (all the customers in the list) foreach (Common.Customer customer in Common.customerList) { resultList.AddRange(filterCustomersByName(customer.name, customer.alias)); } // filter only tomorrow's loading dates // filter only loadings sent from the country of the agent // order by consignee resultList = resultList.Where(x => x.sailingDate.Date == DateTime.Now.AddDays(bookingDays).Date&& x.MBL.ToLower().StartsWith(shippingCompany.id.ToLower())) .OrderBy(x => x.sailingDate) .Distinct() .ToList(); // check if customer has orders if (resultList.Count == 0) { OrdersParser._Form.log(string.Format("no new bookings in {0} days for {1}", bookingDays, shippingCompany.shippingLine)); return; } OrdersParser._Form.log(string.Format("{0} bookings in {1} days found for {2}", resultList.Count, bookingDays, shippingCompany.shippingLine)); // not all the columns are needed in the report - remove some List <Common.BookingsReport> targetResList = resultList.ConvertAll(x => new Common.BookingsReport { jobNo = x.jobNo, fromCountry = x.fromCountry, sailingDate = x.sailingDate, toCountry = x.toCountry, toPlace = x.toPlace, vessel = x.vessel, voyage = x.voyage, MBL = x.MBL, }); string htmlTableStr = addHtmlTable <Common.BookingsReport>(targetResList); // send mail to customer MailDetails mailDetails = new MailDetails(); mailDetails.mailRecepient = shippingCompany; mailDetails.mailType = Common.MailType.BookingConfirmation; mailDetails.bodyParameters = new Dictionary <string, string>() { { "table", htmlTableStr }, { "agent", shippingCompany.name }, }; mailDetails.subject = string.Format("Booking confirmation for the upcoming {0} days", bookingDays); mailDetails.attachments = new List <string>() { }; mailDetails.bHighImportance = false; // send mail sendMail(mailDetails); }
public void CheckEmail(string mailAddress, bool expectedTestResult) { var mailDetails = new MailDetails(); Assert.Equal(expectedTestResult, mailDetails.IsValidAddress(mailAddress)); }
// function prepares mail per customer in case it has any orders private static void prepareOrdersMailToCustomer(Common.Customer customer) { DateTime now = DateTime.Now; string outputFileName = string.Empty; int rows = 0; int cols = 0; // filter the list for certain customer // filter out past arrivals // order by arrival date List <Common.Order> resultList = filterCustomersByName(customer.name, customer.alias).Where(x => x.arrivalDate > now) .OrderBy(x => x.arrivalDate) .Distinct() .ToList(); // check if customer has orders if (resultList.Count == 0) { OrdersParser._Form.log(string.Format("{0}: no new orders for this customer - mail won't be sent", customer.name)); return; } OrdersParser._Form.log(string.Format("{0}: {1} new orders found", customer.name, resultList.Count)); // not all the columns are needed in the report - remove some List <Common.OrderReport> targetResList = resultList.ConvertAll(x => new Common.OrderReport { jobNo = x.jobNo, shipper = x.shipper, consignee = x.consignee, customerRef = x.customerRef, tankNum = x.tankNum, activity = x.activity, loadingDate = x.loadingDate, fromCountry = x.fromCountry, fromPlace = x.fromPlace, sailingDate = x.sailingDate, toCountry = x.toCountry, toPlace = x.toPlace, arrivalDate = x.arrivalDate, productName = x.productName, vessel = x.vessel, voyage = x.voyage, }); // prepare 2d array for excel print object[,] valuesArray = Utils.generateObjectFromList <Common.OrderReport>(targetResList, out rows, out cols); // create new excel file with this data // to make sure that file name is unique add high time accuracey string extendedTimeFormat = string.Concat(Common.DATE_FORMAT, "_fffffff"); outputFileName = Path.Combine(Utils.resultsDirectoryPath, string.Format("{0}_{1}.{2}", customer.name, now.ToString(extendedTimeFormat), "xlsx")); Excel.generateCustomerFile(valuesArray, rows, cols, customer, outputFileName); // send mail to customer MailDetails mailDetails = new MailDetails(); mailDetails.mailRecepient = customer; mailDetails.mailType = Common.MailType.Reports; mailDetails.bodyParameters = new Dictionary <string, string>() { { "arrivalDate", resultList.FirstOrDefault().arrivalDate.ToString(Common.DATE_FORMAT) }, { "totalNumOfOrders", resultList.Count.ToString() } }; mailDetails.subject = "דו'ח סטטוס הזמנות"; mailDetails.attachments = new List <string>() { outputFileName }; mailDetails.bHighImportance = true; // send mail sendMail(mailDetails); }
public async Task <IActionResult> SignUp(SignUpViewModel model) { if (!ModelState.IsValid) //if the modelstate returned is not valid { return(View()); //A view is returned showing the validation errors thrown by the models } string imagePath = string.Empty; if (model.Image != null) { imagePath = _imageServices.ImageUpload(model); } if (await _userMngr.FindByEmailAsync(model.EmailAddress) != null) { //returns error message if email already exists in database ModelState.AddModelError("", "User with email already exists!"); return(View(model)); } BlogUser user = new BlogUser { FirstName = model.FirstName, LastName = model.LastName, Email = model.EmailAddress, UserName = model.UserName, ProfilePhoto = imagePath }; try { var result = await _userMngr.CreateAsync(user, model.Password); //creates a user and sets password if (!result.Succeeded) { foreach (var err in result.Errors) { ModelState.AddModelError("", err.Description); } return(View(model)); } await _userMngr.AddToRoleAsync(user, "Member"); //assign member role to a new user by default //sends a congratulatory mail to the new user var mailDetails = new MailDetails { MessageTitle = "CONGRATULATIONS", MessageBody = $"Congratulations {user.UserName}, you are now a member of the elite community of readers and writers here at BLOGIT. Remember, Readers are leaders!!!", Recievers = new List <string> { user.Email } }; _mailService.SendMail(mailDetails); } catch (Exception e) { _logger.LogError(e.Message); } //signs in the new user and returns to the home index view await _signInMngr.PasswordSignInAsync(user, model.Password, false, false); return(RedirectToAction("Index", "Home")); }
private string generatefiles(DataSet ds, DataSet ds1, DataTable dt1, string fromdate, string todate, string s_fromdate, string s_todate, string FirstPath, string SecondPath, DataTable mailsetting) { try { bool isSecondDataPresent = false; DataView dv = new DataView(ds.Tables[0]); DataView dv1 = new DataView(); bool isSendFirstData = false; bool isSendSecondata = false; if (ds1 != null) { isSecondDataPresent = true; dv1.Table = ds1.Tables[0]; } string strAttachFirst = string.Empty; string strAttachSecond = string.Empty; System.Collections.ArrayList objList = new ArrayList(); objList.Add(MailSetting(mailsetting)); CrystalDecisions.CrystalReports.Engine.ReportDocument crystalReport; foreach (DataRow Row in dt1.Rows) { MailDetails objMails = new MailDetails(); #region First Data dv.RowFilter = "Superzone = " + Row["SuperZoneID"].ToString(); crystalReport = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); crystalReport.Load(Server.MapPath("../Report/CollectionReport.rpt")); crystalReport.SetDataSource(dv.ToTable()); isSendFirstData = dv.ToTable().Rows.Count > 0 ? true : false; strAttachFirst = Server.MapPath(FirstPath + "Wkly_Col_" + Convert.ToDateTime(fromdate).ToString("dd-MMM-yy") + "_" + Convert.ToDateTime(todate).ToString("dd-MMM-yyyy") + "_" + Row["SuperZoneID"].ToString() + ".pdf"); crystalReport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, strAttachFirst); crystalReport.Close(); crystalReport.Dispose(); crystalReport = null; #endregion #region "Second Data" if (isSecondDataPresent) { dv1.RowFilter = "Superzone = " + Row["SuperZoneID"].ToString(); crystalReport = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); crystalReport.Load(Server.MapPath("../Report/CollectionReport.rpt")); crystalReport.SetDataSource(dv1.ToTable()); isSendSecondata = dv1.ToTable().Rows.Count > 0 ? true : false; strAttachSecond = Server.MapPath(SecondPath + "_Wkly_Col_" + Convert.ToDateTime(s_fromdate).ToString("dd-MMM-yy") + "_" + Convert.ToDateTime(s_todate).ToString("dd-MMM-yy") + "_" + Row["SuperZoneID"].ToString() + ".pdf"); crystalReport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, strAttachSecond); crystalReport.Close(); crystalReport.Dispose(); crystalReport = null; } #endregion objMails.Attachment = strAttachSecond != "" ? strAttachFirst + "," + strAttachSecond : strAttachFirst; objMails.Name = Row["SuperZoneName"].ToString(); objMails.EmailId = Row["Email"].ToString(); string makesubject = "Collection from " + (isSecondDataPresent == true ? Convert.ToDateTime(fromdate).ToString("dd-MMM-yyyy") + " TO " + Convert.ToDateTime(todate).ToString("dd-MMM-yyyy") + " & " + Convert.ToDateTime(s_fromdate).ToString("dd-MMM-yyyy") + " TO " + Convert.ToDateTime(s_todate).ToString("dd-MMM-yyyy") : Convert.ToDateTime(fromdate).ToString("dd-MMM-yyyy") + " TO " + Convert.ToDateTime(todate).ToString("dd-MMM-yyyy")); objMails.Subject = makesubject; objMails.Desc = makesubject; if (isSendFirstData) { objList.Add(objMails); } objMails = null; } return(JsonConvert.SerializeObject(objList)); } catch (Exception ex) { throw; } }
private string generatefiles(DataSet ds, string FirstPath, DataTable mailsetting) { try { DataView dvmaster = new DataView(ds.Tables[0]); DataView dv = new DataView(ds.Tables[1]); string strAttachFirst = string.Empty; string strAttachSecond = string.Empty; bool isSendData = false; System.Collections.ArrayList objList = new ArrayList(); CrystalDecisions.CrystalReports.Engine.ReportDocument crystalReport; objList.Add(MailSetting(mailsetting)); XmlDocument doc = new XmlDocument(); XmlNode inode = doc.CreateElement("f"); XmlNode fnode = doc.CreateElement("r"); foreach (DataRow Row in ds.Tables[0].Rows) { MailDetails objMails = new MailDetails(); dv.RowFilter = "SubDocId = " + Row["subdocno"].ToString(); dvmaster.RowFilter = "subdocno = " + Row["subdocno"].ToString(); crystalReport = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); crystalReport.Load(Server.MapPath("../Report/PrintInvoiceMM.rpt")); crystalReport.SetDataSource(dv); isSendData = dv.ToTable().Rows.Count > 0 ? true : false; strAttachFirst = Server.MapPath(FirstPath + dvmaster[0]["CustCode"] + "-" + dvmaster[0]["subdocno"] + ".pdf"); crystalReport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, strAttachFirst); crystalReport.Close(); crystalReport.Dispose(); crystalReport = null; objMails.Attachment = strAttachSecond != "" ? strAttachFirst + "," + strAttachSecond : strAttachFirst; objMails.Name = dvmaster[0]["CustName"].ToString(); objMails.EmailId = Row["EmailID"].ToString(); string makesubject = dvmaster[0]["subject"].ToString(); objMails.Subject = makesubject; objMails.Desc = Row["msg"].ToString(); XmlNode element = doc.CreateElement("i"); inode = doc.CreateElement("subdoc"); inode.InnerText = Row["subdocno"].ToString(); element.AppendChild(inode); inode = doc.CreateElement("fyu"); inode.InnerText = Row["FY"].ToString(); element.AppendChild(inode); inode = doc.CreateElement("mod"); inode.InnerText = Row["module"].ToString(); element.AppendChild(inode); fnode.AppendChild(element); if (isSendData) { objList.Add(objMails); } objMails = null; } Other_Z.OtherBAL ObjBal = new Other_Z.OtherBAL(); ObjBal.UpdateEmailLog(fnode.OuterXml, "", "", ""); return(JsonConvert.SerializeObject(objList)); } catch (Exception ex) { throw; } }
public ActionResult Create(SignupModel model, FormCollection collection) { BALCommon CSvc = new BALCommon(ConStr); OragnisationMaster master = new OragnisationMaster(); //model.CountryList = CSvc.GetCountryList(0); //model.CityList = CSvc.GetCityList(0, 0); //model.StateList = CSvc.GetStateList(0, 0); if (ModelState.IsValid) { try { master = CSvc.GetOragnisationAlready(model.LEmailId); if (master.OMID == 0) { HttpPostedFileBase empimg = Request.Files["emppathimage"]; string folderpath = Constants.EMPATTACHMENT; if (empimg.ContentLength > 0) { string guidstring = Guid.NewGuid().ToString(); string _FileName = Path.GetFileName(empimg.FileName); string filepath = Path.Combine(Server.MapPath(folderpath) + guidstring + "_" + _FileName); string dbpath = Path.Combine(folderpath + guidstring + "_" + _FileName); empimg.SaveAs(filepath); master.OrgImage = dbpath; } else { string _FileName = "schooldummylogo.png"; string dbpath = Path.Combine(folderpath + _FileName); master.OrgImage = dbpath; } master.Oname = model.Oname; master.BOAddress = model.BOAddress; master.BOAddress2 = model.BOAddress2; master.BOCity = model.CITY_ID; master.BOPincode = model.BOPincode; master.LCountry = model.COUNTRY_ID; master.LState = model.STATE_ID; master.LDistict = model.LDistict; master.LArea = model.LArea; master.LEmailId = model.LEmailId; master.LMobile = model.LMobile; master.LPhone = model.LPhone; master.LWebsite = model.LWebsite; master.OAfficilate = model.OAfficilate; master.OlicNo = model.OlicNo; master.OTaxNo = model.OTaxNo; master.OPanNo = model.OPanNo; master.OContactNo = model.OContactNo; master.IsActive = false; master.Createddate = DateTime.Now; master.Modifieddate = DateTime.Now; master.CreatedBy = "EndUser"; master.ModifiedBy = "EndUser"; master.Otype = "INS"; // to check int _retua = CSvc.OragnasitionBasicopation(master); if (_retua > 0) { string Password = Utility.GenerateRandomPassword(); WebSecurity.CreateUserAndAccount(master.LEmailId, Password, new { Name = master.OContactNo, Mobile = master.LMobile, EmailId = master.LEmailId, Address = master.BOAddress, RoleId = 1, CITY_ID = master.BOCity, STATE_ID = master.LState, COUNTRY_ID = master.LCountry, ISACTIVE = 0, SchoolID = _retua }); CSvc.Firstuserconfigure(_retua);//first user configure //TempData[Constants.MessageInfo.SUCCESS] = Constants.Orgnisation_ADD_SUCCESS; #region SendMail MailDetails _MailDetails = new MailDetails(); _MailDetails.ToMailIDs = master.LEmailId; _MailDetails.HTMLBody = true; _MailDetails.Subject = "Organisation Registration"; _MailDetails.Body = BALMail.TemplateOrganisation(master, AESEncrytDecry.EncryptStringAES(Password)); if (BALMail.SendMail(_MailDetails)) { TempData[Constants.MessageInfo.SUCCESS] = Constants.Orgnisation_ADD_SUCCESS + ", Please check your mail inbox for more information."; } else { TempData[Constants.MessageInfo.SUCCESS] = Constants.Orgnisation_ADD_SUCCESS; } #endregion SendMail return(RedirectToAction("login")); } } else { TempData[Constants.MessageInfo.SUCCESS] = "Orgnisation is already Exist !"; return(RedirectToAction("Create")); } } catch (Exception ex) { WebSecurity.Logout(); ExecptionLogger.FileHandling("Account(Create_Post)", "Error_014", ex, "Account"); } } return(View(model)); }