Below is the code for sending mail.Iam not getting any error or exception but when mail is triggered iam getting blank fields for region name,location name and partner code. Partner name also is displayed.
if (objUser.UserMasterId == 0)
{
objUser.FunctionalityId = 10; //Partner Creation
dtPartnerMailDetails = UserMasterBL.GetPartnerMailDetails(objUser);
if (dtPartnerMailDetails.Rows.Count > 0)
{
objUser.RegionName = dtPartnerMailDetails.Rows[0]["RegionName"].ToString();
objUser.LocationName = dtPartnerMailDetails.Rows[0]["LocationName"].ToString();
objUser.PartnerCode = dtPartnerMailDetails.Rows[0]["PartnerCode"].ToString();
objUser.PartnerName = dtPartnerMailDetails.Rows[0]["partnername"].ToString();
}
dtMailDetails = UserMasterBL.GetMailDetails(objUser);
if (dtMailDetails.Rows.Count > 0)
{
string strMailFROM = "WiproIMSCertificationPortal#wipro.com";
string ToMailIds = dtMailDetails.Rows[0]["ToMailIds"].ToString();
string CCMailIds = dtMailDetails.Rows[0]["CCMailIds"].ToString();
/* string Region = dtPartnerMailDetails.Rows[0]["regionname"].ToString();
string Location = dtPartnerMailDetails.Rows[0]["locationname"].ToString();
string PartnerCode = dtPartnerMailDetails.Rows[0]["PartnerCode"].ToString();
string partnername = dtPartnerMailDetails.Rows[0]["partnername"].ToString();*/
string Region = objUser.RegionName;
string Location = objUser.LocationName;
string PartnerCode = objUser.PartnerCode;
string PartnerName = objUser.PartnerName;
//string partnercodeauto = objUser.PartnerCodeid;
string strmailBody = "<html><body><font face='Verdana' size=2 color=#0E6192>";
strmailBody += "Dear Administrator " + "<br/><br/>";
strmailBody += "Kindly approve below request, Created by " + objUser.PartnerName + "<br/> <br/>";
strmailBody += "<br/><br/>";
strmailBody += "<table border=1><tr><td><b>sl no </b></td><td><b>Region</b></td><td><b>Location</b></td><td><b>Partner Name</b></td><td><b>Partner Code</b></td>";
strmailBody += "<tr><td>1 </td><td>" + Region + "</td><td> " + Location + " </td><td>" + PartnerName + " </td><td>" + PartnerCode + " </td></tr></table>";
strmailBody += "<br/><br/>";
strmailBody += "</body></html>";
strmailBody += "Best Regards" + "<br/>" + " IMS Team";
strmailBody += "<br/><br/>";
strmailBody += "Disclaimer: This is a system generated mail. Please do not reply to this mail. For any queries, Please log a call in https://serviceconnect.wipro.com <br/>";
string strMailSubject = "Partner Addition " + objUser.PartnerCode + "";
Helper.Sendmail(strMailFROM, ToMailIds, strMailSubject, strmailBody, CCMailIds, null, null);
}
Data layer code:
public static DataTable GetPartnerMailDetails(UserMasterOL objUser)
{
if (objUser == null)
{
throw new ArgumentNullException("objUser");
}
DataTable dtGetPartnerMailDetails = new DataTable();
dtGetPartnerMailDetails.Locale = CultureInfo.InvariantCulture;
try
{
DbCommand DbCmd = DataAccessbase.Database.GetStoredProcCommand(Constants.GetPartnerCreationMailDetails);
DataAccessbase.Database.AddInParameter(DbCmd, "#PartnerCode", DbType.String, objUser.PartnerCode);
dtGetPartnerMailDetails = DataAccessbase.Database.ExecuteDataSet(DbCmd).Tables[0];
}
stored procedure:
ALTER PROCEDURE [dbo].[GetPartnerCreationMailDetails]
(
#PartnerCode INT
)
AS
BEGIN
SET NOCOUNT ON
select rm.regionname,pm.PartnerCode,pm.partnername,lm.locationname from partnermaster pm
inner join regionmaster rm on
rm.regionid=pm.regionid
inner join locationmaster lm on
lm.locationid=pm.locationid
where pm.PartnerCode=#PartnerCode
end
Try closing the TR on this line:
strmailBody += "<table border=1><tr><td><b>sl no </b></td><td><b>Region</b></td><td><b>Location</b></td><td><b>Partner Name</b></td><td><b>Partner Code</b></td>";
It should be
strmailBody += "<table border=1><tr><td><b>sl no </b></td><td><b>Region</b></td><td><b>Location</b></td><td><b>Partner Name</b></td><td><b>Partner Code</b></td></tr>";
Related
Hello i'm developing a little application that download attachment from unread mails by imap and make a sevarla job on this attachment. Problem is encoding because after i have saved a, for example, txt file, when i load it again letters with accents becomes "?" I dont know why. I tried a several example around on the web (like converting directly the file from ansi to utf-8) with no result. Whe i open a file in windows it works, words are correct.
i have used either ReadAllText that StreamReader in the following example:
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
as you can see in the following example if i set directly a string with an accent word, it works, from file no.
Please help me!
check image
Reproducible Code:
using CsvHelper;
using NLog;
using System;
using System.Data;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class Class1
{
public static void test2()
{
using (var client = new ImapClient())
{
try
{
int porta = Convert.ToInt32(par.portaimap);
bool ssl = Convert.ToBoolean(par.sslimap);
client.Connect(par.host, porta, ssl);
Logger.Info("Connessione server posta riuscita");
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
try
{
Logger.Info("Autenticazione in corso");
client.Authenticate(par.usernameimap, par.passwordimap);
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
// The Inbox folder is always available on all IMAP servers...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadWrite);
Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Recent);
var query = SearchQuery.NotSeen;//SearchQuery.SubjectContains("MimeKit").Or(SearchQuery.SubjectContains("MailKit"));
var uids = client.Inbox.Search(query);
var items = client.Inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
Logger.Info("Selezione lista di email non lette");
foreach (var summary in items)
{
var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\", summary.UniqueId.ToString());
// create the directory
Directory.CreateDirectory(directory);
if (summary.Body is BodyPartMultipart)
Logger.Info("Download allegati in corso.");
foreach (var attachment in summary.Attachments)
{
var entity = client.Inbox.GetBodyPart(summary.UniqueId, attachment);
var part = (MimePart)entity;
// note: it's possible for this to be null, but most will specify a filename
var fileName = part.FileName;
var path = Path.Combine(directory, fileName);
try
{
using (var stream = File.Create(path))
part.Content.DecodeTo(stream);
Logger.Info("Allegato scaricato.");
}
catch (Exception ex)
{
Logger.Error("Allegato non scaricato. Di seguito errore: " + ex.Message);
}
int scelta = 0;
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
Console.WriteLine(contents);
Console.ReadLine();
contents = "Proprietà";
Console.WriteLine(contents);
Console.ReadLine();
string ext = Path.GetExtension(fileName);
SmtpSettings smtpSettings = new SmtpSettings();
smtpSettings.SenderName = "Test";
smtpSettings.server = "smtp.gmail.com";
smtpSettings.Port = 587;
smtpSettings.SenderMail = par.usernameimap;
smtpSettings.Username = par.usernameimap;
smtpSettings.Password = par.passwordimap;
smtpSettings.ToMail1Name = "Test1";
smtpSettings.ToMail1 = "test1#gmail.com";
smtpSettings.ToMail2Name = "Test2";
smtpSettings.ToMail2 = "Test2#bsolution.org";
string PATHTODELETE = "";
if (ext == ".txt")
{
string line1 = File.ReadLines(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName).First();
if (line1 == "FOR|CLIEN|STAB|INSEGNA|INDIRIZZO|CAP|LUOGO|PROV|ORDINE|POS|STATO|DTORD|ORAORD|MALFUNZIONE|COD_RIS|RISORSA|TERMID|ESESIA|STABSIA|ABI|TELEFONO|NOTE|COD_HOST|ACCESSORIO|DESC_HOST|MOD_COLLEG|FUNZ. AGG:|REFERENTE|DT_SCADENZA|LAKA|")
{
DataTable dt;
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.Delimiter = "|";
// Do any configuration to `CsvReader` before creating CsvDataReader.
using (var dr = new CsvDataReader(csv))
{
dt = new DataTable();
dt.Load(dr);
reader.Close();
}
}
//Costruzione body mail csv
string value = "";
string filename = "";
string Msg = "";
foreach (DataRow drow in dt.Rows)
{
value = "";
value += "FOR: " + drow["FOR"].ToString() + "\n";
value += "CLIEN: " + drow["CLIEN"].ToString() + "\n";
value += "STAB: " + drow["STAB"].ToString() + "\n";
value += "INSEGNA: " + drow["INSEGNA"].ToString() + "\n";
value += "INDIRIZZO: " + drow["INDIRIZZO"].ToString() + "\n";
value += "LUOGO: " + drow["LUOGO"].ToString() + "\n";
value += "ORDINE: " + drow["ORDINE"].ToString() + "\n";
value += "POS: " + drow["POS"].ToString() + "\n";
value += "STATO: " + drow["STATO"].ToString() + "\n";
value += "DTORD: " + drow["DTORD"].ToString() + "\n";
value += "ORAORD: " + drow["ORAORD"].ToString() + "\n";
value += "MALFUNZIONE: " + drow["MALFUNZIONE"].ToString() + "\n";
value += "COD_RIS: " + drow["COD_RIS"].ToString() + "\n";
value += "RISORSA: " + drow["RISORSA"].ToString() + "\n";
value += "TERMID: " + drow["TERMID"].ToString() + "\n";
value += "ESESIA: " + drow["ESESIA"].ToString() + "\n";
value += "STABSIA: " + drow["STABSIA"].ToString() + "\n";
value += "ABI: " + drow["ABI"].ToString() + "\n";
value += "TELEFONO: " + drow["TELEFONO"].ToString() + "\n";
value += "NOTE: " + drow["NOTE"].ToString() + "\n";
value += "COD_HOST: " + drow["COD_HOST"].ToString() + "\n";
value += "ACCESSORIO: " + drow["ACCESSORIO"].ToString() + "\n";
value += "DESC_HOST: " + drow["DESC_HOST"].ToString() + "\n";
value += "MOD_COLLEG: " + drow["MOD_COLLEG"].ToString() + "\n";
value += "FUNZ. AGG: " + drow["FUNZ. AGG:"].ToString() + "\n";
value += "REFERENTE: " + drow["REFERENTE"].ToString() + "\n";
value += "DT_SCADENZA: " + drow["DT_SCADENZA"].ToString() + "\n";
value += "LAKA: " + drow["LAKA"].ToString();
Msg = value;
// Save File to .txt
filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
using (FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg, Encoding.UTF8);
m_WriterParameter.Flush();
m_WriterParameter.Close();
}
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
Invio(smtpSettings, Msg, filename);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
Logger.Info("Pulizia directory allegati terminata.");
}
else
{
string[] stringSeparators = new string[] { "************************************************************************************************************" };
string[] attivita = contents.Split(stringSeparators, StringSplitOptions.None);
foreach (string att in attivita)
{
Console.WriteLine(att);
string Msg = att;
// Save File to .txt
string filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write);
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg);
m_WriterParameter.Flush();
m_WriterParameter.Close();
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
if (att.Contains("OGGETTO"))
{
Invio(smtpSettings, att, filename);
}
else { }
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
Logger.Info("Pulizia directory allegati terminata.");
}
}
else
{
}
}
}
}
}
}
}
After searching around on the web i found a solution, here microsoft msdn
Streamreader and maybe readalltext doesn't support accent letters with UTF-8 Encoding, so changing it in UTF-7, letters are showed correctly.
Thank you for all support!
when i run this code after 30 second give me error 'time out expire' . error comming exactly after fill dataset . by the way i add connection time out = 0 to my app config but still the problem is the same . so how i can set connection time out for this dataset
public void ExportInvoicesAccount()
{
var q = from h in hmsdb.TransHdrs
where h.Account.AccountsContracts.First().AccountsMain.ID == _mainaccid
&& h.PayMethod == "R"
&& h.CancelDate == null
&& h.TransDate >= _fromdate
&& h.TransDate <= _todate
group h by new
{
amID = h.Account.AccountsContracts.First().AccountsMain.ID,
amcode = h.Account.AccountsContracts.First().AccountsMain.Code,
amName = h.Account.AccountsContracts.First().AccountsMain.EngName,
acccode = h.AccountCode,
accid = h.AccountID,
accname = h.Account.EngName
} into qg
select new
{
amID = qg.Key.amID,
amCode = qg.Key.amcode,
amName = qg.Key.amName,
acccode = qg.Key.acccode,
accid = qg.Key.accid,
accname = qg.Key.accname
};
if (_facccode != "" && _taccccode == "")
{
q = q.Where(f => f.acccode == _facccode);
}
if (_facccode != "" && _taccccode != "")
{
q = q.Where(f => Convert.ToInt32(f.acccode) >= Convert.ToInt32(_facccode) && Convert.ToInt32(f.acccode) <= Convert.ToInt32(_taccccode) && f.acccode != "C" && f.acccode != "10281501مكرر ");
}
foreach (var x in q)
{
try
{
ClaimDS ds = new ClaimDS();
SP_EClaims_StatmentOfAccountGeneralTableAdapter adapt = new SP_EClaims_StatmentOfAccountGeneralTableAdapter();
ds.EnforceConstraints = false;
adapt.Fill(ds.SP_EClaims_StatmentOfAccountGeneral, x.amID, x.accid, 0, _fromdate, _todate, _inout,0,0,0, 0);
if (ds.SP_EClaims_StatmentOfAccountGeneral.Rows.Count != 0)
{
InvoicesByAcc rptinv = new InvoicesByAcc();
rptinv.SetDataSource(ds);
ExportOptions expop = new ExportOptions();
DiskFileDestinationOptions dfdo = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions pdfop = new PdfRtfWordFormatOptions();
FolderPath = _path + x.amCode + " - " + x.amName + "\\";
bool exists = System.IO.Directory.Exists(FolderPath);
if (!exists)
System.IO.Directory.CreateDirectory(FolderPath);
fpath = FolderPath;
rptinv.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptinv.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
DiskFileDestinationOptions objDiskOpt = new DiskFileDestinationOptions();
if (_inout == "O")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-OUT" + ".pdf";
}
else if (_inout == "I")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-IN" + ".pdf";
}
else
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-ALL" + ".pdf";
}
rptinv.ExportOptions.DestinationOptions = objDiskOpt;
rptinv.Export();
rptinv.Dispose();
rptinv.Close();
}
GC.Collect();
ds.Dispose();
ds.Clear();
}
catch (Exception ex)
{
string logpath = FolderPath + "E_Claim_ErrorLog.txt";
// This text is added only once to the file.
if (!File.Exists(logpath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logpath))
{
//sw.WriteLine(ex.Message + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - "+ "ConsID: " + x.consid + " - " + "MRN: " + x.mrn + " )");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(logpath))
{
sw.WriteLine(ex.Message + " SP_EClaims_StatmentOfAccountGeneral" + "ExportInvoicesAccount" + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - " + "ConsID: " + "0" + " - " + "MRN: " + "0" + " )");
}
//MessageBox.Show(ex.Message + "AccountMainID: " + x.amID + "-"+ "AccountID: " + x.accid + "ConsID: " + x.consid + "MRN: " + x.mrn );
}
}
}
I'm building an Edit/Update system in my program using Linq in C# WPF.
My problem is that my code does submit to the LinqToSQLDatacontex but doesn't parse it through to the actual Database.
The result of that is that the datarow is updated in Runtime but in fact isn't updated in the actual Database.
this is the code I use for Updating my rows.
private void dgUsers_MouseUp(object sender, MouseButtonEventArgs e)
{
try
{
item = dgUsers.SelectedItem;
this.name = (dgUsers.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
var query =
from t in db.tbl_Users
where t.Name == name
select t;
foreach (var q in query)
{
tbMoreName.Text = q.Name;
tbMoreRights.Text = q.Rights;
tbMoreTag.Text = q.Operatortag;
checkMoreActive.IsChecked = q.Active;
tbMoreCardCode.Text = q.CardCode;
}
var table =
from q in db.tbl_UserProfiles
where q.Userprofile == tbMoreRights.Text
select q;
}
catch (Exception exc)
{
MessageBox.Show("NOPE");
}
}
private void btnSaveUser_Click(object sender, RoutedEventArgs e)
{
switch (saveType)
{
case "Edit":
#region save Edit User
var edit =
(from t in db.tbl_Users
where t.Name == name
select t).First();
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString());
edit.Id = edit.Id;
edit.Name = tbName.Text;
edit.Operatortag = tbOperatortag.Text;
edit.Rights = cbRights.Text;
edit.Active = checkActive.IsChecked.Value;
edit.CardCode = tbCardcode.Text;
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString() + " " + edit.CardCode.ToString());
db.SubmitChanges();
#endregion
saveType = "";
break;
}
var refresh =
(from q in db.tbl_Users
select new { Name = q.Name, Rights = q.Rights, Operatortag = q.Operatortag, Active = q.Active, Cardcode = q.CardCode }).ToList();
dgUsers.ItemsSource = null;
dgUsers.ItemsSource = refresh;
MessageBox.Show(refresh[0].ToString() + " " + refresh[1].ToString() + " " + refresh[2].ToString() + " " + refresh[3].ToString() + " " + refresh[4].ToString());
}
I hope that one of you guys can help me.
Thanks in advance!!!
I have to send mail through SMTP server. I can able to send it with single values. But, I want to send List<> values as message body in table format or some other structure. I include my code following :
MailMessage mailObj = new MailMessage("abc#gmail.com", "xyz#gmail.com", "Reg : send mail",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com", ***);
SMTPServer.Host = "smtp.gmail.com";
SMTPServer.EnableSsl = true;
SMTPServer.Timeout = 200000;
SMTPServer.Credentials = new System.Net.NetworkCredential("asd#gmail.com", "******");
SMTPServer.Send(mailObj);
I have my list of values as follows :
List<TimesheetValues> mailBody = new SampleDAO().GetDataForMail(dt1, satDate);
How can I include this List<> values with body and send?
I try with following :
List<TimesheetValues> Msg = new List<TimesheetValues>(); string strMsg = ""; int n=1;
foreach(var item in mailBody)
{
strMsg = strMsg + "<table><tr><td>" + n + "</td><td>" + item.Project_Name + "</td><td>" + item.Task_Name + "</td><td>" + item.Notes + "</td><td>" + item.Hrs_Worked + "</td></tr></table>";
n++;
}
strMsg = strMsg + "</br>";
MailMessage mailObj = new MailMessage("abc123#gmail.com", "xyz123#gmail.com", "Reg : Timesheet",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
mailObj.Body = "Emp Name : " + "Emp1" + Environment.NewLine + "Date From : " + Date2 + " Date To : " + Date6 + Environment.NewLine + strMsg;
Now I get all records but i have tr td tags with in records and not display as a table. How can i acheive this ?
can anyone help to overcome this..
Thanks in advance...
If you want to read the string into a list again, serialize is better.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(yourList);
mailObj.Body = json;
You can also deserialize in the other side:
List<string> g = JsonConvert.DeserializeObject<List<string>>(body);
I try with this following :
string strMsg = ""
strMsg = timsheetMail + " <table style=\"border-collapse:collapse; text-align:center;\" border=\"1\"><tr><td> Date </td><td> Working Hours </td><td> Task </td><td>Comments</td></tr>";
List<TimesheetValues> Msg = new List<TimesheetValues>(); int n=1;
foreach(var item in mailBody)
{
timesheetData = new TimesheetDetailModel();
timesheetData.Task_Id = matrix.Task_Id;
timesheetData.Hours = matrix.Hours;
//timesheetData.Date = matrix.Date.Date;
timesheetData.Date = matrix.Date.AddDays(1);
timesheetData.EmpId = Convert.ToInt32(Session["EmpId"].ToString());
timesheetData.Notes = matrix.Notes;
strMsg = strMsg+ " <tr><td> " + timesheetData.Date.ToString("dd/MM/yyyy") + "</td><td>" + timesheetData.Hours + "</td><td>" + task + "</td><td>" + timesheetData.Notes + "</td></tr>";
n++;
}
strMsg = strMsg + "</table>";
Its working good now..
I want format my .doc file, because when I retrive information and save in a .doc format using Open XML SDK, the document with all information is just in one line, and I need some information in other lines, just to format.
How can I do that?
This is my method that build an .doc
private static void BuildDocument(string fileName, string id, string conteudo)
{
Utilidade.QuebraToken tk2 = new Utilidade.QuebraToken();
////id = id.Remove(id.Length - 1);
string select3 = "SELECT San_Imovel.TextoAnuncio, San_Imovel.Filial_Id, San_Imovel.NomeBairro,San_Imovel.TipoDsc1,San_Imovel.Imovel_Id,San_Filial.NomeFantasia ,San_ContatoFilial.Contato " +
"FROM San_Imovel " +
"JOIN San_Filial ON San_Imovel.Filial_Id = San_Filial.Filial_id " +
"JOIN San_ContatoFilial ON San_Filial.Filial_Id = San_ContatoFilial.Filial_Id " +
"WHERE Imovel_Id IN (" + id + ") " +
" AND San_ContatoFilial.TipoContatoFilial_Id = 1";
using (WordprocessingDocument w = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
MainDocumentPart mp = w.AddMainDocumentPart();
DocumentFormat.OpenXml.Wordprocessing.Document d = new DocumentFormat.OpenXml.Wordprocessing.Document();
Body b = new Body();
DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
Run r = new Run();
Text t = new Text();
t.Text = conteudo;
r.Append(t);
p.Append(r);
b.Append(p);
HeaderPart hp = mp.AddNewPart<HeaderPart>();
string headerRelationshipID = mp.GetIdOfPart(hp);
SectionProperties sectPr = new SectionProperties();
HeaderReference headerReference = new HeaderReference();
headerReference.Id = headerRelationshipID;
headerReference.Type = HeaderFooterValues.Default;
sectPr.Append(headerReference);
b.Append(sectPr);
d.Append(b);
hp.Header = BuildHeader(hp, "Anuncio");
hp.Header.Save();
mp.Document = d;
mp.Document.Save();
w.Close();
}
}
And here, I call this method
public static object GerarDoc(string id, string email, string veiculo)
{
try
{
id = id.Remove(id.Length - 1);
string conteudo = string.Empty;
string select3 = "SELECT San_Imovel.TextoAnuncio, San_Imovel.Filial_Id, San_Imovel.NomeBairro,San_Imovel.TipoDsc1,San_Imovel.Imovel_Id,San_Filial.NomeFantasia ,San_ContatoFilial.Contato " +
"FROM San_Imovel " +
"INNER JOIN San_Filial ON San_Imovel.Filial_Id = San_Filial.Filial_id " +
"INNER JOIN San_ContatoFilial ON San_Filial.Filial_Id = San_ContatoFilial.Filial_Id " +
"WHERE Imovel_Id IN (" + id + ") " +
"AND San_ContatoFilial.TipoContatoFilial_Id = 1 ";
Utilidade.Conexao c3 = new Utilidade.Conexao();
SqlConnection con3 = new SqlConnection(c3.Con);
SqlCommand cmd3 = new SqlCommand(select3, con3);
con3.Open();
SqlDataReader r3 = cmd3.ExecuteReader();
while (r3.Read())
{
conteudo = conteudo + "" + (r3["Contato"]) + "";
conteudo = conteudo + "\n"+ (r3["NomeBairro"]);
conteudo = conteudo + "\n" + (r3["TipoDsc1"]) ;
conteudo = conteudo + "\n" + (r3["NomeFantasia"]) + " (" + (r3["Imovel_Id"]) + ") " + (r3["TextoAnuncio"]) + "\n\n";
}
con3.Close();
Random rnd = new Random (DateTime.Now.Millisecond);
string NomeArquivo = "Anuncio_" + Credenciada + "_" + Usuario + "_" + rnd.Next().ToString();
rng.Font.Name = "Arial";
rng.Text = conteudo;
BuildDocument(#"C:\inetpub\wwwroot\galileu.redenetimoveis.com\Anuncios\" + NomeArquivo + ".doc", id, rng.Text);
retorno = "1";
}
}
You can simply create a run with a break object in it and insert this run in your code everytime a page break is required, please see below for an example:
using (WordprocessingDocument package = WordprocessingDocument.Create("D:\\LineBreaks.docx", WordprocessingDocumentType.Document))
{
package.AddMainDocumentPart();
Run run1 = new Run();
Text text1 = new Text("The quick brown fox");
run1.Append(text1);
Run lineBreak = new Run(new Break());
Run run2 = new Run();
Text text2 = new Text("jumps over a lazy dog");
run2.Append(text2);
Paragraph paragraph = new Paragraph();
paragraph.Append(new OpenXmlElement[] { run1, lineBreak, run2 });
Body body = new Body();
body.Append(paragraph);
package.MainDocumentPart.Document = new Document(new Body(body));
}
Create your desired document manually and then reflect it Using Open XML productivity tool. so you can find what you need to do.