will appreciate any Help on this one.
I am trying to replace text in an email template using Mailkit. The issue is that in Mailkit there is at least a text part and and Html part.
I can get then set the text part using code such as:
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
I can get the htmlbody using
var htmlPart = message.htmlBody
but once I modify it I do not know how to set the htmlpart to the message's htmlBody.
My code so far:
FileStream sr = new FileStream(fileLocation + "\\" + fileName, FileMode.Open, FileAccess.Read);
message = MimeMessage.Load(sr);
sr.Close();
//Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
//Get the HtmlBody
var htmlPart = message.HtmlBody;
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart = regexText.Replace(htmlPart, regexReplacement);
}
}
try
{
message.WriteTo(fileLocation + "\\output\\" + fileName);
}
catch (Exception Ex)
{
result = Ex.Message;
return BadRequest(result);
}```
Something like this will probably work:
// Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsPlain);
var htmlPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsHtml);
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart.Text = regexText.Replace(htmlPart.Text, regexReplacement);
}
}
Related
Hello i'm getting some strings from a Web API
Like This
mail-lf0-f100.google.com,209.85.215.100
mail-vk0-f100.google.com,209.85.213.100
mail-ua1-f100.google.com,209.85.222.100
mail-ed1-f100.google.com,209.85.208.100
mail-lf1-f100.google.com,209.85.167.100
mail-ej1-f100.google.com,209.85.218.100
mail-pj1-f100.google.com,209.85.216.100
mail-wm1-f100.google.com,209.85.128.100
mail-io1-f100.google.com,209.85.166.100
mail-wr1-f100.google.com,209.85.221.100
mail-vs1-f100.google.com,209.85.217.100
mail-ot1-f100.google.com,209.85.210.100
mail-qv1-f100.google.com,209.85.219.100
mail-yw1-f100.google.com,209.85.161.100
it give me some string records and i want to do this Operations.
I want to make it line by line like it show in original
I want to remove everything after comma in eachline
I want to set a prefix before each line for the example:
Example: Google.com to>> This is Dns: Google.com
and This is my code . What should i edit and what should i add?
string filePath = "D:\\google.txt";
WebClient wc = new WebClient();
string html = wc.DownloadString("https://api.hackertarget.com/hostsearch/?q=Google.com");
File.CreateText(filePath).Close();
string number = html.Split(',')[0].Trim();
File.WriteAllText(filePath, number);
MessageBox.Show("Finish");
you are actually close. Check the solution below
var filePath = #"C:\Users\Mirro\Documents\Visual Studio 2010\Projects\Assessment2\Assessment2\act\actors.txt";
WebClient client = new WebClient();
string html = client.DownloadString("https://api.hackertarget.com/hostsearch/?q=google.com");
string[] lines = html.Split(
new[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
);
var res = lines.Select(x => (x.Split(',')[0]).Trim()).ToList();
//res.Dump();
System.IO.File.WriteAllLines(filePath, lines);
.Net Fiddle
Hi
Thanks to Derviş Kayımbaşıoğlu
Also i find my solution from another way
string path = #"D:\Google.txt";
var url = "https://api.hackertarget.com/hostsearch/?q=google.com";
var client = new WebClient();
//StreamWriter myhost = new StreamWriter(path);
using (var stream = client.OpenRead(url))
using (var reader = new StreamReader(stream))
{
string line;
string realString;
using (StreamWriter myhost = new StreamWriter(path))
{
while ((line = reader.ReadLine()) != null)
{
realString = "This is the dns: " + line.Split(',')[0].Trim();
myhost.WriteLine(realString);
}
}
}
MessageBox.Show("Finish");
I have this txt file that contains this text:
MSH^~|\&^R3POCQUERYS^050~BCMABU.MED.VA.GOV~DNS^R3POCQUERYR^^201711081317040500^^RQC~I06^50279320^D^2.5^^^AL^NE^USA
QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T
but I only want the values that come after SSN~% and after the MED~
I want to be able read from the Line that starts with QRD and then be able to grab ANY value after SSN~% and MED~, so the value can be anything I'm just using ABC123 and WA0034 as examples.
Form1.cs
private void Parse(string filename)
{
string line;
var str = File.ReadAllText(filename);
System.IO.StreamReader file = new System.IO.StreamReader(filename);
targetRichTextBox = richTextBox1;
WriteTextSafelyInRichTextBox(str);
while ((line = file.ReadLine()) != null)
{
if ((line.Contains("QRD"))
{
//Enter code here
}
}
char[] delimiterChars = { '^' };
string[] words = str.Split(delimiterChars);
var createText = (RetrunTemplate.Get().Replace(words[24], "VHIC-").Replace(words[25], "9A-MED~WA0034"));
var outputFilename = outputDir + "\\OutboundMessage - " + DateTime.UtcNow.ToString("yyyy-MM-dd HH-mm-ss-ff", CultureInfo.InvariantCulture) + ".txt";
File.WriteAllText(outputFilename, createText);
targetRichTextBox = richTextBox2;
WriteTextSafelyInRichTextBox(createText);
file.Close();
File.Delete(filename);
MessageBox.Show("You have successfuly creatd an outbound Message");
}
RetrunTemplate
class RetrunTemplate
{
public static string Get()
{
string retrunTemplate = #"MSH^~|\&^R3POCSEND^442~CHEY209.FO-BAYPINES.MED.VA.GOV~DNS^R3POCRCV^^20171108131710-0400^^RCL~I06^442157252912^D^2.5^^^AL^NE^USA" + Environment.NewLine +
"PID^^^4420041228V165312~~~USVHA&&0363~NI~VA FACILITY ID&442&L~~20171108|666393848~~~" + Environment.NewLine +
#"USSSA&&0363~SS~VA FACILITY ID&442&L|""~~~USDOD&&0363~TIN~VA FACILITY ID&442&L" + Environment.NewLine +
#"""~~~USDOD&&0363~FIN~VA FACILITY ID&442&L|7209344~~~USVHA&&0363~PI~VA FACILITY ID&442&L" + Environment.NewLine +
#"^VHIC-ABC123~~~USVHA&&0363~PI~VA FACILITY ID&742V1&L^ZEIGLER~PG~EIGHT~~~~L" + Environment.NewLine +
#"|""~~~~~~N^^19220304^M^^^9234234~""~SAN FRANCISCO~CA~94114~USA~P~""~075|~~SAN JOSE~CO~~""~N^^""^^^^^^^^^^^^^^^^^^" + Environment.NewLine +
#"PV1^^^9A-MED" + Environment.NewLine + "HH1^WA0034";
return retrunTemplate;
}
}
Suppose you read the file line by line. You can validate each line against the following Regex, and extract what you want.
var text = "QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T";
var rgx = new Regex(#"QRD.+SSN~%(.+)MED~(.+)");
var match = rgx.Match(text);
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
Console.WriteLine(match.Groups[2].Value);
}
The match.Groups[1] has ABC123^9A-, and match.Groups[2] has WA0034^^^T. You can now do what you will with those text.
Regex Breakdown
#"QRD.+SSN~%(.+)MED~(.+)"
QRD - Starts with the string QRD
.+ - Followed by one or more characters
SSN~% - Followed by SSN~~%
(.+) - Grab (to Groups[1]) one or more characters between SSN~% and MED~
MED! - Followed by MED~
(.+) - Grab everything else in the line to Groups[2]
Here's my effort.
var input = #"MSH^~|\&^R3POCQUERYS^050~BCMABU.MED.VA.GOV~DNS^R3POCQUERYR^^201711081317040500^^RQC~I06^50279320^D^2.5^^^AL^NE^USA
QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T" ;
var pattern = #"SSN\~\%([A-Z0-9]+).*MED\~([A-Z0-9]+)";
var matches = Regex.Matches(input, pattern, RegexOptions.Multiline).
Select( m => new { SSN = m.Groups[1].Value, MED = m.Groups[2].Value});
foreach(var m in matches ) {
Console.WriteLine($"SSN = {m.SSN}, MED = {m.MED}");
}
Output
SSN = ABC123, MED = WA0034
With QRD matching
var input = #"MSH^~|\&^R3POCQUERYS^050~BCMABU.MED.VA.GOV~DNS^R3POCQUERYR^^201711081317040500^^RQC~I06^50279320^D^2.5^^^AL^NE^USA
QRD^20171108131704-0500^R^I^WQRY^^^^SSN~%ABC123^9A-MED~WA0034^^^T";
var pattern = #"SSN\~\%([A-Z0-9]+).*MED\~([A-Z0-9]+)";
var matches = input
.Split()
.Where(l => l.StartsWith("QRD"))
.Select(l => Regex.Matches(l, pattern).Select(m => new { SSN = m.Groups[1].Value, MED = m.Groups[2].Value }));
foreach (var groups in matches)
{
foreach (var g in groups)
{
Console.WriteLine($"SSN = {g.SSN}, MED = {g.MED}");
}
}
Output
SSN = ABC123, MED = WA0034
DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
TextDocument activeDoc = dte.ActiveDocument.Object() as TextDocument;
var text = activeDoc.CreateEditPoint(activeDoc.StartPoint).GetText(activeDoc.EndPoint);
var input = (text);
var regex = new Regex(#"(\bresourcekey\b+) = ");
var match = regex.Matches(input);
string matches = string.Empty;
foreach(var item in match)
{
matches += item.ToString() + " ";
}
MessageBox.Show(matches);
My regex command are fault(i know)but i want capture meta:resourcekey = "......" from my messagebox text i want only .... part of my capturing.
Here is plain regex
meta:resourcekey[\s]=[\s]\"(.*?)\"
And here is c# Example
var mydata = "meta:resourcekey = \"something\"";
Regex regex = new Regex("meta:resourcekey[\\s]*=[\\s]*\"(.*?)\\\"");
foreach (Match htmlPath in regex.Matches(mydata))
{
Console.WriteLine(htmlPath.Groups[1].Value);
}
DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
TextDocument activeDoc = dte.ActiveDocument.Object() as TextDocument;
var text = activeDoc.CreateEditPoint(activeDoc.StartPoint).GetText(activeDoc.EndPoint);
var input = (text);
Regex regex = new Regex(#"(meta:resourcekey)+(\W)+(\w*)+(\W)");
var match = regex.Matches(input);
string matches = string.Empty;
foreach(var item in match)
{
matches += item.ToString() + " ";
}
MessageBox.Show(matches);
I found the answer like that.That makes Scann the current page code and write to text and finally getting meta:resourcekey="something" all of the code pages... Write to MessageBox
I am trying to email a checklist but I can't get the rows to line up.
string aheading = "Defects:";
string bheading = "Comments:";
string result = aheading.PadRight(20, ' ') + bheading.PadRight(20, ' ') + Environment.NewLine;
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
result += item.ItemTitle.Trim().PadRight(20,' ') + item.Comment.Trim().PadRight(20,' ') + Environment.NewLine ;
}
}
In the database there is a list of defects and comments, so the code loops around to display each defect and it's comment on separate lines but it looks like this:
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
Is there a way to get the comments to line up? It's like the vehicle secure string is pushing the comment out. There could be a long list of defects and I won't know how long each string will be so can I set the comments to display in a certain position?
Format your string as HTML, then you could use tables to format. the mailmessage has a property to set its content as Html.
var htmlstring = "<table>";
htmlstring += "<tr><th>Header</th><th>Header</th></tr>";
foreach (var row in content)
{
htmlstring += string.Format("<tr><td>text</td><td>{0}</td></tr>", row.data);
}
htmlstring += "</table>";
var message = new MailMessage();
message.IsBodyHtml = true;
message.Body = htmlString;
implementing the code from the question
string aheading = "Defects:";
string bheading = "Comments:";
string result = string.Format("<table><tr><th>{0}</th><th>{1}</th></tr>", aheading, bheading);
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
result += string.Format("<tr><td>{0}</td><td>{1}</td></tr>", item.ItemTitle.Trim(), item.Comment.Trim());
}
}
result += "</table>";
var message = new MailMessage();
message.IsBodyHtml = true;
message.Body = result;
// SEND MESSAGE
var client = new SmtpClient("mailhost");
// If auth is needed
client.Credentials = new NetworkCredential("username", "password");
client.Send(message);
You should count the length of string.
First, go through all your CheckItems and find the longest ItemTitle
Second, make a variable padding to put the max padding.
Finally, you can count each line's padding by using String.Format
string aheading = "Defects:";
string bheading = "Comments:";
int maxlength = 0;
foreach (var item in chkList.CheckItems)
{
if (item.ItemTitle.Length > maxlength)
maxlength = item.ItemTitle.Length;
}
int padding = maxlength + 10; //10 spaces between the longest 'Defects' and its 'Comments'
string format = "{0,-" + padding + "} {1,-" + padding + "}\r\n"
string result = String.Format(format, "Defects:", "Comments:");
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
result += String.Format(format, item.ItemTitle, Item.Comment);
}
}
Note
Each of the characters in your current font should have the same width.
You should use Monospaced Font in your mail to make this work properly.
If you wish it to work on every font. See #Gelootn's answer instead.
Use String.Format, rather than .padright.
Create a string such as:
string title = String.Format("{0,-10} {1,-10}\n", "Defects:", "Comments:");
Then in your loop use:
string result = String.Format("{0,-10} {1,-10}\n", item.ItemTitle, item.Comment);
You will have to adjust the values to get it to look how you are happy with.
Please tell me hoe to attach the file using telerik rad upload in a mail and send the mail.
I tried differrent scenarios to attach the file to the mail but it doesn't get attached.
Here is the scenario: I used target folder to save it on the webserver and attach the file from that location.
if (rdtxtAdditionalEmail.Text != "")
{
char[] delimiterChars = { ';' };
string text = rdtxtAdditionalEmail.Text;
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
newEmail.To = dr["Email"].ToString();
newEmail.From = "sy#mydomain.com";
newEmail.Subject = rdtxtSubject.Text;
newEmail.BodyFormat = MailFormat.Html;
newEmail.Body = rdtxtSubject.Text;
List<EmailAttachment> attachments = new List<EmailAttachment>();
foreach (EmailAttachment attach in attachments)
{
System.Net.Mail.Attachment attachFile = new Attachment("C:/Inetpub /wwwroot/DotNetNuke/Data/" + attach.fileName);
newEmail.Attachments.Add(attachFile);
}
for (int i = 0; i < rdauAttachments.UploadedFiles.Count; i++)
{
UploadedFile file = rdauAttachments.UploadedFiles[i];
EmailAttachment attachment = new EmailAttachment();
attachment.filePath = "C:/Inetpub/wwwroot/DotNetNuke/Data/" + rdauAttachments.UploadedFiles[i].GetName();
attachment.fileName = rdauAttachments.UploadedFiles[i].GetName();
newEmail.Attachments.Add(attachment);
}
SmtpMail.Send(newEmail);
}
}
I also try to do it using the demo exapmle in telerik pages but it didnot workout.
Please help me.
Thanks,
Sravanthi
string filename = string.Empty;
string path = string.Empty;
MailMessage mailMsg = new MailMessage();
if (AsyncUpload1.UploadedFiles.Count > 0)
{
foreach (UploadedFile file in AsyncUpload1.UploadedFiles)
{
filename = file.FileName;
path = System.IO.Path.GetFileName(filename);
string Withoutext = System.IO.Path.GetFileNameWithoutExtension(filename);
file.SaveAs(Server.MapPath("~/AttachMents/") + path);
FileStream fs = new FileStream(Server.MapPath("~/AttachMents/") + filename,
FileMode.Open, FileAccess.Read);
System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(fs, filename,
MediaTypeNames.Application.Octet);
mailMsg.Attachments.Add(a);
}
}