0

Here is what I am hoping to do: I would like to upload a media item to the Media Library.

Here is my Code:

enter image description here

Here is my App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

    <configSections>

    </configSections>

    <startup>

        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />

    </startup>
  <connectionStrings configSource="App_Config\ConnectionStrings.config" />

</configuration>

and ConnectionStrings.config:

<connectionStrings>
  <!-- 
    Sitecore connection strings.
    All database connections for Sitecore are configured here.
  -->
  <add name="core" connectionString="Data Source=Bushcmsdb01dev;Initial Catalog=intranet.dev_core;Integrated Security=False;User ID=ssa-ap-sitecoredev;Password=$eioMaSXln" />
  <add name="master" connectionString="Data Source=Bushcmsdb01dev;Initial Catalog=intranet.dev_master;Integrated Security=False;User ID=ssa-ap-sitecoredev;Password=$eioMaSXln" />
  <add name="web" connectionString="Data Source=Bushcmsdb01dev;Initial Catalog=intranet.dev_web;Integrated Security=False;User ID=ssa-ap-sitecoredev;Password=$eioMaSXln" />
  <add name="reporting" connectionString="Data Source=Bushcmsdb01dev;Initial Catalog=intranet.dev_reporting;Integrated Security=False;User ID=ssa-ap-sitecoredev;Password=$eioMaSXln" />
  <add name="wffm" connectionString="Data Source=Bushcmsdb01dev;Initial Catalog=Sitecore_Wffm;User ID=ssa-ap-sitecoredev;Password=$eioMaSXln"  />
</connectionStrings>

Note: I am using Sitecore 8.2, and I attempting to do this in a console app outside of our Sitecore solution. If this cannot be done, then I will explore using the .web api

7
  • 2
    This cannot be done
    – Marek Musielak
    Commented Dec 10, 2019 at 20:29
  • Thank you for your comment, is the right direction using the Web api? Commented Dec 10, 2019 at 21:01
  • It depends on what you want to achieve. I believe this might be longer discussion so I suggest to move it to sitecore.chat
    – Marek Musielak
    Commented Dec 10, 2019 at 21:52
  • I joined Sitecore chat ... but in a nutshell, I just want to be able to update the Sitecore Media Library outside of our Sitecore environment. We are on Sitecore 8.2, but not using Sitecore MVC currently. Commented Dec 10, 2019 at 22:21
  • Could you please explain the use case here? it will give a good idea about the solution to your problem. I guess you want to upload the media programmatically from public site if so see this - sitecore.stackexchange.com/questions/1374/… Commented Dec 11, 2019 at 5:37

2 Answers 2

0

It's possible but a bit of a rabbit hole. Copy the entire <sitecore> config node into your app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="sitecore" type="Sitecore.Configuration.ConfigReader, Sitecore.Kernel" />
    </configSections>
    <sitecore database="SqlServer">
        //
    </sitecore>      
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
    </startup>
    <connectionStrings configSource="App_Config\ConnectionStrings.config" />
</configuration>

Comment out any <sc.include/> nodes, in <configStores> update arg0 to remove the leading slash (copy those files from your Sitecore solution into the appropriate place, or add them to the project and select to copy on build)

<configStores>
  <add name="domains" type="Sitecore.Configuration.XmlConfigStore, Sitecore.Kernel" factoryMethod="LoadFromFile" arg0="App_Config/Security/Domains.config" />
  <add name="globalRoles" type="Sitecore.Configuration.XmlConfigStore, Sitecore.Kernel" factoryMethod="LoadFromFile" arg0="App_Config/Security/GlobalRoles.config" />
</configStores>

Now wrap your code in a security disabler and an event disabler

using (new SecurityDisabler())
using (new EventDisabler())
{
    MediaCreatorOptions options = new MediaCreatorOptions();
    options.FileBased = false;
    options.IncludeExtensionInItemName = false;
    options.KeepExisting = false;
    options.Versioned = false;
    options.Destination = "/sitecore/media library/...";
    options.Database = Sitecore.Configuration.Factory.GetDatabase("master");

    MediaCreator creator = new MediaCreator();
    var mediaItem = creator.CreateFromFile("...", options);
}

Run the code and add references to any assemblies it complains are missing. Once you have this working you can experiment on cutting out any config sections you don't need. If I was you though, I'd go the API route.

Edit: if you have a running instance of Sitecore you might not see the new items as they are not in the Sitecore cache and Sitecore doesn't know you've created them. Stop and start IIS to make sure.

0

Here is some demo-quality code I once wrote which uses REST. It's very hard-coded and opinionated, but enough to steer you in the right direction. Let me know if you have any questions. You'll need to be familiar with setting up WebAPI controllers and securing them.

[Route("UploadMedia")]
[HttpPost]
public async Task<HttpResponseMessage> UploadMedia()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var root = HttpContext.Current.Server.MapPath("~/temp");
    var provider = new MultipartFormDataStreamProvider(root);

    var creator = new MediaCreator();
    var masterDb = DatabaseHelper.MasterDatabase;

    try
    {
        await Request.Content.ReadAsMultipartAsync(provider);

        var languageCode = provider.FormData["language"];

        var versioned = true;
        if (string.IsNullOrEmpty(languageCode))
        {
            languageCode = "en";
            versioned = false;
        }

        var language = Sitecore.Globalization.Language.Parse(languageCode);

        var ids = new List<Guid>();

        foreach (var file in provider.FileData)
        {
            var fileName = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');

            var fileKey = file.Headers.ContentDisposition.Name.TrimStart('"').TrimEnd('"');
            var index = fileKey.Substring(4);

            var pathKey = $"path{index}";
            var path = provider.FormData[pathKey];

            var nameKey = $"name{index}";
            var name = provider.FormData[nameKey];

            if (path == null || name == null)
            {
                continue;
            }

            var pathItem = masterDb.GetItem(path);
            if (pathItem == null)
            {
                continue;
            }

            var extension = Path.GetExtension(fileName);
            var localFileName = file.LocalFileName + extension;
            File.Copy(file.LocalFileName, localFileName, true);

            name = MakeSeoFriendly(name);
            var destinationPath = $"{path}/{name}";

            using (new LanguageSwitcher(language))
            {
                var destinationItem = (MediaItem)masterDb.GetItem(destinationPath);
                if (destinationItem == null)
                {
                    var options = new MediaCreatorOptions
                    {
                        FileBased = false,
                        IncludeExtensionInItemName = false,
                        OverwriteExisting = false,
                        Versioned = versioned,
                        Destination = destinationPath,
                        Database = masterDb,
                        Language = language
                    };

                    var mediaItem = creator.CreateFromFile(localFileName, options);
                    ids.Add(mediaItem.ID.Guid);
                }
                else
                {
                    var media = MediaManager.GetMedia(destinationItem);
                    using (var fileStream = new MemoryStream(File.ReadAllBytes(localFileName)))
                    {
                        media.SetStream(fileStream, extension);
                    }

                    ids.Add(destinationItem.ID.Guid);
                }
            }
        }

        return Request.CreateResponse(HttpStatusCode.OK, ids);
    }
    catch (Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}

private string MakeSeoFriendly(string str)
{
    if (str == null)
    {
        return null;
    }

    str = Regex.Replace(str, "[\\'\\`]", string.Empty).ToLower();
    str = Regex.Replace(str, "[^a-zA-Z\\-0-9]", "-").ToLower();
    str = Regex.Replace(str, "[\\-]{2,}", "-");
    if (str.StartsWith("-"))
    {
        str = str.Substring(1);
    }

    if (str.EndsWith("-"))
    {
        str = str.TrimEnd('-');
    }

    return str;
}

You then consume it from your console app:

var f = new MultipartFormDataContent
{
    { new StringContent("file1"), "file1" },
    { new StringContent("/sitecore/media library/Images"), "path1" },
    { new StringContent("name of the image"), "name1" },
    { new StringContent("en"), "language" }
};

var fileContent = new StreamContent(fuImage.PostedFile.InputStream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {
    Name = "file1",
    FileName = fuImage.PostedFile.FileName
};
f.Add(fileContent);

var r = await YourRestClient.PostAsync("yourapi/UploadMedia", f);
var sitecoreIds = await r.Content.ReadAsAsync<List<Guid>>();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.