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); }
}
}
}
}
Related
How can I browse the email and download all attachments ?
public string Connect_Email ()
{
string Res = "";
try
{
mailclient = new TcpClient("pop.orange.fr", Convert.ToInt16("110"));
}
catch ( SocketException ExTrhown )
{
Res = "Unable to connect to server 1";
throw new Exception(ExTrhown.Message + "Unable to connect to server 1");
}
ns = mailclient.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
response = sr.ReadLine(); //Get opening POP3 banner
sw.WriteLine("USER " + "xxxxx#orange.fr"); //Send username
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 4) == "-ERR" )
{
Res = "Unable to log into server 2";
}
sw.WriteLine("PASS " + "xxxxx"); //Send password
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 3) == "-ER" )
{
Res = "Unable to log into server 3";
}
return Res;
}
public void Get_Attacht ()
{
string ClientName = "";
#region Chercher Attachment
sw.WriteLine("STAT"); //Send stat command to get number of messages
sw.Flush();
response = sr.ReadLine();
//find number of message
string[] nummess = response.Split(' ');
totmessages = Convert.ToInt16(nummess[1]);
//read emails
for ( int i = 1; i <= totmessages; i++ )
{
msg = null;
sw.WriteLine("top " + i + " 0"); //read header of each message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
//read attachment
attachment = null;
if ( Regex.Match(msg, "multipart/mixed").Success )
{
msg = null;
sw.WriteLine("retr " + i.ToString()); //Retrieve entire message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
int End = msg.IndexOf(".csv");
string LeFile = msg.Substring(End - 9, 9);
if ( Regex.Match(msg, LeFile + ".csv").Success )
{
data = msg.Split('\r');
startindex = 0;
index = 0;
lastindex = 0;
x = null;
ms = null;
fs = null;
while ( true )
{
attachment = null;
while ( !Regex.Match(data[index].Trim(), "filename").Success )
{
index++;
}
if ( index == data.Length - 1 ) break;
FileName_Email = data[index].Trim().Substring(42).Replace("\"", "");
//find start of attachment data
index++;
while ( data[index].Length != 1 )
{
index++;
}
if ( index == data.Length - 1 ) break;
startindex = index + 1;
//find end of data
index = startindex + 1;
while ( ( !Regex.Match(data[index].Trim(), "--0").Success ) && ( data[index].Length != 1 ) && ( index < data.Length - 1 ) )
{
index++;
}
if ( index == data.Length ) break;
lastindex = index - 2;
for ( int j = startindex; j <= lastindex; j++ )
{
attachment = attachment + data[j];
}
attachment = attachment + "\r\n";
if ( Regex.Match(FileName_Email.ToLower(), "csv").Success )
{
byte[] filebytes = Convert.FromBase64String(attachment);
FileStream LeFS = new FileStream(filePath + "\\testDEC.csv", FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
break;
}
}
}
}
}
sw.WriteLine("quit"); //quit
sw.Flush();
#endregion
}
It does not work, have you another simple idea ?
Try something like this
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("server");
pop3.UseBestLogin("user", "password");
foreach (string uid in pop3.GetAll())
{
IMail email = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine(email.Subject);
// save all attachments to disk
email.Attachments.ForEach(mime => mime.Save(mime.SafeFileName));
}
pop3.Close();
}
// here is a reference link you can use as well
Getting Email Attachments
If you're trying to read e-mail via POP3, I would recommend using the OpenPOP.NET library instead of rolling your own. It's pretty easy to use.
Thanks you all for your contribution. Finally I use POP3:
public string Connect_Email()
{
string Res = "";
try
{
Pop3Client email = new Pop3Client("login", "password", "server");
email.OpenInbox();
while (email.NextEmail())
{
if (email.IsMultipart)
{
IEnumerator enumerator = email.MultipartEnumerator;
while (enumerator.MoveNext())
{
Pop3Component multipart = (Pop3Component)
enumerator.Current;
if (multipart.IsBody)
{
//Console.WriteLine("Multipart body:" + multipart.Name);
}
else
{
//Console.WriteLine("Attachment name=" + multipart.Name); // ... etc
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
}
}
}
}
email.CloseConnection();
}
catch (Pop3LoginException)
{
Res = "Vous semblez avoir un problème de connexion!";
}
return Res;
}
It work well, but still I have to find and download the attachement my self.
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
This not work more. Use Modern Authentication with Microsoft.Graph after create a cliente secret into AZURE and registered tha application them.
I am trying to download mp3 from http://www.audiodump.com/. The site has a lot of redirections. However I managed getting a part of it working.
This is my method for getting all informations such as DL links, titles, mp3 durations.
private void _InetGetHTMLSearch(string sArtist)
{
if(_AudioDumpQuery == string.Empty)
{
//return string.Empty;
}
string[] sStringArray;
string sResearchURL = "http://www.audiodump.biz/music.html?" + _AudioDumpQuery + sArtist.Replace(" ", "+");
string aRet;
HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(sResearchURL);
webReq.Referer = "http://www.audiodump.com/";
try
{
webReq.CookieContainer = new CookieContainer();
webReq.Method = "GET";
using (WebResponse response = webReq.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
aRet = reader.ReadToEnd();
//Console.WriteLine(aRet);
string[] aTable = _StringBetween(aRet, "<BR><table", "table><BR>", RegexOptions.Singleline);
if (aTable != null)
{
string[] aInfos = _StringBetween(aTable[0], ". <a href=\"", "<a href=\"");
if (aInfos != null)
{
for(int i = 0; i < aInfos.Length; i++)
{
aInfos[i] = aInfos[i].Replace("\">", "*");
aInfos[i] = aInfos[i].Replace("</a> (", "*");
aInfos[i] = aInfos[i].Remove(aInfos[i].Length - 2);
sStringArray = aInfos[i].Split('*');
aLinks.Add(sStringArray[0]);
aTitles.Add(sStringArray[1]);
sStringArray[2] = sStringArray[2].Replace("`", "'");
sStringArray[2] = sStringArray[2].Replace("dont", "don't");
sStringArray[2] = sStringArray[2].Replace("lets", "let's");
sStringArray[2] = sStringArray[2].Replace("cant", "can't");
sStringArray[2] = sStringArray[2].Replace("shes", "she's");
sStringArray[2] = sStringArray[2].Replace("aint", "ain't");
sStringArray[2] = sStringArray[2].Replace("didnt", "didn't");
sStringArray[2] = sStringArray[2].Replace("im", "i'm");
sStringArray[2] = sStringArray[2].Replace("youre", "you're");
sStringArray[2] = sStringArray[2].Replace("ive", "i've");
sStringArray[2] = sStringArray[2].Replace("youll", "you'll");
sStringArray[2] = sStringArray[2].Replace("'", "'");
sStringArray[2] = sStringArray[2].Replace("'", "simplequotes");
sStringArray[2] = sStringArray[2].Replace("vk.com", "");
sStringArray[2] = _StringReplaceCyrillicChars(sStringArray[2]);
sStringArray[2] = Regex.Replace(sStringArray[2], #"<[^>]+>| ", "").Trim();
sStringArray[2] = Regex.Replace(sStringArray[2], #"\s{2,}", " ");
sStringArray[2] = sStringArray[2].TrimStart('\'');
sStringArray[2] = sStringArray[2].TrimStart('-');
sStringArray[2] = sStringArray[2].TrimEnd('-');
sStringArray[2] = sStringArray[2].Replace("- -", "-");
sStringArray[2] = sStringArray[2].Replace("http", "");
sStringArray[2] = sStringArray[2].Replace("www", "");
sStringArray[2] = sStringArray[2].Replace("mp3", "");
sStringArray[2] = sStringArray[2].Replace("simplequotes", "'");
aDurations.Add(sStringArray[2]);
}
}
else
{
//Console.WriteLine("Debug");
}
}
else
{
//Console.WriteLine("Debug 2");
}
//return aRet;
}
}
}
catch (Exception ex)
{
//return null;
////Console.WriteLine("Debug message: " + ex.Message);
}
}
I simply had to add referrer to prevent the search from redirection webReq.Referer = "http://www.audiodump.com/";
However when I want to download the mp3 I can't get it working. The urls are correct and checked with the ones I get when I download them manually rather than programmatically.
This is my mp3 download part:
private void _DoDownload(string dArtist, ref string dPath)
{
if (!Contain && skip <= 3 && !Downloading)
{
Random rnd = new Random();
int Link = rnd.Next(5);
_InetGetHTMLSearch(dArtist);
Console.WriteLine("--------------------------------> " + aLinks[0]);
string path = mp3Path + "\\" + dArtist + ".mp3";
if (DownloadOne(aLinks[Link], path, false))
{
hTimmer.Start();
Downloading = true;
}
}
else if (Downloading)
{
int actualBytes = strm.Read(barr, 0, arrSize);
fs.Write(barr, 0, actualBytes);
bytesCounter += actualBytes;
double percent = 0d;
if (fileLength > 0)
percent =
100.0d * bytesCounter /
(preloadedLength + fileLength);
label1.Text = Math.Round(percent).ToString() + "%";
if (Math.Round(percent) >= 100)
{
string path = mp3Path + "\\" + dArtist + ".mp3";
label1.Text = "";
dPath = path;
aLinks.Clear();
hTimmer.Stop();
hTimmer.Reset();
fs.Flush();
fs.Close();
lastArtistName = "N/A";
Downloading = false;
}
if (Math.Round(percent) <= 1)
{
if (hTimmer.ElapsedMilliseconds >= 3000)
{
string path = mp3Path + "\\" + dArtist + ".mp3";
hTimmer.Stop();
hTimmer.Reset();
fs.Flush();
fs.Close();
File.Delete(path);
Contain = false;
skip += 1;
Downloading = false;
}
}
}
}
private static string ConvertUrlToFileName(string url)
{
string[] terms = url.Split(
new string[] { ":", "//" },
StringSplitOptions.RemoveEmptyEntries);
string fname = terms[terms.Length - 1];
fname = fname.Replace('/', '.');
return fname;
} //ConvertUrlToFileName
private static long GetExistingFileLength(string filename)
{
if (!File.Exists(filename)) return 0;
FileInfo info = new FileInfo(filename);
return info.Length;
} //GetExistingFileLength
private static bool DownloadOne(string url, string existingFilename, bool quiet)
{
ServicePointManager.DefaultConnectionLimit = 20;
HttpWebRequest webRequest;
HttpWebResponse webResponse;
IWebProxy proxy = null; //SA???
//fmt = CreateFormat(
//"{0}: {1:#} of {2:#} ({3:g3}%)", "#");
try
{
fname = existingFilename;
if (fname == null)
fname = ConvertUrlToFileName(url);
if (File.Exists(existingFilename))
{
File.Delete(existingFilename);
}
webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A";
webRequest.Referer = "http://www.audiodump.com/";
preloadedLength = GetExistingFileLength(fname);
if (preloadedLength > 0)
webRequest.AddRange((int)preloadedLength);
webRequest.Proxy = proxy; //SA??? or DefineProxy
webResponse = (HttpWebResponse)webRequest.GetResponse();
fs = new FileStream(fname, FileMode.Append, FileAccess.Write);
fileLength = webResponse.ContentLength;
strm = webResponse.GetResponseStream();
if (strm != null)
{
bytesCounter = preloadedLength;
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
//Console.WriteLine(
//"{0}: {1} '{2}'",
// url, e.GetType().FullName,
//e.Message);
return false;
}
//exception
} //DownloadOne
The method _DoDownload() is executed from a timer which runs every 250 milliseconds. This way works perfectly on other sites. However audiodump is giving me hard time with these redirections.
I am not a genius with httprequest. I managed solving the search issue however the download part is freaking me out. Any advice on how to manage the download issue?
You just need to set referrer to the page from where you got that download link. For example you grabbed links to files from page "http://www.audiodump.biz/music.html?q=whatever", then when downloading file set that as Referrer, not just "http://www.audiodump.biz".
What I'm trying to achieve
In my c# application I would like to generate a report (word document) from data in my application, I figured that the best way to do this would be to perform something like a mail merge using the data source from my application.
What I've tried
I tried following this
Mail Merge into word
however this uses GemBox which you need to pay for
I have tried using Microsoft.Office.Interop.Word however I fell
short when I didn't know how to reference the saved template document:
Dictionary<string, string> MailMerge = new Dictionary<string, string>()
{
{ "ID", "123" },
{ "Name", "Test" },
{ "Address1", "Test" },
{ "Address2", "Test" },
{ "Address3", "Test" },
{ "Address4", "Test" },
{ "PostCode", "Test" },
{ "Year End", "Test" },
{ "SicCode", "123" },
};
Document doc = new Document();
doc.MailMerge.Execute(MailMerge);
Summary
I'm looking for some guidance as to what to research further as I believe there must be a 'standard' way of doing this.
Can't believe third party software charge thousands for interface functions with Word. I have perfectly solved this mail merge thing in my project -- no third party, no particular demands on IIS, just use OpenXML.
So, add these 4 functions to your project:
public static void dotx2docx(string sourceFile, string targetFile)
{
MemoryStream documentStream;
using (Stream tplStream = File.OpenRead(sourceFile))
{
documentStream = new MemoryStream((int)tplStream.Length);
CopyStream(tplStream, documentStream);
documentStream.Position = 0L;
}
using (WordprocessingDocument template = WordprocessingDocument.Open(documentStream, true))
{
template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
MainDocumentPart mainPart = template.MainDocumentPart;
mainPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(targetFile, UriKind.Absolute));
mainPart.Document.Save();
}
File.WriteAllBytes(targetFile, documentStream.ToArray());
}
public static void CopyStream(Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
public static void Mailmerge(string templatePath, string DestinatePath, DataRow dr, DataColumnCollection columns)
{
try
{
dotx2docx(templatePath, DestinatePath);
}
catch //incase the server does not support MS Office Word 2003 / 2007 / 2010
{
File.Copy(templatePath, DestinatePath, true);
}
using (WordprocessingDocument doc = WordprocessingDocument.Open(DestinatePath, true))
{
var allParas = doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>();
Text PreItem = null;
string PreItemConstant = null;
bool FindSingleAnglebrackets = false;
bool breakFlag = false;
List<Text> breakedFiled = new List<Text>();
foreach (Text item in allParas)
{
foreach (DataColumn cl in columns)
{
//<Today>
if (item.Text.Contains("«" + cl.ColumnName + "»") || item.Text.Contains("<" + cl.ColumnName + ">"))
{
item.Text = item.Text.Replace("<" + cl.ColumnName + ">", dr[cl.ColumnName].ToString())
.Replace("«" + cl.ColumnName + "»", dr[cl.ColumnName].ToString());
FindSingleAnglebrackets = false;
breakFlag = false;
breakedFiled.Clear();
}
else if //<Today
(item.Text != null
&& (
(item.Text.Contains("<") && !item.Text.Contains(">"))
|| (item.Text.Contains("«") && !item.Text.Contains("»"))
)
&& (item.Text.Contains(cl.ColumnName))
)
{
FindSingleAnglebrackets = true;
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"\<" + cl.ColumnName + #"(?!\w)", dr[cl.ColumnName].ToString());
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"\«" + cl.ColumnName + #"(?!\w)", dr[cl.ColumnName].ToString());
}
else if //Today> or Today
(
PreItemConstant != null
&& (
(PreItemConstant.Contains("<") && !PreItemConstant.Contains(">"))
|| (PreItemConstant.Contains("«") && !PreItemConstant.Contains("»"))
)
&& (item.Text.Contains(cl.ColumnName))
)
{
if (item.Text.Contains(">") || item.Text.Contains("»"))
{
FindSingleAnglebrackets = false;
breakFlag = false;
breakedFiled.Clear();
}
else
{
FindSingleAnglebrackets = true;
}
if (PreItemConstant == "<" || PreItemConstant == "«")
{
PreItem.Text = "";
}
else
{
PreItem.Text = global::System.Text.RegularExpressions.Regex.Replace(PreItemConstant, #"\<" + cl.ColumnName + #"(?!\w)", dr[cl.ColumnName].ToString());
PreItem.Text = global::System.Text.RegularExpressions.Regex.Replace(PreItemConstant, #"\«" + cl.ColumnName + #"(?!\w)", dr[cl.ColumnName].ToString());
}
if (PreItemConstant.Contains("<") || PreItemConstant.Contains("«")) // pre item is like '[blank]«'
{
PreItem.Text = PreItem.Text.Replace("<", "");
PreItem.Text = PreItem.Text.Replace("«", "");
}
if (item.Text.Contains(cl.ColumnName + ">") || item.Text.Contains(cl.ColumnName + "»"))
{
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"(?<!\w)" + cl.ColumnName + #"\>", dr[cl.ColumnName].ToString());
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"(?<!\w)" + cl.ColumnName + #"\»", dr[cl.ColumnName].ToString());
}
else
{
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"(?<!\w)" + cl.ColumnName + #"(?!\w)", dr[cl.ColumnName].ToString());
}
}
else if (FindSingleAnglebrackets && (item.Text.Contains("»") || item.Text.Contains(">")))
{
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"(?<!\w)" + cl.ColumnName + #"\>", dr[cl.ColumnName].ToString());
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"(?<!\w)" + cl.ColumnName + #"\»", dr[cl.ColumnName].ToString());
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"^\s*\>", "");
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"^\s*\»", "");
FindSingleAnglebrackets = false;
breakFlag = false;
breakedFiled.Clear();
}
else if (item.Text.Contains("<") || item.Text.Contains("«")) // no ColumnName
{
}
} //end of each columns
PreItem = item;
PreItemConstant = item.Text;
if (breakFlag
|| (item.Text.Contains("<") && !item.Text.Contains(">"))
|| (item.Text.Contains("«") && !item.Text.Contains("»"))
)
{
breakFlag = true;
breakedFiled.Add(item);
string combinedfiled = "";
foreach (Text t in breakedFiled)
{
combinedfiled += t.Text;
}
foreach (DataColumn cl in columns)
{
//<Today>
if (combinedfiled.Contains("«" + cl.ColumnName + "»") || combinedfiled.Contains("<" + cl.ColumnName + ">"))
{
//for the first part, remove the last '<' and tailing content
breakedFiled[0].Text = global::System.Text.RegularExpressions.Regex.Replace(breakedFiled[0].Text, #"<\w*$", "");
breakedFiled[0].Text = global::System.Text.RegularExpressions.Regex.Replace(breakedFiled[0].Text, #"<\w*$", "");
//remove middle parts
foreach (Text t in breakedFiled)
{
if (!t.Text.Contains("<") && !t.Text.Contains("«") && !t.Text.Contains(">") && !t.Text.Contains("»"))
{
t.Text = "";
}
}
//for the last part(as current item), remove leading content till the first '>'
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"^\s*\>", dr[cl.ColumnName].ToString());
item.Text = global::System.Text.RegularExpressions.Regex.Replace(item.Text, #"^\s*\»", dr[cl.ColumnName].ToString());
FindSingleAnglebrackets = false;
breakFlag = false;
breakedFiled.Clear();
break;
}
}
}
}//end of each item
#region go through footer
MainDocumentPart mainPart = doc.MainDocumentPart;
foreach (FooterPart footerPart in mainPart.FooterParts)
{
Footer footer = footerPart.Footer;
var allFooterParas = footer.Descendants<Text>();
foreach (Text item in allFooterParas)
{
foreach (DataColumn cl in columns)
{
if (item.Text.Contains("«" + cl.ColumnName + "»") || item.Text.Contains("<" + cl.ColumnName + ">"))
{
item.Text = (string.IsNullOrEmpty(dr[cl.ColumnName].ToString()) ? " " : dr[cl.ColumnName].ToString());
FindSingleAnglebrackets = false;
}
else if (PreItem != null && (PreItem.Text == "<" || PreItem.Text == "«") && (item.Text.Trim() == cl.ColumnName))
{
FindSingleAnglebrackets = true;
PreItem.Text = "";
item.Text = (string.IsNullOrEmpty(dr[cl.ColumnName].ToString()) ? " " : dr[cl.ColumnName].ToString());
}
else if (FindSingleAnglebrackets && (item.Text == "»" || item.Text == ">"))
{
item.Text = "";
FindSingleAnglebrackets = false;
}
}
PreItem = item;
}
}
#endregion
#region replace \v to new Break()
var body = doc.MainDocumentPart.Document.Body;
var paras = body.Elements<Paragraph>();
foreach (var para in paras)
{
foreach (var run in para.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
if (text.Text.Contains("MS_Doc_New_Line"))
{
string[] ss = text.Text.Split(new string[] { "MS_Doc_New_Line" }, StringSplitOptions.None);
text.Text = text.Text = "";
int n = 0;
foreach (string s in ss)
{
n++;
run.AppendChild(new Text(s));
if (n != ss.Length)
{
run.AppendChild(new Break());
}
}
}
}
}
}
#endregion
doc.MainDocumentPart.Document.Save();
}
}
public static void MergeDocuments(params string[] filepaths)
{
//filepaths = new[] { "D:\\one.docx", "D:\\two.docx", "D:\\three.docx", "D:\\four.docx", "D:\\five.docx" };
if (filepaths != null && filepaths.Length > 1)
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(#filepaths[0], true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
for (int i = 1; i < filepaths.Length; i++)
{
string altChunkId = "AltChunkId" + i;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = File.Open(#filepaths[i], FileMode.Open))
{
chunk.FeedData(fileStream);
}
DocumentFormat.OpenXml.Wordprocessing.AltChunk altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
altChunk.Id = altChunkId;
//new page, if you like it...
mainPart.Document.Body.AppendChild(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
//next document
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
}
mainPart.Document.Save();
myDoc.Close();
}
}
And use them like this:
DataTable dt = new DataTable();
dt.Columns.Add("Date");
dt.Columns.Add("Today");
dt.Columns.Add("Addr1");
dt.Columns.Add("Addr2");
dt.Columns.Add("PreferContact");
dt.Columns.Add("TenantName");
//......
DataRow nr = dt.NewRow();
nr["Date"] = DateTime.Now.ToString("dd/MM/yyyy");
nr["Today"] = DateTime.Now.ToString("dd/MM/yyyy");
//......
dt.Rows.Add(nr);
string sourceFile = "c:\my_template.docx"; //this is where you store your template
string filePath = "c:\final.docx"; //this is where your result file locate
Mailmerge(sourceFile, filePath, nr, dt.Columns);
Your template(c:\my_template.docx) will be just like normal .docx file, and you need to specify your fields in it:
<field>
So, your template(c:\my_template.docx) should be like:
<Today>
<DebtorName>
<DebtorADDR>
<DebtorEmail>
Dear <Dear>,
Congratulations on yourr property <PlanNo> <BuildAddress>. Your unit number is <LotNo> ...............
In addition, if some of your fields contain line breaks, use this:
nr["Address"] = my_address_text_contains_line_breaks.Replace(Environment.NewLine, "MS_Doc_New_Line");
This is quite simple by using Microsoft.Office.Interop.Word. Here is a simple step by step tutorial on how to do this.
The code to replace a mergefield with a string is like this:
public static void TextToWord(string pWordDoc, string pMergeField, string pValue)
{
Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();
oWord.Visible = true;
Object oTemplatePath = pWordDoc;
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Word.Field myMergeField in oWordDoc.Fields)
{
Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
fieldName = fieldName.Trim();
if (fieldName == pMergeField)
{
myMergeField.Select();
oWord.Selection.TypeText(pValue);
}
}
}
}
originally posted here and here
In case you wish to use a dictionary to replace many fields at once use the code below:
public static void TextToWord(string pWordDoc, Dictionary<string, string> pDictionaryMerge)
{
Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();
oWord.Visible = true;
Object oTemplatePath = pWordDoc;
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Microsoft.Office.Interop.Word.Field myMergeField in oWordDoc.Fields)
{
Microsoft.Office.Interop.Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
fieldName = fieldName.Trim();
foreach (var item in pDictionaryMerge)
{
if (fieldName == item.Key)
{
myMergeField.Select();
oWord.Selection.TypeText(item.Value);
}
}
}
}
}
I am also using the same thing but I have more complexity. I have to check the if condition also. In word template file
{ IF «Installment» = Monthly "then the table will appear" "nothing to show" }
when I use the above code shared in the answer. and for if condition in c# I have written
Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text.Trim();
if (fieldText.ToUpper().StartsWith("IF"))
{
myMergeField.UpdateSource();}
so the output is like
{ IF Monthly = Monthly "then table will appear" "nothing to show" }
but the desired output is only "then the table will appear".
I am working with a project where I am generating PDF Files from PSR Files. The PDF Files works fine if its a single page but if It has more than two PSR Files and I generate two files it does not open on iPad and works fine on Desktop.
The Third library tool I am using here is 'dbatuotrack' and I am using C#.
Can anyone please guide me how to resolve this problem?
Thanks,
S.
foreach (var pdfform in pdfPagesID)
{
//dbAutoTrack.PDFWriter.Document objDoc = null;
//dbAutoTrack.PDFWriter.Page objPage = null;
objDoc = new dbAutoTrack.PDFWriter.Document();
pdfPagesID.Clear();
pdfPagesID = GetSpecPageID(pdfform);
if (pdfPagesID.Count > 1)
{
foreach (var pdfPage in pdfPagesID)
{
dbAutoTrack.PDFWriter.Page objPage2 = null;
var lastItem = pdfPagesID.Last();
prefixPageID = prefixSpecPageID(pdfPage);
suffixPageIDPSR = prefixPageID + ".psr";
if (File.Exists(PSRPath + suffixPageIDPSR))
{
objDs = new CDatasheet(this.PSRPath + suffixPageIDPSR, false);
objDs.pdfDbHelper = pdfhelper;
//Giving the specformId as SpecFornName
pdfFormName = "Form" + pdfform + ".pdf";
if (!(pdfPage == pdfPagesID.First()))
{
objPage2 = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage2);
}
else
{
objPage = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage);
}
if (objPage != null)
{
if (pdfWithNotePage == true && pdfPage.Equals(lastItem))
{
objNotePage = objDs.GetNotePage();
objDoc.Pages.Add(objPage);
objDoc.Pages.Add(objNotePage);
}
else
{
//objDoc.Pages.Add(objPage);
//objDoc.Pages.Add(objPage2);
}
fsOutput = new FileStream(TemplatePath + pdfFormName, FileMode.Create, FileAccess.Write);
objDoc.Generate(fsOutput);
}
if (fsOutput != null)
{
fsOutput.Close();
fsOutput.Dispose();
fsOutput = null;
}
}
}
objDoc = null;
objPage = null;
}
This how I tweaked the code to make it work. Thanks for the suggestion DJ KRAZE
foreach (var pdfform in pdfPagesID)
{
//dbAutoTrack.PDFWriter.Document objDoc = null;
//dbAutoTrack.PDFWriter.Page objPage = null;
objDoc = new dbAutoTrack.PDFWriter.Document();
pdfPagesID.Clear();
pdfPagesID = GetSpecPageID(pdfform);
if (pdfPagesID.Count > 1)
{
foreach (var pdfPage in pdfPagesID)
{
dbAutoTrack.PDFWriter.Page objPage2 = null;
var lastItem = pdfPagesID.Last();
prefixPageID = prefixSpecPageID(pdfPage);
suffixPageIDPSR = prefixPageID + ".psr";
if (File.Exists(PSRPath + suffixPageIDPSR))
{
objDs = new CDatasheet(this.PSRPath + suffixPageIDPSR, false);
objDs.pdfDbHelper = pdfhelper;
//Giving the specformId as SpecFornName
pdfFormName = "Form" + pdfform + ".pdf";
if (!(pdfPage == pdfPagesID.First()))
{
objPage2 = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage2);
}
else
{
objPage = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage);
}
if (objPage != null)
{
if (pdfWithNotePage == true && pdfPage.Equals(lastItem))
{
objNotePage = objDs.GetNotePage();
objDoc.Pages.Add(objPage);
objDoc.Pages.Add(objNotePage);
}
else
{
//objDoc.Pages.Add(objPage);
//objDoc.Pages.Add(objPage2);
}
}
}
}
fsOutput = new FileStream(TemplatePath + pdfFormName, FileMode.Create, FileAccess.Write);
objDoc.Generate(fsOutput);
//This region was the problem, disposing the output everytime.
//Needed it to be included after completion of iteration
if (fsOutput != null)
{
fsOutput.Close();
fsOutput.Dispose();
fsOutput = null;
}
}
public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
DataTable GetListID = new DataTable();
try
{
SqlParameter[] arParams = new SqlParameter[4];
arParams[0] = new SqlParameter("#Date", typeof(DateTime));
arParams[0].Value = objFeedRetPL.requestdate;
}
catch (Exception ex)
{
string dir = #"C:\Error.txt"; // folder location
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
File.AppendAllText(Server.MapPath("~/Error.txt"), "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
string New = Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine;
File.AppendAllText(Server.MapPath("~/Error.txt"), New);
}
}
}
Here, I want to save an Exception in "C:\" ..I am trying In DAL... How to save the Exception In
C drive Error.txt
Since you want to save the exception to C:\Error.txt, you don't need Directory.Exists, Directory.CreateDirectory, or Server.MapPath("~/Error.txt"). You can simply use StreamWriter like this:
string filePath = #"C:\Error.txt";
Exception ex = ...
using( StreamWriter writer = new StreamWriter( filePath, true ) )
{
writer.WriteLine( "-----------------------------------------------------------------------------" );
writer.WriteLine( "Date : " + DateTime.Now.ToString() );
writer.WriteLine();
while( ex != null )
{
writer.WriteLine( ex.GetType().FullName );
writer.WriteLine( "Message : " + ex.Message );
writer.WriteLine( "StackTrace : " + ex.StackTrace );
ex = ex.InnerException;
}
}
The above code will create C:\Error.txt if it doesn't exist, or append C:\Error.txt if it already exists.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ErrorLoggingSample
{
class Program
{
static void Main(string[] args)
{
try
{
string str = string.Empty;
if (string.IsNullOrEmpty(str))
{
throw new Exception("Wrong Data");
}
}
catch (Exception ex)
{
ErrorLogging(ex);
ReadError();
}
}
public static void ErrorLogging(Exception ex)
{
string strPath = #"D:\Rekha\Log.txt";
if (!File.Exists(strPath))
{
File.Create(strPath).Dispose();
}
using (StreamWriter sw = File.AppendText(strPath))
{
sw.WriteLine("=============Error Logging ===========");
sw.WriteLine("===========Start============= " + DateTime.Now);
sw.WriteLine("Error Message: " + ex.Message);
sw.WriteLine("Stack Trace: " + ex.StackTrace);
sw.WriteLine("===========End============= " + DateTime.Now);
}
}
public static void ReadError()
{
string strPath = #"D:\Rekha\Log.txt";
using (StreamReader sr = new StreamReader(strPath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}
I use that one
catch (Exception e)
{
new MessageWriteToFile(e).WriteToFile();
}
public class MessageWriteToFile
{
private const string Directory = "C:\\AppLogs";
public string Message { get; set; }
public Exception Exception { get; set; }
public string DefaultPath
{
get
{
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var folder = $"{Directory}\\{appName}";
if (!System.IO.Directory.Exists(folder))
{
System.IO.Directory.CreateDirectory(folder);
}
var fileName = $"{DateTime.Today:yyyy-MM-dd}.txt";
return $"{Directory}\\{appName}\\{fileName}";
}
}
public MessageWriteToFile(string message)
{
Message = message;
}
public MessageWriteToFile(Exception ex)
{
Exception = ex;
}
public bool WriteToFile(string path = "")
{
if (string.IsNullOrEmpty(path))
{
path = DefaultPath;
}
try
{
using (var writer = new StreamWriter(path, true))
{
writer.WriteLine("-----------------------------------------------------------------------------");
writer.WriteLine("Date : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
writer.WriteLine();
if (Exception != null)
{
writer.WriteLine(Exception.GetType().FullName);
writer.WriteLine("Source : " + Exception.Source);
writer.WriteLine("Message : " + Exception.Message);
writer.WriteLine("StackTrace : " + Exception.StackTrace);
writer.WriteLine("InnerException : " + Exception.InnerException?.Message);
}
if (!string.IsNullOrEmpty(Message))
{
writer.WriteLine(Message);
}
writer.Close();
}
}
catch (Exception)
{
return false;
}
return true;
}
}
Try This
try
{
int i = int.Parse("Prashant");
}
catch (Exception ex)
{
this.LogError(ex);
}
private void LogError(Exception ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(message);
writer.Close();
}
}
string[] path1 = Directory.GetFiles(#"E:\storage", "*.txt");//it get the all textfiles from the folder
for (var i = 0; i < path1.Length; i++)
{
var file = Directory.GetDirectories(networkPath);
var path = file;
string temp_FilePath = "E:\\temp.txt";
string temp_FilePath1 = #"E:\ExceptionFiles\Cs_regular\\Cs_regular.txt";
string temp_FilePath2 = #"E:\ExceptionFiles\CC_eBilling\\CC_eBilling.txt";
string folder = #"E:\ExceptionFiles\Cs_regular";
string folder1 = #"E:\ExceptionFiles\CC_eBilling";
string[] lines;
var list = new List<string>();
var list1 = new List<string>();
var list2 = new List<string>();
var error = false;
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream1 = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream2 = new FileStream(path, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy /MM/dd HH:mm");
var timenow1 = "2020/10/31 10:11";
if (res == timenow1)
{
string linesRemoved = "ERROR";
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list1.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if (line.Contains("Exception1") && error == false)
{
list1.Add(line);
error = true;
}
}
}
}
using (var streamReader2 = new StreamReader(fileStream2, Encoding.UTF8))
{
string line;
while ((line = streamReader2.ReadLine()) != null)
{
string linesRemoved = "ERROR";
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
var timenow1 = "2020/10/29 12:38";
if (res == timenow1)
{
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list2.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if ((line.Contains("Exception2") && line.Contains("Exception:")) && error == false)
{
list2.Add(line);
error = true;
}
}
}
}
if ((System.IO.File.Exists(temp_FilePath1) || System.IO.File.Exists(temp_FilePath2)))
{
int fileCount = Directory.GetFiles(folder).Length;
int fileCount1 = Directory.GetFiles(folder1).Length;
fileCount++;
fileCount1++;
temp_FilePath1 = temp_FilePath1 + "(" + fileCount.ToString() + ").txt";
temp_FilePath2 = temp_FilePath2 + "(" + fileCount1.ToString() + ").txt";
}
{
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
System.IO.File.WriteAllLines(temp_FilePath, list);
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
}
}
catch (Exception ex)
{
}
return null;