Using CMSDesk and click on the Tools tab, then Media Library I can add files to the inbuilt Kentico Media Library. Is there a way to do this using their API?
You can do this using the Kentico API. It is actually quite rich but the documentation and samples out there are a bit lacking.
Following is a sample method (actually used as a web service method as we have both remote and local pages that use it) and a sample method that calls it (say from an 'edit' web page).
fileLogo - > protected System.Web.UI.WebControls.FileUpload fileLogo;
[WebMethod]
public bool Import(int libraryID, string folderName, string fileName, byte[] bytes)
{
SiteInfo siteInfo = SiteInfoProvider.GetCurrentSite();
MediaLibraryInfo libraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(libraryID);
fileName = fileName.Replace(" ", "-").Replace("&", "-").Replace("'", "-").Replace("+", "-").Replace("=", "-").Replace("[", "-").Replace("]", "-").Replace("#", "-").Replace("%", "-").Replace("\\", "-").Replace("/", "-").Replace(":", "-").Replace("*", "-").Replace("?", "-").Replace("\"", "-").Replace("<", "-").Replace(">", "-").Replace("|", "-");
bool bRetValue = false;
string filePath = Server.MapPath(string.Format("/{0}/media/{1}/{2}/{3}", siteInfo.SiteName, libraryInfo.LibraryFolder, folderName, fileName));
File.WriteAllBytes(filePath, bytes);
if (File.Exists(filePath))
{
string path = MediaLibraryHelper.EnsurePath(filePath);
MediaFileInfo fileInfo = new MediaFileInfo(filePath, libraryInfo.LibraryID, folderName);
fileInfo.FileSiteID = siteInfo.SiteID;
MediaFileInfoProvider.ImportMediaFileInfo(fileInfo);
bRetValue = true;
}
return bRetValue;
}
string filePath = "~/SITENAME/media/SITE_MEDIALIB/Logos/";
string fileName = string.Empty ;
if (fileLogo.FileName.Length > 0)
{
var ext = fileLogo.FileName.Substring(fileLogo.FileName.LastIndexOf('.') + 1).ToLower();
fileName = entryTitle + "." + ext;
MediaLibrary il = new MediaLibrary();
il.Import(3, "FOLDERNAME", fileName, fileLogo.FileBytes);
}
Keeping it here as the original link seems to be dead.
Posted on June 23, 2010 by kevin
So, if you’ve ever worked with the .NET based CMS Kentico (http://www.kentico.com), you’ll know that Media Libraries can be a very powerful tool for organizing your non-site data, including images, documents, and anything else that you need storing and integrating with your CMS. And it all works fantastically, as long as you don’t try to do anything with it code-side. That’s where things get interesting, to say the least.
The Kentico documentation website (http://devnet.kentico.com/documentation.aspx) is very useful in terms of working with and manipulating the tree from the code, it offers very little in terms of manipulating and working-with in general with Media Libraries. So I spent a good amount of time looking through the Modules seeing what Kentico does and how it does it so you don’t have to.
Since this is my first post, and I’m still a little rusty on the whole “writing” thing, so let’s just get to the code.
//Media Library Info - takes Media Library Name and Website Name
MediaLibraryInfo libraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo("Website", "MediaLibrary");
//Folder in Media Library where Item will be Inserted
string mediaLibraryFolder = "MediaLibraryFolder";
//Absolute Path to File
string filePath = Server.MapPath("~/Website/media/MediaLibrary/" + "MediaLibraryFolder/MediaLibraryItem.pdf");
// Get Relative Path to File
string path = MediaLibraryHelper.EnsurePath(filePath);
//create media file info item - takes the relative path to the document, the library ID, and the folder name where the document will be located within the media library
MediaFileInfo fileInfo = new MediaFileInfo(path, libraryInfo.LibraryID, mediaLibraryFolder);
//set the title to something nice
fileInfo.FileTitle = "Document Title";
//set the description to something useful
fileInfo.FileDescription = "Document Description";
// Save media file info
MediaFileInfoProvider.ImportMediaFileInfo(fileInfo);
I think this is pretty self explanatory, we create a MediaFileInfo object, set some stuff in it, and then insert it into the MediaFileInfoProvider. There are a lot of additional properties within the MediaFileInfo object, such as FileSize, which (as the name of the property suggests), stores the file size in a long. Pro tip – use the CMS.GlobalHelper.DataHelper.GetSizeString function to convert the long to a string, formatting it into user-readable data.
This really just scratches the surface on what you can do with Media Libraries in the code-behind. Take a closer look at the MediaFileInfo and MediaFIleInfoProvider classes, along with the MediaLibraryHelper, MediaLibraryInfo, MediaLibraryInfoProvider classes. There’s very little that can’t be done.
Related
I have .net framework web forms that needs to save pdf. But I can't save that to wanted location because application is ran through IISExpres and I cant acces my project directories. This is on localhost but will eventually be on server.
This is code that accepts svg string from javascript.
[WebMethod()]
public static List<string> sendEmail(string svgStr)
{
List<string> ret = new List<string>();
string savePath = Path.Combine("some path", "file.pdf");
var options = new PdfSaveOptions();
//this converts svg string to pdf
//instead of path, there can be passed memory stream provider
//which is extended from Aspose.Html.IO.ICreateStreamProvider
//but i dont know how to use this like memory stream
Converter.ConvertSVG(svgStr, ".", options, savePath);
ret.Add("proslo je");
return ret;
}
Edit: I managed to get the pdf to memory stream and use it later. Thanks for help.
If the path is accessible via the internet not at a lower level than the application that is running it you just need to map the web path to the underlying server path.
var filePath = HttpContext.Current.Server.MapPath("/download/" +filename);
This will take the path from the root of the website.
You just need to provide the required permissions on the target folder for the account running the application. A guide on how to do so can be found here: https://www.online-tech-tips.com/computer-tips/set-file-folder-permissions-windows/
This question is about a asp.net WEB Application and not about .net windows application. In my application I am uploading video files (mp4) using asp.net core.
I need to get metadata from this video file, but for now I am focusing on the duration of this video file.
I have created the form and in my controller I am successfully receiving an IFormFile file object. I can find the size the file by just calling the .length method ( file.Length ) but I am really struggling to get the exact date and especially the duration of this object.
How can I determine the exact date and the duration of this object?
This is my code:
public async Task UploadVideos(IList<IFormFile> files)
{
long size = files.Sum(f => f.Length);
Console.WriteLine("The size of all the selected files is:"+size);
Console.WriteLine("the file name is" + files[0].FileName);
string type = files[0].ContentType;
if (type.Equals("video/mp4"))
{
Console.WriteLine("Indeed a mp4 format");
}
}
Sorry for the late reply, here is how you would go about getting the duration of a video after it is uploaded,
You can use NReco,the provided link has a nice little example on how to get the info of a video,
var ffProbe = new NReco.VideoInfo.FFProbe();
var videoInfo = ffProbe.GetMediaInfo(pathToVideoFile);
Console.WriteLine(videoInfo.FormatName);
Console.WriteLine(videoInfo.Duration);
The the only issue being licensing for commercial use.
The other one you can try is the mediatoolkit, I have used this before and it works great, especially for the functionality that you are looking for, a simple usage would be along the lines of
var inputFile = new MediaFile { Filename = video_name };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
}
A sample image shows the output of calling the getmetadata method,
.
MediaToolkit uses an MIT license
All the above are wrappers of the c++ FFmpeg Library
I am using the media plugin for xamarin forms (by james montemagno) and the actual taking of the picture and storing it works fine, I have debugged the creation of the image on the emulator and it is stored in
/storage/emulated/0/Android/data/{APPNAME}.Android/files/Pictures/{DIRECTORYNAME}/{IMAGENAME}
however in my app it will get a list of file names from an API I want to check if the image exists in that folder.
The following works fine on IOS
var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, App.IMAGE_FOLDER_NAME);
jpgFilename = System.IO.Path.Combine(jpgFilename, name);
I have tried the 2 following methods for getting it on android but both are incorrect
var documentsDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, App.IMAGE_FOLDER_NAME);
jpgFilename = System.IO.Path.Combine(jpgFilename, name);
Java.IO.File dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DataDirectory + "/" + App.IMAGE_FOLDER_NAME + "/" + name);
dir ends up as
/storage/emulated/0/data/{DIRECTORY}/{IMAGENAME}
jpgFileName ends up as /data/data/{APPNAME}.Android/files/{DIRECTORYNAME}/{IMAGENAME}
I dont want to hardcode anything in the paths but neither of these are right. I could not find anything in the GIT documentation for getting the file path except by looking at the path of the file created when taking a picture
The problem
I had the same kind of issue with Xamarin Media Plugin. For me, the problem is:
we don't really know where the plugin save the picture on android.
After reading all documentation I found, I just noted this:
... When your user takes a photo it will still store temporary data, but also if needed make a copy to the public gallery (based on platform). In the MediaFile you will now see a AlbumPath that you can query as well.
(from: Github plugin page)
so you can save your photo to your phone gallery (it will be public) but the path is known.
and we don't know what means "store the temporary data".
Solution
After investigating on how/where an app can store data, I found where the plugin stores photos on Android >> so I can generate back the full file names
In your Android app, the base path you are looking for is:
var basePath = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath
It references your app's external private folder. It looks like that:
/storage/emulated/0/Android/data/com.mycompany.myapp/files
So finally to get your full file's path:
var fullPath = basePath + {DIRECTORYNAME} + {FILENAME};
I suggest you to make a dependency service, for instance 'ILocalFileService', that will expose this 'base path' property.
Please let me know if it works for you !
I resolved a similar problem. I wanted to collect all files for my app in a folder visible to all users.
var documentsDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(
Android.OS.Environment.DirectoryDocuments);
If you want to create Directory, add to your class using System.IO; and you have the same functions in a normal .NET application.
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
If you want to create files or directory, you can use PCLStorage.
public async Task<bool> CreateFileAsync(string name, string context)
{
// get hold of the file system
IFolder folder = FileSystem.Current.LocalStorage;
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync(name,
CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync(context);
return true;
}
to get the private path
var privatePath = file.Path;
to get the public Album path
var publicAlbumPath = file.AlbumPath;
se the documentation here https://github.com/jamesmontemagno/MediaPlugin
I am uploading a PDF file using the following code
if (FileUploadControl.PostedFile.ContentType == "application/pdf")
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/App_Data/") + filename);
// Renaming the file uploaded with the ApplicationId
string filePathName = Server.MapPath("~/App_Data/") + filename;
string newfilePathName = (Server.MapPath("~/App_Data/") + Session["ApplicationId"] + ".pdf");
System.IO.File.Move(filePathName, newfilePathName);
lblStatusLabel.Text = "Upload status: File uploaded!";
roUpdate = engeStamp.UpdateAppStatus(5, Convert.ToInt16(Session["ApplicationId"]));
Response.Redirect("Estamp.aspx", false);
roUpdate = engeStamp.UpdateAppStatus(5, Convert.ToInt16(Session["ApplicationId"]));
}
I need to add a header to the uploaded PDF in all the PDF pages (Like a master page in asp.net)
How is it possible?
There are a number of PDF editor API's that are available. My favorite of them is ActivePDF Toolkit. There are others of varying utilities and price and there is probably some freeware out there as well. ActivePDF will allow you to "stitch" together multiple elements, for instance your header with a users uploaded document.
As Cos Callis stated there are many PDF editor API's available. I would like to recommend Amyuni PDF Creator .Net. You can experiment with the trial version and you will have technical support during your evaluation period. I am part of the development team of this product.
I'm reading a text file containing an insert statement for SQL using C# in an MVC Website I'm working on. When debugging the function I'm using works fine and the insert occurs. But once I publish the site and run it on my local machine (with IIS set-up to use asp.net 4.0 even) it doesn't seem to work.
if (Request.Files != null && Request.Files["txtImportFile"] != null)
{
//newFilePath = Server.MapPath("\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
string[] temp_string = Request.Files["txtImportFile"].FileName.Split(new char[] { '\\' });
string temp_filename = temp_string[temp_string.Count() - 1];
//newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + temp_filename);
Request.Files["txtImportFile"].SaveAs(newFilePath);
StreamReader reader = new StreamReader(newFilePath);
string contents = reader.ReadToEnd();
reader.Close();
Models.WingsRemoteDbLibrary dbLib = new Models.WingsRemoteDbLibrary();
string update_message = dbLib.UpdateSlaveItemsTable(contents);
if (System.IO.File.Exists(newFilePath))
System.IO.File.Delete(newFilePath);
RandomPopupView(update_message);
}
I hope my explanation doesn't sound vague. I'll try my best to answer any further questions. Thanks.
Workaround:
Instead of using
Server.MapPath("\\temp\\"...
Create folder under root with name "temp" and use
System.Web.HttpContext.Current.Request.MapPath("~\\temp....
Well, "it doesn't seem to work" is pretty vague - a bit more detail would be nice! But it sounds like a permissions issue. The default profile in IIS has very little access to the disk, especially write access. It isn't really a good idea to write inside your own site anyway (I'd use an unrelated part of the disk, myself), but you will need to configure IIS to run the application in a specific named identity, with access to the disk. Configuring the account itself (not IIS - the account; for example granting "logon as a service") to run as an ASP.NET account is not particularly trivial, unfortunately.
Another thought: is your app a sub-application, i.e. is your app-root /, or is it /MyApp/ ? The reason I ask is your use of MapPath might be better expressed relative to the app-root, i.e. ~/temp/ - but again I stress; writing inside the app is risky. You really want that folder to be non-executing.
There may be an alternative solution to this problem. You can avoid messing with path and file system altogether if you can 'bake' the file into assembly at build time. Here is how you can do this:
In Visual Studio solution explorer right click on a file and go to Properties.
Set Build Action to 'Embedded Resource'.
Later you can read the file using GetManifestResourceStream:
var stream = GetType()
.Assembly
.GetManifestResourceStream("YourNameSpace.Folder.YourFile.txt");
using (var reader = new StreamReader(stream)) {
var fileContent = reader.ReadToEnd();
}
More info here.