I have a asp.net MVC 3 web application, where in some page I am showing a bar chart.
Now user is asking a "mailto" kind of link in that page and on clicking of that link, email client should open, where TO, Subject & Body will fill automatically and the bar chart should appear in body.
I know there is limitation of "mailto", we can prepare body with simple text like below, but is there any workaround to put graph within email body?
Check Mail
The mailto protocol is pretty limited. You might need to send the email from your server.
using Microsoft.Office.Interop.Outlook;
public void Sendemail()
{
try
{
Application oApp = new Application();
MailItem oMsg = (MailItem)(oApp.CreateItem(OlItemType.olMailItem));
// Set HTMLBody.
const string emailSubject = "Auto Generated Email:Graph Screen Shot Update for";
const string sDisplayName = "MyAttachment";
const int iPosition = 50; //
const int iAttachType = (int)OlAttachmentType.olByValue;
string htmlStart = "<html><body><h5><Font Color=Purpel>Hi,<br/>Please Find below The screen shot as of " + DateTime.Now + "<br/></h5>";
string body = string.Empty;
Microsoft.Office.Interop.Outlook.Attachment oAttach = oMsg.Attachments.Add(#"c:\Apps\download.jpg", iAttachType, iPosition, sDisplayName);
body += "<img src=\"cid:" + oAttach.FileName + "\" /><br/>";
string wholeBody = htmlStart + body + "<h5><Font Color=Purpel>Note:Please check the graph.<br/>Regards,<br/>Md. Ajmal<br/><br/></h5></body></html>";
oMsg.HTMLBody = wholeBody;
// Set the subject.
oMsg.Subject = emailSubject;
//display
oMsg.Display(oMsg);
// Clean up.
oMsg = null;
oApp = null;
}
catch (System.Exception ex)
{
throw ex;
}
}
Related
I'm very new to programming and are trying hard to learn. I've been struggling with an issue for a few hours without understanding what I'm doing wrong.
My goal is to save text (article with a lot of line breaks) to a database, and then retrieve the text and view the output as it was written, with all line breaks preserved.
The text is part of an object named KaseriInfo.
I've read some topics regarding this and tried the following:
Before saving to the Db I use the inputText.Replace("\r\n", "<br />");
After retrieving from Db I user the inputText.Replace("<br />", "\r\n");
I've been mixing with the .Replace-methods in different ways but I won't get the result I wish for.
This is my code for adding to the database using a local web service:
public bool AddKaseri(KaserierInfo kaseri)
{
bool successOrNot = false;
Kaserier kaseriToBeAdded = new Kaserier();
kaseriToBeAdded.Title = kaseri.Title;
kaseriToBeAdded.Content = kaseri.Content.Replace("\r\n", "<br />");
kaseriToBeAdded.About = kaseri.About;
kaseriToBeAdded.Uploaded = DateTime.Now;
db.Kaseriers.Add(kaseriToBeAdded);
try
{
db.SaveChanges();
successOrNot = true;
}
catch (Exception e)
{
Console.WriteLine(e);
}
return successOrNot;
}
And this is the code for retrieving the data from the Db:
public KaserierInfo GetOneKaseri(int id)
{
var result = from row in db.Kaseriers
where row.Id == id
select row;
KaserierInfo kaseri = new KaserierInfo();
var kas = result.FirstOrDefault();
if (kas != null)
{
kaseri.Id = kas.Id;
kaseri.Title = kas.Title;
kaseri.About = kas.About;
kaseri.Content = kas.Content.Replace("<br />", "\r\n");
kaseri.UploadedDateOnly = kas.Uploaded.ToString();
kaseri.Uploaded = kas.Uploaded;
kaseri.UploadedDateOnly = kaseri.Uploaded.ToLongDateString();
}
return kaseri;
}
What is stored in the Db
The HTML-output won't come with line breaks for some reason. This is what is displayed:
Output on website
Here is the C# code inside the controller responsible:
public ActionResult ViewKaseri(int id)
{
//Getting the object from WS
var kas = kasref.GetOneKaseri(id);
//Moving to local object
KaseriModel kaseri = new KaseriModel();
kaseri.Id = kas.Id;
kaseri.About = kas.About;
kaseri.Title = kas.Title;
kaseri.Content = kas.Content;
kaseri.UploadedDateOnly = kas.UploadedDateOnly;
return View(kaseri);
}
I would be glad to solve this so that the line breaks will be rendered correctly. Please keep in mind that my skills are low.
Best
/J
you need to use #Html.Raw(). This will allow you to display the contents
I'm trying to save a xml document programmatically inside the Internal Storage of my Sony Android TV. I will also later on will need to accecss this file. Is it even possible to do and how should I approach this? Any suggestions or solutions?
Code:
public class xmlCreateFile {
Boolean finished = false;
String TAG = "xmlCreateFile";
public Boolean xmlCreate(){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
StreamResult result = new StreamResult(path +"/file.xml");
Log.d(TAG,"Env: " + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS));
//Output to console for testing
StreamResult result2 = new StreamResult(System.out);
// transformer.transform(source, result);
transformer.transform(source, result2);
finished = true;
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
return finished;
}
}
There are a number of ways to store data on a device. It seems like you only need this information to be visible to your app, so you can use the private Internal Storage APIs.
These APIs make it relatively easy to store and retrieve a file. Here's a short example.
// Save a file
String FILENAME = "textfile.txt";
String writeString = "hello world!";
FileOutputStream fos = getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(writeString.getBytes());
fos.close();
// Read file
FileInputStream fis = getActivity().openFileInput(FILENAME);
StringBuilder builder = new StringBuilder();
int inputChar;
while((inputChar = fis.read()) != -1) {
builder.append((char) inputChar);
}
fis.close();
String readString = builder.toString();
I'm using the following code to extract the textual contents from the web pages, my app is hosted on Google App Engine and works exactly like BoilerPipe Web API. The problem is that I can only get the result in plain text format. I played around the library to find a work around, but I couldn't find a method to display the result in HTML. What I am trying to have is to include a option like HTML (extract mode) as in the original BoilerPipe Web API here.
This is the code I'm using for extracting the plain text.
PrintWriter out = response.getWriter();
try {
String urlString = request.getParameter("url");
String listOUtput = request.getParameter("OutputType");
String listExtractor = request.getParameter("ExtractorType");
URL url = new URL(urlString);
switch (listExtractor) {
case "1":
String mainArticle = ArticleExtractor.INSTANCE.getText(url);
out.println(mainArticle);
break;
case "2":
String fullArticle = KeepEverythingExtractor.INSTANCE.getText(url);
out.println(fullArticle);
break;
}
} catch (BoilerpipeProcessingException e) {
out.println("Sorry We Couldn't Scrape the URL you Entered " + e.getLocalizedMessage());
} catch (IOException e) {
out.println("Exception thrown");
}
How can I include the feature for displaying the result in HTML form?
i am using the source code of Boilerpipe, and solve your question with the following code:
String urlString = "your url";
URL url = new URL(urlString);
URI uri = new URI(urlString);
final HTMLDocument htmlDoc = HTMLFetcher.fetch(url);
final BoilerpipeExtractor extractor = CommonExtractors.DEFAULT_EXTRACTOR;
final HTMLHighlighter hh = HTMLHighlighter.newExtractingInstance();
hh.setOutputHighlightOnly(true);
TextDocument doc;
String text = "";
doc = new BoilerpipeSAXInput(htmlDoc.toInputSource()).getTextDocument();
extractor.process(doc);
final InputSource is = htmlDoc.toInputSource();
text = hh.process(doc, is);
System.out.println(text);
Source
I have created html code and then save this html page as an image . The html controls which I have created is showing properly in the image with all images and background color. It is woking fine on localhost.
but I am trying to creating html code to image on the server. the image is creating but it's not showing anything like bgcolor, images, etc.
only blank image is showing.
Code :
Using Ajax calling function from client side I am sending the html content to the serverside
Server Side Method
[System.Web.Services.WebMethod()]
public static void GenerateTemplateImage(string html_Content, string TemplateName)
{
var t = new Thread(MakeScreenshot);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public static void MakeScreenshot()
{
Bitmap bitmap;
string html = string.Empty;
string Title = string.Empty;
string Meta = string.Empty;
string Style = string.Empty;
string ScriptBefore = string.Empty;
string ScriptAfter = string.Empty;
string Scripthead = string.Empty;
html="<div><div id='s_p_box-1' style='background-color: rgb(24, 0, 238); width: 109px; height: 75px;>Welcome </div>' <br/> <img id='template1' class='template' style='border:1px solid green; height:142px;width:116px' src='http://ace.demos.classicinformatics.com/Advertiser-Admin/Campaign/UserTemplate/template1.jpg'></div>";
WebBrowser wb = new WebBrowser();
wb.Navigate("about:blank");
if (wb.Document != null)
{
wb.Document.Write(html);
}
wb.DocumentText = html;
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
// Set the size of the WebBrowser control
// Take Screenshot of the web pages full width
// wb.Width = wb.Document.Body.ScrollRectangle.Width;
wb.Width = 1024;
// Take Screenshot of the web pages full height
// wb.Height = wb.Document.Body.ScrollRectangle.Height;
//wb.Height = 786;
wb.ScrollBarsEnabled = true;
if (wb.Height <= 0)
{
wb.Height = 1024;
}
//if (wb.Width <= 400)
//{
// wb.Width = 700;
//}
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
//Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
//using (bitmap = new Bitmap(wb.Width, wb.Height))
using (bitmap = new Bitmap(wb.Width, wb.Height))
{
//wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
//string imgPath = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ImgPath"].ToString());
//string imgPath="C:\\Projects\\aec\\Ace-A-Metric\\Advertiser-Admin\\Campaign\\UserTemplate\\";
string imgPath = URlPath + "test123" + ".bmp";
//bitmap.Save(#"D:\" + txtTempName.Text + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
bitmap.Save(imgPath, System.Drawing.Imaging.ImageFormat.Bmp);
//string imgpath = Path.Combine(HttpContext.Current.Server.MapPath("~") + "Advertiser-Admin\\Campaign\\UserTemplate\\" + txtTempName.Text +".bmp");
//bitmap.Save(imgpath, System.Drawing.Imaging.ImageFormat.Bmp);
}
wb.Dispose();
GC.Collect();
}
Do not use the WebBrowser control, it is shipped with a lot of constraints due its COM legacy, and the very poor object model.
One of the possible solution is to use Awesomium.Net
Espacially, this article explain the process : Capturing Web-Pages With C# (.NET)
The major difference, is that Awesomium and its .Net wrapper is written with no dependency to the host (actually from the Chromium source code). Then the library is actually standalone and let you consider a lots of more scenarios.
This is very very strange.
Basically, i'm using ASP.NET. What I want is to get the .Text value from a label.
Initially, the label is actually totally empty. However, after some interaction and some clicks etc, the label changes.
Now.... I want to simply access the content of that specific label...BUT....ASP.NET thinks it's content is STILL empty.
As a test, I changed the content of the label in to something obvious like "lol", for example.
Then I did the procedure again. Now....This time, the results for checking the contents after all of the interaction and clicks etc turned out to be "lol"...
This means that ASP isn't keeping track of current changes. It just keeps in mind what the initial values were.
The reason why I am checking the contents is because I wish to send an email. Below is my code:
MailMessage email = new MailMessage();
email.Subject = "****";
email.To.Add(txtEmailTo.Text);
email.From = new MailAddress("****");
email.IsBodyHtml = true;
string emailBody = "<h2>Journey Details</h2><br><strong>From</strong>: %From%<br><strong>To</strong>: %To%<br><strong>Price</strong>: %Price%<br><hr><br>Kind Regards, <br><br>";
String newBody = emailBody;
newBody.Replace("%From%", lblResultsFrom.Text);
email.Body = newBody;
try
{
SMTPServer.Send(email);
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
First, use String.Format() instead of manually replacing string fragments, if possible.
How do you change the label's text? Are you doing it at client side with JavaScript? The text of an html label, span, bold, and lot of tags is not sent back to the server. If you want to change the value of something, and send it back to the server, that must be a textbox, or textarea. Or you would have to use hand coded JavaScript to send the value, and custom server side logic to get the value.
I managed to fix my code. The following works:
var SMTPServer = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("..", "..."),
};
MailMessage email = new MailMessage();
email.Subject = "...";
email.To.Add(txtEmailTo.Text);
email.From = new MailAddress("..");
email.IsBodyHtml = true;
string emailBody = "...";
String newBody = emailBody;
email.Body = newBody;
try
{
SMTPServer.Send(email);
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}