Microsoft Expression SDK - c#

I'm converting mp3 to wma with expression encoder sdk 4 with the code below
A wma file is produced but it is missing the thumbnail / image / cover from the mp3 file.
using (var job = new Job())
{
var mediaItem = new MediaItem(input.FullName)
{
OutputFileName = outputFileName,
OutputFormat =
{
AudioProfile =
{
Codec = AudioCodec.Wma,
Bitrate = BitRate ?? BitRate,
Channels = 1
}
}
};
job.MediaItems.Add(mediaItem);
job.OutputDirectory = OutputDirectory;
job.CreateSubfolder = false;
job.Encode();
}
I have tried the following:
1)
mediaItem.MarkerThumbnailCodec = ImageFormat.Jpeg;
mediaItem.MarkerThumbnailJpegCompression = 0;
mediaItem.MarkerThumbnailSize = new Size(50, 50);
2)
mediaItem.ThumbnailCodec = ImageFormat.Jpeg;
mediaItem.ThumbnailEmbed = true;
mediaItem.ThumbnailJpegCompression = 50;
mediaItem.ThumbnailMode = ThumbnailMode.BestFrame;
mediaItem.ThumbnailSize = new Size(50, 50);
mediaItem.ThumbnailTime = TimeSpan.FromSeconds(0);
3)
mediaItem.OverlayFileName = #"c:\Chrysanthemum.jpg";
mediaItem.OverlayStartTime = TimeSpan.FromSeconds(0);
..but it doesn't help.
Please help me :)

Related

Memorystream performance issue with multiple users

I have a section in my application that displays a PDF to a user. I'm using memorystream to get this document. Whenever I have more than a handful of users requests a document at the same time the performance of my application slows down. If i have 30+ users it comes to a crawl. Most of my users say it starts to slow as they reach the document. Here is how I call the document
public FileStreamResult GetDocument(bool useDefault)
{
string contentType = string.Empty;
short verificationType = VerificationType();
MemoryStream ms = DocumentToStream(useDefault, out contentType);
if (contentType == string.Empty) contentType = "application/pdf";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline;" + FormFileName());
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
HttpContext.Current.Response.OutputStream.Flush();
HttpContext.Current.Response.OutputStream.Close();
HttpContext.Current.Response.End();
ms.Close();
if (verificationType == OBDocVerification.Presentation) SetVerified(verificationType);
return new FileStreamResult(HttpContext.Current.Response.OutputStream, contentType);
}
To get the actual file it does this
private MemoryStream CreatePdfStream(PdfReader pdfDoc, List<MappedField> pdfFields, bool useVerifyButton, bool isLocked, bool isI9, bool isManualUpdate, string state) // 04/26/2018 DS TFS # 3161
{
using (MemoryStream stream = new MemoryStream())
{
PdfStamper stamper = new PdfStamper(pdfDoc, stream);
if (!isLocked)
{
foreach (MappedField mappedFld in pdfFields)
{
if (!string.IsNullOrEmpty(mappedFld.DB_Table))
{
//string v = PDFformFieldValue(mappedFld, this.docLevel);
string v = PDFformFieldValue(mappedFld, this.docLevel, isI9, state); // 10/04/2017 DS TFS # 2768 (added isI9)
if (!string.IsNullOrEmpty(v))
{
stamper.AcroFields.SetField(mappedFld.FormName, v);
}
else
{
stamper.AcroFields.SetField(mappedFld.FormName, string.Empty);
}
if (useVerifyButton)
{
if (!IsPDFformFieldEditable(mappedFld) || !GlobalVariables.IsIE) stamper.AcroFields.SetFieldProperty(mappedFld.FormName, "setfflags", PdfFormField.FF_READ_ONLY, null);
}
}
}
if (isI9) ValidateI9NAFields(ref stamper, pdfFields);
if (!isManualUpdate && GlobalVariables.IsIE) stamper.FormFlattening = true; // 04/26/2018 DS TFS # 3161
}
//else
// stamper.FormFlattening = true;
if (useVerifyButton && GlobalVariables.IsIE)
{
// Add "Verify" button
string alignmentType;
int numberOfPages = pdfDoc.NumberOfPages;
int stampPage = GetVerifyButtonLocation(out alignmentType);
if (stampPage <= 1) stampPage = numberOfPages;
if (stampPage > numberOfPages) stampPage = numberOfPages;
if (alignmentType == string.Empty) alignmentType = "bottom_right";
Rectangle thePage = pdfDoc.GetCropBox(stampPage);
float buttonWidth = 100;
float buttonHeight = 40;
Rectangle ButtonRect = CreateVerifyButtonLocation(thePage, alignmentType, buttonWidth, buttonHeight);
PushbuttonField button = new PushbuttonField(stamper.Writer, ButtonRect, "postSubmit");
button.BackgroundColor = ButtonColor();
button.BorderColor = GrayColor.BLACK;
button.BorderWidth = 1f;
button.BorderStyle = PdfBorderDictionary.STYLE_INSET;
button.TextColor = BaseColor.WHITE;
button.FontSize = 12f;
button.Text = VerifyButtonTitle();
button.Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
button.Rotation = pdfDoc.GetPageRotation(stampPage);
PdfFormField field = button.Field;
//field.Put(PdfName.TU, new PdfString("Save changes and return to the folder."));
field.Action = PdfAction.CreateSubmitForm(this.submitUrl, null, PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_INCLUDE_NO_VALUE_FIELDS);
stamper.AddAnnotation(field, stampPage);
}
//else
// stamper.FormFlattening = true;
stamper.Close();
return stream;
}
}
I feel like I may be doing something inefficient here.
This is not a memory stream problem at all. Consider storing a generated stream and then serve it directly. If you have a large pdf file and several users than
your code will be executed several times with same result.

The process cannot access the file '...' because it is being used by another process

I have a code to delete file in my folder, but in my line code, I want to delete two file together with different folder. But I always get an error "the process cannot access.... another process". May be you can correct my code and give me a solution. Thanks
1) I have a code to generate watermark when save file(.pdf):
public bool InsertWaterMark(string path)
{
bool valid = true;
string FileDestination = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path;
string FileOriginal = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path.Replace("FileTemporary", "FileOriginal");
System.IO.File.Copy(FileDestination, FileOriginal);
string watermarkText = "Controlled Copy";
#region process
PdfReader reader1 = new PdfReader(FileOriginal);//startFile
using (FileStream fs = new FileStream(FileDestination, FileMode.Create, FileAccess.Write, FileShare.None))//watermarkedFile
{
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
int pageCount1 = reader1.NumberOfPages;
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
for (int i = 1; i <= pageCount1; i++)
{
iTextSharp.text.Rectangle rect = reader1.GetPageSize(i);
PdfContentByte cb = stamper.GetUnderContent(i);
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 80);
PdfGState gState = new PdfGState();
gState.FillOpacity = 0.15f;
cb.SetGState(gState);
cb.SetColorFill(BaseColor.GRAY);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f);
cb.EndText();
PdfContentByte canvas = stamper.GetUnderContent(i);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
canvas.SetColorFill(BaseColor.RED);
PdfGState gStateFooter = new PdfGState();
gStateFooter.FillOpacity = 1f;
canvas.SetGState(gStateFooter);
canvas.BeginText();
canvas.SetFontAndSize(bf, 12);
canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, '"' + "When printed, this documents are considered uncontrolled" + '"', 300.7f, 10.7f, 0);
canvas.EndText();
cb.EndLayer();
}
}
}
#endregion
return valid;
}
2) And this code i call when delete detail data from one page together.
public ActionResult Delete(string parm)
{
TableEDIS data = db.TableEDISs.FirstOrDefault(e => e.detail_guid_edis == new Guid(parm));
string fisikFile = data.upload_document;
string fisikFileFormulir = data.upload_document_formulir;
if (!string.IsNullOrEmpty(fisikFile))
{
var relativePath = "~/Content/" + fisikFile;
var absolutePath = HttpContext.Server.MapPath(relativePath);
var absolutePathOriginal = HttpContext.Server.MapPath(relativePath.Replace("Temporary", "Original"));
if (Directory.Exists(Path.GetDirectoryName(absolutePath)))
{
System.IO.File.Delete(absolutePath);
}
if (Directory.Exists(Path.GetDirectoryName(absolutePathOriginal)))
{
System.IO.File.Delete(absolutePathOriginal);
}
}
}
I hope you understand what I mean.
Thanks in advance.
My spidey senses tells me you need to call
reader1.Close();

Album artwork not encoding

Trying to create an mp3 embedder for personal use. Tried all of the solutions here on StackO, but none have worked.
Here is what I have:
TagLib.File tagFile = TagLib.File.Create("C:\\Users\\Dom\\Desktop\\song.mp3");
TagLib.Id3v2.AttachedPictureFrame pic = new TagLib.Id3v2.AttachedPictureFrame();
pic.TextEncoding = TagLib.StringType.Latin1;
pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
pic.Type = TagLib.PictureType.FrontCover;
pic.Data = TagLib.ByteVector.FromPath("C:\\Users\\Dom\\Pictures\\picture.png");
tagFile.Tag.Pictures = new TagLib.IPicture[1] { pic };
tagFile.Tag.Album = "Album 1";
tagFile.Tag.Year = 1990;
tagFile.Save();
The album tag and year tag show up fine under properties, and the program is not crashing or throwing any errors. Picture does not show up as the file icon, or in windows media player. Picture size is 300x300 pixels if that has any importance.
The reason is probably some conflict with existing ID3v2 Tags. Fix it like this:
TagLib.File tagFile = TagLib.File.Create("C:\\Users\\Dom\\Desktop\\song.mp3");
Tag t = tagFile.GetTag(TagTypes.Id3v2);
tagFile.RemoveTags(TagTypes.Id3v2);
Tag tags = tagFile.GetTag(TagTypes.Id3v2);
tagFile.GetTag(TagTypes.Id3v2, true);
tagFile.Save();
tagFile = TagLib.File.Create("C:\\Users\\Dom\\Desktop\\song.mp3");
tags = t;
tagFile.GetTag(TagTypes.Id3v2).Pictures = new IPicture[] {
new Picture("C:\\Users\\Dom\\Pictures\\picture.png")
{ MimeType = "image/png", Type = PictureType.FrontCover }
};
tagFile.Tag.Album = "Album 1";
tagFile.GetTag(TagTypes.Id3v2).Track = 0;
tagFile.Tag.Year = 1990;
tagFile.Save();

Error while opening the excel file created by NPOI

I am using NPOI to export the data to excel. I am forcing the file to be downloaded as an attachment for the user. When the user saves the file on the disk and opens the file it works but fails when he tries to select the open option from the download dialog box. Please see the code below. Not sure what is wrong
var xssfworkbook = new XSSFWorkbook();
var sheet1 = xssfworkbook.CreateSheet("Sheet 1");
//make header row
var row1 = sheet1.CreateRow(0);
var cell0 = row1.CreateCell(0);
cell0.SetCellValue("Firm Id");
var cell1 = row1.CreateCell(1);
cell1.SetCellValue("Account Number");
for (int i = 0; i < result.Count; i++)
{
var row = sheet1.CreateRow(i + 1);
if (result[i].FeeAmount != null)
{
var cellFirmID = row.CreateCell(0);
cellFirmID.SetCellValue(result[i].FirmID);
}
if (result[i].AccountNumber != null)
{
var cellAccountNumber = row.CreateCell(1);
cellAccountNumber.SetCellValue(result[i].AccountNumber);
}
}
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "BESTINVEST_fee_rebate_loader_.xlsx"));
MemoryStream file = WriteToStream(xssfworkbook);
response.Clear();
response.BinaryWrite(file.ToArray());
response.End();
private MemoryStream WriteToStream(XSSFWorkbook xssfworkbook)
{
MemoryStream file = new MemoryStream();
xssfworkbook.Write(file);
return file;
}
This problem is from "culture". before Create excel:
var culture=new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture=culture;
Thread.CurrentThread.CurrentUICulture=culture;
I would recommend you make sure your cells are unlocked.
I use the following without problems:
var workbook = new XSSFWorkbook();
var members = (obj as IEnumerable<MemberListViewModel>).ToDataSourceResult(request).Data;
var sheet = workbook.CreateSheet(TempData["List"].ToString());
var headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Name");
headerRow.CreateCell(1).SetCellValue("Degrees");
headerRow.CreateCell(2).SetCellValue("Rank");
headerRow.CreateCell(3).SetCellValue("Endowed Professorship");
headerRow.CreateCell(4).SetCellValue("Department");
headerRow.CreateCell(5).SetCellValue("Program");
var font = workbook.CreateFont();
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
style.SetFont(font);
style.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
style.IsLocked = false;
style.WrapText = true;
for (int i = 0; i < 6; i++)
{
var colStyle = sheet.GetColumnStyle(i);
colStyle.WrapText = !colStyle.WrapText;
sheet.SetDefaultColumnStyle(i, colStyle);
var cell = headerRow.Cells[i];
cell.CellStyle = style;
}
headerRow.RowStyle = style;
sheet.SetColumnWidth(0, 30 * 256);
sheet.SetColumnWidth(1, 20 * 256);
sheet.SetColumnWidth(2, 20 * 256);
sheet.SetColumnWidth(3, 50 * 256);
sheet.SetColumnWidth(4, 30 * 256);
sheet.SetColumnWidth(5, 50 * 256);
int rowNumber = 1;
style = (XSSFCellStyle)workbook.CreateCellStyle();
style.IsLocked = false;
style.WrapText = true;
foreach (MemberListViewModel member in members)
{
var row = sheet.CreateRow(rowNumber++);
row.CreateCell(0).SetCellValue(member.FullName);
row.CreateCell(1).SetCellValue(member.degrees);
row.CreateCell(2).SetCellValue(member.rank);
row.CreateCell(3).SetCellValue(member.endowed_professorship);
row.CreateCell(4).SetCellValue(member.department);
row.CreateCell(5).SetCellValue(member.program);
}
//var colStyle = sheet.GetColumnStyle(3);
//colStyle.WrapText = !colStyle.WrapText;
//sheet.SetDefaultColumnStyle(3, colStyle);
workbook.Write(output);
var fileName = String.Format(
"{0} {2} - {1}.xlsx",
DateTime.Now.ToString("yyyyMMdd-HHmmss"),
Utilities.getUsername(Utilities.GetCurrentUser()), TempData["List"]).Replace(":", "");
var file = File(output.ToArray(), Utilities.ExcelFileContentType, fileName);
var context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.AddHeader("content-disposition", String.Format("inline;filename=\'{0}\'", fileName));
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = file.ContentType;
context.Response.AddHeader("content-length", file.FileContents.Length.ToString());
context.Response.BinaryWrite(buffer: file.FileContents.ToArray());
context.Response.Flush();
context.Response.End();
output.Dispose();

Images are not coming after creating word Document through Open XML

I am Creating a word document through the c# with the use of OpenXMl sdk.
I am converting all my html page to word document but while converting i am giving a absolute address for my images and after converting it is coming perfectly in my system but when i am trying to take this document to other system the Images are Not Coming there.
I checked the media Directory all images are there but with different Name.
my document is converted but I am Using this mathod.
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(documentPath, true))
{
XNamespace w =
"http://schemas.openxmlformats.org/wordprocessingml/2006/main";
XNamespace r =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships";
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId);
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
using (StreamWriter stringStream = new StreamWriter(chunkStream))
stringStream.Write(html);
XElement altChunk = new XElement(w + "altChunk",
new XAttribute(r + "id", altChunkId)
);
XDocument mainDocumentXDoc = GetXDocument(myDoc);
mainDocumentXDoc.Root
.Element(w + "body")
.Elements(w + "p")
.Last()
.AddAfterSelf(altChunk);
SaveXDocument(myDoc, mainDocumentXDoc);
}
private static XDocument GetXDocument(WordprocessingDocument myDoc)
{
// Load the main document part into an XDocument
XDocument mainDocumentXDoc;
using (Stream str = myDoc.MainDocumentPart.GetStream())
using (XmlReader xr = XmlReader.Create(str))
mainDocumentXDoc = XDocument.Load(xr);
return mainDocumentXDoc;
}
private static void SaveXDocument(WordprocessingDocument myDoc,
XDocument mainDocumentXDoc)
{
// Serialize the XDocument back into the part
using (Stream str = myDoc.MainDocumentPart.GetStream(
FileMode.Create, FileAccess.Write))
using (XmlWriter xw = XmlWriter.Create(str))
mainDocumentXDoc.Save(xw);
}
and this will generate a afchunk.dat file which is showing in the content and the Absolute path.
Basically i doesn't want to create a file through all coding i just want to convert the .html to .docx file .
so can any one tell me how can i convert without getting error in html.
Is there a reason you aren't embedding the images? Here's a link with sample code to show you how.
http://msdn.microsoft.com/en-us/library/bb497430.aspx
Try to create a DocumentResource (Item->Add new) and associate the images there.
Call the Document
using (Stream imgStream = ip.GetStream())
{
System.Drawing.Bitmap logo = DocumentResources._default;
logo.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
Drawing drawing = BuildImage(imageRelationshipID, "_default.jpg", 200, 30);
And create the method to build image in the header or footer;
private static Drawing BuildImage(string imageRelationshipID, string imageName, int pixelWidth, int pixelHeight)
{
int emuWidth = (int)(pixelWidth * EMU_PER_PIXEL);
int emuHeight = (int)(pixelHeight * EMU_PER_PIXEL);
Drawing drawing = new Drawing();
d.Wordprocessing.Inline inline = new d.Wordprocessing.Inline { DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 };
d.Wordprocessing.Anchor anchor = new d.Wordprocessing.Anchor();
d.Wordprocessing.SimplePosition simplePos = new d.Wordprocessing.SimplePosition { X = 0, Y = 0 };
d.Wordprocessing.Extent extent = new d.Wordprocessing.Extent { Cx = emuWidth, Cy = emuHeight };
d.Wordprocessing.DocProperties docPr = new d.Wordprocessing.DocProperties { Id = 1, Name = imageName };
d.Graphic graphic = new d.Graphic();
d.GraphicData graphicData = new d.GraphicData { Uri = GRAPHIC_DATA_URI };
d.Pictures.Picture pic = new d.Pictures.Picture();
d.Pictures.NonVisualPictureProperties nvPicPr = new d.Pictures.NonVisualPictureProperties();
d.Pictures.NonVisualDrawingProperties cNvPr = new d.Pictures.NonVisualDrawingProperties { Id = 2, Name = imageName };
d.Pictures.NonVisualPictureDrawingProperties cNvPicPr = new d.Pictures.NonVisualPictureDrawingProperties();
d.Pictures.BlipFill blipFill = new d.Pictures.BlipFill();
d.Blip blip = new d.Blip { Embed = imageRelationshipID };
d.Stretch stretch = new d.Stretch();
d.FillRectangle fillRect = new d.FillRectangle();
d.Pictures.ShapeProperties spPr = new d.Pictures.ShapeProperties();
d.Transform2D xfrm = new d.Transform2D();
d.Offset off = new d.Offset { X = 0, Y = 0 };
d.Extents ext = new d.Extents { Cx = emuWidth, Cy = emuHeight };
d.PresetGeometry prstGeom = new d.PresetGeometry { Preset = d.ShapeTypeValues.Rectangle };
d.AdjustValueList avLst = new d.AdjustValueList();
xfrm.Append(off);
xfrm.Append(ext);
prstGeom.Append(avLst);
stretch.Append(fillRect);
spPr.Append(xfrm);
spPr.Append(prstGeom);
blipFill.Append(blip);
blipFill.Append(stretch);
nvPicPr.Append(cNvPr);
nvPicPr.Append(cNvPicPr);
pic.Append(nvPicPr);
pic.Append(blipFill);
pic.Append(spPr);
graphicData.Append(pic);
graphic.Append(graphicData);
inline.Append(extent);
inline.Append(docPr);
inline.Append(graphic);
drawing.Append(inline);
return drawing;
}

Categories