本文整理汇总了C#中MediaItem.GetMediaStream方法的典型用法代码示例。如果您正苦于以下问题:C# MediaItem.GetMediaStream方法的具体用法?C# MediaItem.GetMediaStream怎么用?C# MediaItem.GetMediaStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MediaItem
的用法示例。
在下文中一共展示了MediaItem.GetMediaStream方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParsePdf
/// <summary>
/// Parses a pdf item and returns its content as string.
/// </summary>
/// <param name="mediaItem">MediaItem (should be a pdf - otherwise an empty string will be returned).</param>
/// <returns>String represantation of the pdf content.</returns>
public static string ParsePdf(MediaItem mediaItem)
{
if (mediaItem.MimeType != PdfMimetype) return string.Empty;
PDDocument doc = null;
ikvm.io.InputStreamWrapper wrapper = null;
try
{
var stream = mediaItem.GetMediaStream();
wrapper = new ikvm.io.InputStreamWrapper(stream);
doc = PDDocument.load(wrapper);
if (doc.isEncrypted())
{
string[] pwArray = LoadPasswords();
doc = Decrypt(doc, pwArray);
if (doc == null)
{
Log.Warn("PdfUtil :: ParsePDF :: Decryption Failed for: [" + mediaItem.Name + "]", typeof(PdfUtil));
return string.Empty;
}
else
{
Log.Debug("PdfUtil :: ParsePDF :: Successfully decrypted [" + mediaItem.Name + "]", typeof(PdfUtil));
}
}
var stripper = new PDFTextStripper();
return stripper.getText(doc);
}
catch (Exception ex)
{
Log.Error("PdfUtil :: ParsePDF :: Error parsing pdf: [" + mediaItem.Name + "]", ex);
return string.Empty;
}
finally
{
if (doc != null)
{
doc.close();
wrapper.close();
}
}
}
示例2: TestImageImport
public void TestImageImport()
{
string sampleImage = ConfigurationManager.AppSettings["sampleimage"];
SampleSitecoreLogic.ImportImage(sampleImage);
// Get the imported media item
var imported = new MediaItem(Context.Database.GetItem("/sitecore/media library/Cdm"));
Assert.IsNotNull(imported, "Imported image could not be found");
Assert.AreEqual("Image", imported.InnerItem.TemplateName);
// Get the imported image data and put it in a memory stream
var memoryStream = new MemoryStream();
imported.GetMediaStream().CopyTo(memoryStream);
Assert.IsTrue(
FileUtil.ReadBinaryFile(sampleImage).SequenceEqual(memoryStream.ToArray()),
"The imported image's content is different from the file");
}
示例3: AddMediaItemToZip
private void AddMediaItemToZip(MediaItem mediaItem)
{
Assert.ArgumentNotNull(mediaItem, "mediaItem");
using (Stream stream = mediaItem.GetMediaStream())
{
if (stream == null)
{
Log.Warn(string.Format("Cannot find media data for item '{0}'",
mediaItem.MediaPath),
typeof(object));
return;
}
string mediaExtension = string.IsNullOrEmpty(mediaItem.Extension)
? ""
: "." + mediaItem.Extension;
ZipWriter.AddEntry(
mediaItem.MediaPath.Substring(1) +
mediaItem.Name +
mediaExtension, stream);
}
}
示例4: WriteMediaItem
private void WriteMediaItem(MediaItem mediaItem)
{
Assert.ArgumentNotNull(mediaItem, "mediaItem");
Stream mediaStream = mediaItem.GetMediaStream();
string extension = mediaItem.Extension;
if (!extension.StartsWith("."))
{
extension = String.Format(".{0}", extension);
}
WriteCacheHeaders(mediaItem.Name + extension, mediaStream.Length);
WebUtil.TransmitStream(mediaStream, base.Response, Sitecore.Configuration.Settings.Media.StreamBufferSize);
}
示例5: WriteItem
protected virtual void WriteItem([Diagnostics.NotNull] IProject project, [Diagnostics.NotNull] Item item, [Diagnostics.NotNull] string fileName, [Diagnostics.NotNull] ILanguage language, [Diagnostics.NotNull, ItemNotNull] IEnumerable<string> excludedFields)
{
var itemToWrite = ItemImporter.ImportItem(project, item, language, excludedFields);
using (var stream = new StreamWriter(fileName))
{
language.WriteItem(stream, itemToWrite);
}
// write media file
if (!string.IsNullOrEmpty(item["Blob"]))
{
var mediaItem = new MediaItem(item);
var mediaFileName = PathHelper.GetDirectoryAndFileNameWithoutExtensions(fileName) + "." + mediaItem.Extension;
using (var stream = new FileStream(mediaFileName, FileMode.Create))
{
FileUtil.CopyStream(mediaItem.GetMediaStream(), stream);
}
}
}
示例6: SerializeItem
protected virtual void SerializeItem([Diagnostics.NotNull] Item item, [Diagnostics.NotNull] string itemPath)
{
foreach (var mapper in PathMapper.WebsiteItemPathToProjectDirectories)
{
string projectFileName;
string format;
if (!mapper.TryGetProjectFileName(itemPath, item.TemplateName, out projectFileName, out format))
{
continue;
}
var language = LanguageService.GetLanguageByExtension(format);
if (language == null)
{
throw new ConfigurationException(Texts.Format_not_found, format);
}
var fileName = Path.Combine(ProjectDirectory, projectFileName);
FileSystem.CreateDirectoryFromFileName(fileName);
if (item.TemplateID == TemplateIDs.Template)
{
var importTemplate = ItemImporter.ImportTemplate(Project, item);
using (var stream = new StreamWriter(fileName))
{
language.WriteTemplate(stream, importTemplate);
}
continue;
}
var importItem = ItemImporter.ImportItem(Project, item, language, ExcludedFields);
using (var stream = new StreamWriter(fileName))
{
language.WriteItem(stream, importItem);
}
// write media file
if (!string.IsNullOrEmpty(item["Blob"]))
{
var mediaItem = new MediaItem(item);
var mediaFileName = PathHelper.GetDirectoryAndFileNameWithoutExtensions(fileName) + "." + mediaItem.Extension;
using (var stream = new FileStream(mediaFileName, FileMode.Create))
{
FileUtil.CopyStream(mediaItem.GetMediaStream(), stream);
}
}
}
}
示例7: OnItemProcessed
/// <summary>
/// OnItemProcessed event handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnItemProcessed(object sender, EventArgs args)
{
var context = ((ItemProcessedEventArgs)args).Context;
string targetDataBase = context.PublishOptions.TargetDatabase.Name.ToLower();
Databases = Databases.ToLower();
if (Databases.Contains(targetDataBase))
{
using (new Sitecore.SecurityModel.SecurityDisabler())
{
// Get published item in target environment
var item = context.PublishHelper.GetTargetItem(context.ItemId);
// Check if item is published and it is a media item
if (item != null && item.Paths.IsMediaItem)
{
MediaItem mediaItem = new MediaItem(item);
string fileExtension = mediaItem.Extension.ToLower();
// Check if media item is css or js resource
if (fileExtension != "css" && fileExtension != "js")
{
return;
}
try
{
// Get Stream object of the media item
using (Stream mediaStream = mediaItem.GetMediaStream())
{
using (StreamReader sr = new StreamReader(mediaStream))
{
// Read contents of the media items into a String object
string originalString = sr.ReadToEnd();
string newString = String.Empty;
// If media item is CSS, then use CssCompressor for compression
if (fileExtension == "css")
{
newString = new CssCompressor().Compress(originalString);
}
// If media item is JS, then use JavaScriptCompressor for compression
else if (fileExtension == "js")
{
newString = new JavaScriptCompressor().Compress(originalString);
}
if (String.IsNullOrEmpty(newString))
{
return;
}
byte[] byteArray = Encoding.ASCII.GetBytes(newString);
using (MemoryStream stream = new MemoryStream(byteArray))
{
// Edit mediaItem and upload minified version
using (new EditContext((Item)mediaItem, SecurityCheck.Disable))
{
Sitecore.Resources.Media.Media media = MediaManager.GetMedia(mediaItem);
media.SetStream(new MediaStream(stream, fileExtension, mediaItem));
}
}
}
}
Sitecore.Diagnostics.Log.Info(String.Format("Media Items Minfier: Published item - '{0}' minified successfully.", item.Paths.FullPath), this);
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error(String.Format("Media Items Minfier: Published item - '{0}' not minified. Error: ", item.Paths.FullPath), ex, this);
}
}
}
}
}
示例8: ConvertToBlob
protected static void ConvertToBlob(MediaItem mediaItem, List<string> filesToDelete)
{
Assert.ArgumentNotNull(mediaItem, "mediaItem");
Assert.ArgumentNotNull(filesToDelete, "filesToDelete");
string path = mediaItem.InnerItem["path"];
string filePath = mediaItem.InnerItem["file path"];
string extension = mediaItem.InnerItem["extension"];
// Downloading a file and saving them to a blob field
Stream memoryStream = null;
string downloadUrl = string.Empty;
try
{
Media mediaData = MediaManager.GetMedia(mediaItem);
memoryStream = mediaItem.GetMediaStream();
if (memoryStream == null)
{
Log.Warn(string.Format("Cannot find media data at item '{0}'", mediaItem.MediaPath), typeof(MediaStorageManager));
return;
}
// Check whether storage is allowed for media content
if (memoryStream.Length > Configuration.Settings.Media.MaxSizeInDatabase)
{
return;
}
try
{
using (new EditContext(mediaItem.InnerItem))
{
mediaItem.InnerItem.RuntimeSettings.ReadOnlyStatistics = true;
if (!string.IsNullOrEmpty(mediaItem.InnerItem["Path"]))
{
mediaItem.InnerItem["Path"] = string.Empty;
}
mediaItem.InnerItem["file path"] = string.Empty;
Field blobField = mediaItem.InnerItem.Fields[mediaData.MediaData.DataFieldName];
blobField.SetBlobStream(memoryStream);
}
LogInfo("Media item '{0}' with a file reference '{1}' was converted into BLOB".FormatWith(new object[]
{
mediaItem.InnerItem.Uri.ToString(),
filePath
}));
}
catch (Exception ex)
{
mediaItem.InnerItem.Editing.RejectChanges();
Log.Error("Failed to convert file '{0}' into BLOB for '{1}' media item".FormatWith(new object[]
{
filePath, mediaItem.InnerItem.Uri.ToString()
}), ex, typeof(MediaStorageManager));
throw;
}
string fullPath = FileUtil.MapPath(filePath);
if (filesToDelete.IndexOf(fullPath) < 0)
{
filesToDelete.Add(fullPath);
}
}
catch (IOException ex)
{
Log.Error(string.Format("Can't insert blob to item '{0}' from '{1}'", mediaItem.InnerItem.Paths.FullPath, downloadUrl), ex, typeof(MediaStorageManager));
}
catch (Exception ex)
{
Log.Error(string.Format("Can't insert blob to item '{0}' from '{1}'", mediaItem.InnerItem.Paths.FullPath, downloadUrl), ex, typeof(MediaStorageManager));
}
finally
{
if (memoryStream != null)
memoryStream.Close();
}
}
示例9: WriteItem
private void WriteItem([Diagnostics.NotNull] IProject project, [Diagnostics.NotNull] Data.Items.Item item, [Diagnostics.NotNull] string fileName, [Diagnostics.NotNull] string format, [Diagnostics.NotNull] [ItemNotNull] IEnumerable<string> excludedFields)
{
var itemToWrite = BuildItem(project, item, excludedFields);
using (var stream = new StreamWriter(fileName))
{
switch (format.ToLowerInvariant())
{
case "item.json":
var jsonOutput = new JsonTextWriter(stream);
jsonOutput.Formatting = Newtonsoft.Json.Formatting.Indented;
itemToWrite.WriteAsJson(jsonOutput);
break;
case "item.xml":
var xmlOutput = new XmlTextWriter(stream);
xmlOutput.Formatting = System.Xml.Formatting.Indented;
itemToWrite.WriteAsXml(xmlOutput);
break;
case "item.yaml":
itemToWrite.WriteAsYaml(new YamlTextWriter(stream));
break;
}
}
// write media file
if (!string.IsNullOrEmpty(item["Blob"]))
{
var mediaItem = new MediaItem(item);
var mediaFileName = Path.ChangeExtension(fileName, mediaItem.Extension);
using (var stream = new FileStream(mediaFileName, FileMode.Create))
{
FileUtil.CopyStream(mediaItem.GetMediaStream(), stream);
}
}
}