Converting a string into a link in an email - c#

I am trying to send an email to a supervisor when a work order is created
if(TextBox9.Text=="Quality"&&affectedrows==true)
{
boolisLocal=HttpContext.Current.Request.IsLocal;
if(isLocal==true)
{
System.Net.Mail.MailMessagenn=newSystem.Net.Mail.MailMessage();
nn.From=newSystem.Net.Mail.MailAddress("no_reply_workorder#mover.com");//whosend
nn.To.Add(newSystem.Net.Mail.MailAddress("someone.something#mover.com"));
nn.Subject="WorkOrdersTypeQuality";
HttpFileCollectionuploadFiles=Request.Files;
for(inti=0;i<uploadFiles.Count;i++)
{
HttpPostedFileuserpostedfils=uploadFiles[i];
try
{
if(userpostedfils.ContentLength>0)
{
nn.Attachments.Add(newAttachment(userpostedfils.InputStream,Path.GetFileName(userpostedfils.FileName)));
}
}
catch
{
Labelstatusmessage=(Label)DetailsView1.FindControl("lblmessage");
statusmessage.Text="UploadFailedPleaseContactDeveloper";
}
}
nn.Body="DONOTREPLYTOTHISEMAIL"+"<br><br/>"+"WorkOrderNumber"+": "+
""+TextBox13.Text+""+"<-ClickontheWorkOrderNumberForReport"+"<br><br/>"+"WorkOrderNumber"+
": "+""+TextBox13.Text+""+"<-ClickontheWorkOrderNumberToEnterData"+"<br><br/>"+"Requestor"+
": "+TextBoxRequestor.Text+"<br><br/>"+"Date"+": "+
TextBoxDate.Text+"<br><br/>"+"Department"+": "+
TextBox14.Text+"<br><br/>"+"CompletionDate"+": "+
TextBoxCompletionDate.Text+"<br><br/>"+"MachineDescription"+
": "+TextBoxMachineDescription.Text+"<br><br/>"+
"MachineLocation"+": "+TextBoxMachineLocation.Text+
"<br><br/>"+"WorkRequired"+": "+TextBoxWorkRequired.Text+
"<br><br/>"+"Status"+": "+TextBoxStatus.Text;
nn.IsBodyHtml=true;
System.Net.Mail.SmtpClientclient=newSystem.Net.Mail.SmtpClient();
client.Host=ConfigurationManager.AppSettings["smtpServer"];
captureuseremail();
}
}
in the body of the mail I am sending an link to the workorder that just got created, "http://server01/WorkOrder/QualityReport.aspx?WorkOrderNum="TextBox13.Text+"\">" I am working on four different plants so I need to deploy each project to 4 servers and change the link above to server02, server03, and server04 and there are 3 types of workorders so I was thinking of storing each link into a key in web.config:
<add key ="safetylink" value="http://server01/WorkOrderTool/SafetyReport.aspx?WorkOrderNum="/>
Get the value from web.config and store as string and use it in the email I am not sure how to do that:
string safetylink = ConfigurationManager.AppSettings["safetylink"];
mm.Body = "DO NOT REPLY TO THIS EMAIL" + "<br><br/>" + "WorkOrderNumber" + ": " + "<a href=\"safetylink" + TextBox13.Text + "\">"
but that does not work, by doing the above I hope to simple deploy one web application to 4 servers and go into each ones web.config and change the name of the server instead of find and replace.
Thank You in advance coders

thanks to SamIam anytime you want to sent a string as a hyperlink in the body of an email:
use "<a href=\"" + yourstringname"

Related

Adding Newline in string for HTML email body

I'm trying to generate an email with some basic formatting based on labels in a FormView. I'm going the route of Process.Start("mailto:... instead of System.Net.Mail so the email opens up in the default email client to give the user a chance to edit To: CC: etc without making a new form just to handle that. I've got the following code-behind to handle an "Email Form" button for emailing the URL of the webform.
protected void fvBF_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Email")
{
Label lblBFID = (Label)fvBookingForm.FindControl("lblBFID");
Label lblProjectID = (Label)fvBookingForm.FindControl("lblProjectNum");
Label lblProjectName = (Label)fvBookingForm.FindControl("lblProjectName");
Label lblReleaseName = (Label)fvBookingForm.FindControl("lblReleaseName");
Label lblPMName = (Label)fvBookingForm.FindControl("lblPM");
String strReleaseName = String.IsNullOrEmpty(lblReleaseName.Text) ? "[Description]" : lblReleaseName.Text;
String pmFirst = lblPMName.Text.ToString().Split()[0];
String pmLast = lblPMName.Text.ToString().Split()[1];
String strSubject = "BF " + lblBFID.Text + " - " + lblProjectName.Text + " - Release " + strReleaseName;
String strBody = "A Booking Form for Project #"+ lblProjectID.Text + " - " + lblProjectName.Text +
" - Release " + strReleaseName + " has been created or modified. \n\n" + Request.Url.ToString();
Process.Start("mailto:" + pmFirst + "." + pmLast + "#company.com?subject=" +
HttpUtility.HtmlAttributeEncode(strSubject) + "&body=" +
HttpUtility.HtmlAttributeEncode(strBody).Replace("\n", Environment.NewLine));
}
}
However, when the email is generated, there are no line breaks in the body between the "A Booking Form...." sentence and the URL. I've tried putting Environment.NewLine directly in the string.
...created or modified. " + Environment.Newline + Environment.NewLine + Request.Url.ToString();
Which basically gives me the same results. I've tried replacing the \n with <br /> which doesn't add the line break and for some reason, doesn't display the URL either. I can only guess that the problem has to do with the HtmlAttributeEncode() and getting it to parse the NewLine properly. Is there something I'm missing here?
You might want to try .Replace("\r\n", "<br />") on the body after you have done your encoding of the body.
You should probably use StringBuilder here instead of String.
You can then do the following:
StringBuilder builder = new StringBuilder();
builder.AppendLine(string.Format("A Booking Form for Project #{0} - {1}",lblProjectID.Text, lblProjectName.Text));
builder.AppendLine(string.Format(" - Release {0} has been created or modified.", strReleaseName));
builder.AppendLine();
builder.AppendLine(Request.Url.ToString());
String strBody = builder.ToString();
You can also include (char)10 and (char)13 in your string creation. e.g.:
string.Format("First Line{0}{1}Second Line", (char)10, (char)13);
Model.Message = "my message \n second message";
then add this style to string tag style="white-space: pre-line;"
example <h3 style="white-space: pre-line;">#Model.Message</h3>

Facebook feed story not posting when user input's nothing

The title pretty much says it all. A few days ago the FB.Feed was working normally. The user could hit the share button and simply post the pre made feed story to his timeline. Now there has to be some sort of user input involved in order for the story to get posted. Even if its just a white space. Has facebook changed something or what ?
here is the feed method :
if (FB.IsLoggedIn)
{
int shareScore = m_score.globalScore;
string shareMsg1 = "SAmple msg";
string shareMsg2 = "Sample msg2";
if (gameOverFlag)
{
shareScore = m_score.scoreForPost;
shareMsg1 = "game overmsg1";
shareMsg2 = "gameover msg2 ";
}
FB.Feed(
link: "test.com",
linkName: shareMsg1 + (DataHolder.holder.levelIndex + 1).ToString() + " FuBar",
linkDescription: "Some text",
linkCaption: shareMsg2 + shareScore + " and " + score.ToString() + " Stars",
picture: "test.com/test.jpg",
callback: LogCallback
);
}
else
{
FB.Login("public_profile,user_friends,email,publish_actions", LoginCallback);
}
I replaced the proper links with the fictional test.com in the given example.

.Net.Mail new line

I am using .Net.Mail to send text messages but I am having trouble inserting a new line. I have searched the internet, including StackOverflow, for a method to do this. I have found several but non of them work. I am using StringBuilder to build the body of the message but appending a new line or empty line does cause a new line to be inserted into the message. I have also tried "\n" and several other methods but nothing seems to work. I have added my code below. Does anybody know how I can do this.
Thank you in advance for any help that may be offered.
string cellPhone = reader.GetString(reader.GetOrdinal("CellPhone"));
string suffix = reader.GetString(reader.GetOrdinal("Suffix"));
StringBuilder body = new StringBuilder();
cellPhone = cellPhone.Trim().Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "");
if (!suffix.StartsWith("#"))
{
suffix = "#" + suffix;
}
string address = cellPhone + suffix;
reader.Close();
EMail email = new EMail("mail.yyy.com");
email.IsHTML = true;
email.Subject = "Sales Lead from yyy.com";
email.Add_ToAddress(address, false);
body.AppendLine(" ");
body.AppendLine("Name: " + this.tbSalesLeadName2.Text + "EMail: mailto: " + this.tbSalesLeadEmail2.Text);
if (!this.chkSalesLeadEmail2.Checked) //&& (!this.hidCellPhoneProvider.Value.Equals("0", StringComparison.InvariantCultureIgnoreCase)))
{
body.AppendLine("Phone: " + this.tbSalesLeadPhone2.Text);
body.AppendLine("Cell Phone: " + this.tbSalesLeadCellPhone.Text);
}
body.AppendLine(" ");
body.AppendLine(" ");
body.AppendLine("Comments: " + this.tbSalesLeadComments2.Text);
body.AppendLine(" ");
body.AppendLine(" ");
body.AppendLine("***To respond start a new text thread with the cell phone number listed above");
email.Body = body.ToString();
email.From = "xxx#yyy.com";
email.Send_Mail();
email.IsHTML = true;
You say that your body is in HTML format, but it isn't.
You have two options to fix that:
Set IsHTML to false, and your line breaks should work.
Format your body as real HTML, i.e., use HtmlEncode for your data and <br> for your line breaks.
As you are using email.IsHTML = true;, You should be able to put tag in your string builder object.. The code would look like,
body.AppendLine(" <br/>");
body.AppendLine(" <br/>");
body.AppendLine("Comments: " + this.tbSalesLeadComments2.Text + "<br/>");
body.AppendLine(" <br/>");
body.AppendLine(" <br/>");
body.AppendLine("***To respond start a new text thread with the cell phone number listed above<br/>");
email.Body = body.ToString();
You've specified that the email is HTML. New lines are ignored in HTML.
To actually render a line break you need to use <br /> or some other equivalent.
If you don't actually have any HTML to render, then simply specify that the email is not an HTML email and new lines will be rendered as new lines.
Thank you for your advice. Please ignore my earlier comment. Your suggestion did work I just needed to add "\n" where I wanted a new line.
I really appreciate your help.

Emailing in C# why isn't the information sending correctly?

I have a form that the users for my website will fill out. Once they click submit the information they filled out is supposed to be sent to my email. For some reason the information they fill out is not being sent. I am posting the code below. For a while it was working, but I must have changed something simple when I was trying to get other parts of the code to work and now I can't figure it out.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string strMessage = "Bug Name: " + txtBugName.Text.Trim()
+ "<br/>" + "Module Name: " + ddlModule.SelectedValue
+ "<br/>" + "Page Name: " + ddlPage.SelectedValue
+ "<br/>" + "Description: " + txtComments.Text.Trim()
+ "<br/>" + "Email is" + " " + txtemail.Text.Trim()
+ "<br/>" + "The request was sent at" +
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
As you can see I have this code pulling the information they fill out and then also I am formatting it for the email that will be sent to myself. But now I just get a blank email or actually the subject line will have something, but the email will be blank.
Also at the bottom of the code you can see i put this email was sent at + dandt I am trying to have the date and time sent in that part is there any code I can just put there to send the date and time the email was sent at? Like is there any syntax specifically just for date and time?
Thank you all
You're swallowing the exception. Remove the try/catch to see any errors that may occur as you change your code; only apply exception handling after testing.
Verify your method signature (params) here because that's where the mistake lies:
UPDATE:
You need to pass the parameters in the following order (read the link below):
public void Send(
string from,
string to,
string subject,
string body
)
SmtpClient.Send Method (String, String, String, String)
Your wrote the following, with extra strings snipped:
string strMessage = "..." + ... + SendMessage(..., strMessage, ...);
You're calling SendMessage() before assigning strMessage.

C# / Webservice app on server throwing strange exception

We use ADP for employee information. I had to create a small app that called some web services that ADP has to pull employee information. The app is fairly procedural..not really object orientated in a sense. Basically I go through some web services to pull general information, work information, employee status, etc.
I have most of this data writing out to a text file as a log so I can ensure that everything is working correctly. Finally got it all done, and it works perfect on my local machine. Thought I'd just copy the entire structure onto a server and use windows scheduler to schedule the exe to run nightly (once a day). When it tries to run the app it looks like it is dying when it calls the first web service. The task scheduler log says:
""ADP.job" (ADP.exe)
Started 2/11/2010 2:14:34 PM
"ADP.job" (ADP.exe)
Finished 2/11/2010 2:14:38 PM
Result: The task completed with an exit code of (e0434f4d)."
So I checked the event viewer and it says this:
EventType clr20r3, P1 adp.exe, P2 1.0.0.0, P3 4b745bb9, P4 adp, P5 1.0.0.0, P6 4b745bb9, P7 289, P8 2d, P9 system.io.filenotfoundexception, P10 NIL.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
I put in some console.writelines to see where it is failing...
Here is a simple example of main:
static void Main(string[] args)
{
OpenTextFile();
Console.WriteLine("About to process employee work information...");
tw.WriteLine("About to process employee work information...");
//work info service
EmpWorkInfo();
}
And inside of opentextfile:
public static void OpenTextFile()
{
//used to log data
String sLogName;
Console.WriteLine("Inside of opentextfile");
if (Directory.Exists(logPath))
{
//directory exists
}
else
{
Directory.CreateDirectory(logPath);
}
Console.WriteLine("Inside of opentextfile2");
sLogName = "log_" + DateTime.Today.ToString("MM_dd_yyyy") + ".txt";
tw = new StreamWriter(logPath + sLogName);
}
I see all the console.writelines on the server but as soon as it hits this line from main:
EmpWorkInfo();
Thats when all hell breaks lose (basically it doesn't work). The EmpWorkInfo() is simply a function to get work related information from a web service (as I said this works locally).
static void EmpWorkInfo()
{
Console.Writeline("THIS NEVER PRINTS!!!");
SQLClass s=null;
// Create the web service proxy client.
GetEmployeeWorkInfoService oService = new GetEmployeeWorkInfoService();
oService.Timeout = Int32.MaxValue;
// Serialize the UsernameToken into XML.
// Create the UsernameToken as defined in the WS-I secure profile.
UsernameToken oUsernameToken = new UsernameToken(USERNAME, SECRET);
System.Xml.XmlElement oSecurityHeaderXml =
oUsernameToken.GetXml(new System.Xml.XmlDocument());
ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType oSecurityHeader = new ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType();
oSecurityHeader.Any = new System.Xml.XmlElement[] { oSecurityHeaderXml };
oService.Security = oSecurityHeader;
GetEmployeeWorkInfoRequestFilter oFilter = new GetEmployeeWorkInfoRequestFilter();
//filter by thyssenkrupp company
oFilter.Companies = new String[] { COMPANY_IDENTIFIER };
GetEmployeeWorkInfoRequest oRequest = new GetEmployeeWorkInfoRequest();
oRequest.Filter = oFilter;
try
{
EmployeeWorkInfoType[] arPersonalInfo = oService.GetEmployeeWorkInfo(oRequest);
try
{
s = new SQLClass();
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
for (int i = 0; i < arPersonalInfo.Length; i++)
{
String stID = arPersonalInfo[i].EmployeeKey.Identifier.EmployeeId; //employee number
String stEmailAddress = arPersonalInfo[i].WorkInfo.EmailAddress; //employee email address (work)
String stFax = arPersonalInfo[i].WorkInfo.Fax; //employee fax number
DateTime dtHireDate = arPersonalInfo[i].WorkInfo.OriginalHireDate;
String stPhone = arPersonalInfo[i].WorkInfo.Phone; //employee phone number
String stWireless = arPersonalInfo[i].WorkInfo.Wireless; //employee wireless number
tw.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
s.SetSQLCommand("dbo.ADP_uiEmployeeWorkInfo");
s.AddSQLCmdParameter("#EmployeeNumber", System.Data.SqlDbType.VarChar, stID);
s.AddSQLCmdParameter("#EmailAddress", System.Data.SqlDbType.VarChar, stEmailAddress);
s.AddSQLCmdParameter("#Fax", System.Data.SqlDbType.VarChar, stFax);
s.AddSQLCmdParameter("#HireDate", System.Data.SqlDbType.DateTime, dtHireDate);
s.AddSQLCmdParameter("#Telephone", System.Data.SqlDbType.VarChar, stPhone);
s.AddSQLCmdParameter("#Mobile", System.Data.SqlDbType.VarChar, stWireless);
s.SQLExecuteNonQuery();
Console.WriteLine("Processed ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine(Environment.NewLine);
}
s.CloseSQLDB();
s.Dispose();
}
//catch any exception from adp side.
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
}
This functions code is irrelevant (its ugly but do not let that bother you, the code works...). My issue is I cannot even get to the first console.writeline of that function. Is there anything special I need to do when it comes to working with webservices?
Edit
Logpath is defined as simply a static string outside of main:
private static string logPath = Environment.CurrentDirectory + "\\log\\";
I suspect that your application is not able to load the types referenced in that function - EmpWorkInfo.
1) Can you run this application on the target server in a commannd window (cmd.exe) ?
2) Are you using any assemblies from ADP that are installed in the global assembly cache (GAC)? Run "gacutil -l" on your localmachine to see if you are using any assemblies from ADP that are installed in thr gac. If they are, you will need to install these into the machine on which you are running the app.
Does logPath have a trailing backslash? Either way, you ought to use Path.Combine, rather than the string catenation operator (+).
What happens if you comment out all the code in EmpWorkInfo() apart from the first Console.Writeline? Does it still not get written out?
Found out I need the Microsoft.Web.Services3 dll installed on the server.
Continuation on "feroze" answer;
If you want to figure out if the 'loading of dependencies' is causing you grief here, i suggest using the "FUSLOGVW.EXE" tool *(part of .Net). When you run this it will give you a little dialog window with a few options. Create a directory somewhere (like "c:\temp\fusion_logs"), set the mode of FUSLOGVW to "log bind failures only", "custom location->c:\temp\fusion_logs".
Now restart your application and check that it failed. Now look into your fusion_logs directory. This should give you sub directories with different (maybe only 1 for now) application names. Inside each directory you will find the log files. These log files contain the "failed assembly loads" and who (which calling assembly) caused them.
They might help your hunt for a working application,
Hope this helps,
Edit: Posted this after you found the cause. The fuslogvw.exe would have shown you the missing assembly.

Categories

Resources