VCF file stream to c# - utf-8

I have a VCF file that contains my entire phonebook. I open it with Notepad and transferring data to windows form in c# via StreamReader. Some of vcard entries contains a row like:
"N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=42=75=72=73=61=6C=C4=B1;=4D=75=73=74=61=66=61;;;"
It looks like the line is UTF-8 code charset, but I have no idea how to convert it to a string.
Thanks for any advice.

using System.Net.Mail;
class Test
{
public static string QPDecode(String str, String encoding)
{
Attachment attachment = Attachment.CreateAttachmentFromString("", "=?" + encoding + "?Q?" + str + "?=");
return attachment.Name;
}
public static void Main(string[] args)
{
Console.WriteLine(QPDecode("=42=75=72=73=61=6C=C4=B1;=4D=75=73=74=61=66=61", "UTF-8"));
//Bursalı;Mustafa
}
}
How to extract the parts "UTF-8" and "=42=75=72=73=61=6C=C4=B1;=4D=75=73=74=61=66=61" from your file is left exercise to you :P

The property value is in quoted-printable encoding, which is a standard encoding mechanism. You may be able to find a library that can decode it for you. Also, try this SO thread.

Related

Spring REST file download unable to set header content-type attachment

I have a Springboot REST application that downloads files from a given directory.
The downloads can be any file file and have any format, and I want to use the original filename as the filename of the downloaded file.
I used the code below to set the filename in the header, and add the header to the response:
#RestController
#RequestMapping("/downloads")
public class DownloadCsontroller {
...
#GetMapping
public void downloadSingleFile(#RequestParam("file") String filename, HttpServletResponse response) throws IOException {
String filepath = m_attachmentPathLocation + File.separator + filename;
File file = new File(filepath);
String contentType = getContentType(file);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(contentType);
response.setHeader("Content-Disposition:", "attachment;filename=\"" + file.getName() + "\"");
...
}
...
}
Tested using both "Content-Disposition" and "Content-Disposition:" in setHeader().
Almost everything works (file types), except for PDF, ZIP, RAR, EXE, etc.
Any files (types) not on the list can be downloaded with the desired filenames.
But when any of the file download (PDF, ZIP, RAR, EXE, etc)... it seems it continuously loads like forever... and I cannot even see any request sent in POSTMAN, inspector, firebug, etc.
If I comment out:
//response.setHeader("Content-Disposition:", "attachment;filename=\"" + file.getName() + "\"");
It would work, but the filename would be set to the name of the request mapping. which in this case is "downloads".
I have seen lots of samples that uses "Content-Disposition" header to change the attachment filename... but it seems it fails on these file types.
I have no configurations yet, and it is kinda weird since in most samples I searched... this should be running or working.
TIA
Please add #GetMapping(produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
and instead of returning direct file try to return stream.
Also make a note that "Content-Disposition:" header will not work if the requesting app IP & Port number is different from server app IP & Port number.
Things would work If you can alter the code a bit, by setting all header values using org.springframework.http.HttpHeaders class.
Now looking at your code, i suspect you trying to expose an API that allows to download a multipart File.
I would suggest you not to use HttpServletResponse Class to set the Content- Dispositionheader but use HttpHeaders class. Below is the reformatted code
#RestController
public class DownloadCsontroller {
#GetMapping(value="/downloads")
public ResponseEntity<Object> downloadSingleFile(#RequestParam("file")
String filename) throws IOException {
String filepath = m_attachmentPathLocation + File.separator + filename;
File file = new File(filepath);
String contentType = getContentType(file);
/* response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(contentType);
response.setHeader("Content-Disposition:", "attachment;filename=\""
+ file.getName() + "\"");
*/
// Here is the below Code you need to reform for Content-
//Disposition and the remaining header values too.
HttpHeaders headers= new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename
=whatever.pdf");
headers.add("Content-Type",contentType);
// you shall add the body too in the ResponseEntity Return object
return new ResponseEntity<Object>(headers, HttpStatus.OK);
}
}

Image without extension in src not loading in IE alone, and works perfect in all other browers

I have below HTML code:
<img title="hotelThumbImage" id="hotelThumbImage01" width="140px" height="129px"
src="/b2c/images/?url=FixedPkgB2c/FF-252-325"/>
It renders in IE as below:
It renders in all other browser like FireFox and Chrome as:
Related question : How to make a Servlet call form UI which returns the Content itself and place an img tag using Script in the output?
My project is suffering from this too, and it's because IE prevents download/display of files which have a different encoding than their extension. It has something to do with malicious code being able to be hidden as image files simply by changing the extension of the file.
Firefox and Chrome are smart enough to display it as an image so long as the encoding is that of an image, but IE takes no chances, it seems.
You'll have to add the extension that matches your image's encoding for it to display in IE.
Edit: It's also possible that your server is sending the file with a header denoting plain text. Again, Firefox and Chrome are smart enough to handle it, but IE isn't. See: https://stackoverflow.com/a/32988576/4793951
Welcome to IE world... :(
What i would do, in order to have better control of the situation is to modify the getter method, so in Holiday.getPkgCode():
public String getPkgCode() throws IOException {
if (!this.pkgCode.contains(".")) {
String ext = ImgUtil.determineFormat(this.pkgCode);
return this.pkgCode + ImgUtil.toExtension(ext);
} else {
return this.pkgCode;
}
}
To use it you will need to catch exceptions and this ImgUtil class adapted from here:
class ImgUtil {
public static String determineFormat(String name) throws IOException {
// get image format in a file
File file = new File(name);
// create an image input stream from the specified file
ImageInputStream iis = ImageIO.createImageInputStream(file);
// get all currently registered readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
throw new RuntimeException("No readers found!");
}
// get the first reader
ImageReader reader = iter.next();
String toReturn = reader.getFormatName();
// close stream
iis.close();
return toReturn;
}
public static String toExtension(String ext) {
switch (ext) {
case "JPEG": return ".jpg";
case "PNG": return ".png";
}
return null;
}
}
TEST IT:
NOTE: I placed an image (jpg) without extension placed in C:\tmp folder
public class Q37052184 {
String pkgCode = "C:\\tmp\\yorch";
public static void main(String[] args) throws IOException {
Q37052184 q = new Q37052184();
System.out.println(q.getPkgCode());
}
// the given getter!!!
}
OUTPUT:
C:\tmp\yorch.jpg
You have to set the Content Type property of responses' header in the servlet.
For example in spring 4 mvc,
#GetMapping(value = "/b2c/images/?url=FixedPkgB2c/FF-252-325")
public ResponseEntity<byte []> getImageThumbnail() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(media type));
byte [] content= ...;
return ResponseEntity.ok().headers(headers).body(content);
}

QTextBrowser: How to represent images copied to the clipboard by custom text?

Consider the following code:
QTextDocument * doc = ui->textBrowser->document();
doc->addResource(QTextDocument::ImageResource, QUrl("img://smiley"), QImage("happy.png"));
QTextCursor cursor = ui->textBrowser->textCursor();
cursor.insertHtml("Sample text ");
cursor.insertImage("img://smiley");
ui->textBrowser->setTextCursor(cursor);
(ui->textBrowser is a pointer to a QTextBrowser object)
When I copy the image to the clipboard, it is represented by an object replacement character (U+FFFC). Is it possible to change this behavior and save e.g. ":-)" instead?
Note that I am using Qt 5.2, so it's fine to use any functions introduced in Qt 5.
I'm afraid there is no simple way. In a web browser alt attribute would help, but Qt doesn't support it.
You can track clipboard's changes and correct its content.
Initialization:
QClipboard* clipboard = QApplication::clipboard();
connect(clipboard, SIGNAL(changed(QClipboard::Mode)),
this, SLOT(clipboard_changed()));
Clipboard correction (example):
void MainWindow::clipboard_changed() {
QClipboard* clipboard = QApplication::clipboard();
const QMimeData* data = clipboard->mimeData();
QString html = data->html();
if (html.contains("<img src=\"img://smiley\" />")) {
QString new_html = html;
new_html.replace("<img src=\"img://smiley\" />", ":-)");
QTextDocument doc;
doc.setHtml(new_html);
QString text = doc.toPlainText();
if (text != data->text()) {
QMimeData* new_data = new QMimeData();
new_data->setHtml(html);
new_data->setText(doc.toPlainText());
clipboard->setMimeData(new_data);
}
}
}
Of course you will need more sophisticated implementation for a real program.
I use QTextDocument just to convert HTML to plain text.

How to successfully parse images from within content:encoded tags using SAX?

I am a trying to parse and display images from a feed that has the imgage URL inside tags. An example is this:
*Note>> http://someImage.jpg is not a real image link, this is just an example. This is what I have done so far.
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuilder();
if (qName.equalsIgnoreCase("content:encoded")) {
if (!atts.getValue("src").toString().equalsIgnoreCase("null")) {
feedStr.setImgLink(atts.getValue("src").toString());
Log.d(TAG, "inside if " + feedStr.getImgLink());
} else {
feedStr.setImgLink("");
Log.d(TAG, feedStr.getImgLink());
}
}
}
I believe this part of my programming needs to be tweaked. First, when qName is equal to "content:encoded" the parsing stops. The application just runs endlessly and displays nothing. Second, if I change that initial if to anything that qName cannot equal like "purplebunny" everything works perfect, except there will be no images. What am I missing? Am I using atts.getValue properly? I have used log to see what comes up in ImgLink and it is null always.
You can store the content:encoded data in a String. Then you can extract image by this library Jsoup
Example:
Suppose content:encoded raw data stored in Description variable.
Document doc = Jsoup.parse(Description);
Element image =doc.select("img").first();
String url = image.absUrl("src");

Algorithm or code for converting OMML to MathML

I am in the process of converting Word doc standard equations (OMML) to MathML using flash or Flex, please help me out by providing simple Algorithm or code snippet.
Thanks in advance,
Mani
There is an XSLT 1 stylesheet that does that conversion provided by microsoft as part of the Word Distribution, it is what handles placing MathML on the clipboard in Word. Typically installed as something like
c:/Program Files (x86)/Microsoft Office/Office14/OMML2MML.XSL
There is some discussion of an early version of this at
http://dpcarlisle.blogspot.co.uk/2007/04/xhtml-and-mathml-from-office-20007.html
here is snippet of a C# class I was working on a few days ago ... I know it's too late .. but for less future pain.
I think it's not very different in Action Script
the file OMML2MML.xsl is located at %ProgramFiles%\Microsoft Office\Office12\ as mentioned by #David the xsl file is used for placing MathML on the clipboard in Word and converting OMML to MML too.
public static string OMML(string omml)
{
XslCompiledTransform xslTransform = new XslCompiledTransform();
xslTransform.Load("OMML2MML.xsl");
using (XmlReader reader = XmlReader.Create(new StringReader(omml)))
{
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = xslTransform.OutputSettings.Clone();
// Configure xml writer to omit xml declaration.
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.OmitXmlDeclaration = true;
XmlWriter xw = XmlWriter.Create(ms, settings);
// Transform our OfficeMathML to MathML
xslTransform.Transform(reader, xw);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms, Encoding.UTF8);
string MathML = sr.ReadToEnd();
return MathML;
}
}
}

Resources