November 2, 2012

Install a sitecore package in your code

Here is a code snippet to install a sitecore package into your code:
public void InstallPackage(string path)
{
    bool hasPostAction;
    string historyPath;

    // Use default logger
    ILog log = LogManager.GetLogger("root");
    XmlConfigurator.Configure((XmlElement)ConfigurationManager.GetSection("log4net"));

    FileInfo pkgFile = new FileInfo(path);

    if (!pkgFile.Exists)
        throw new ClientAlertException(string.Format("Cannot access path '{0}'. Please check path setting.", path));

    Sitecore.Context.SetActiveSite("shell");
    using (new SecurityDisabler())
    {
        using (new ProxyDisabler())
        {
            using (new SyncOperationContext())
            {
                Sitecore.Install.Framework.IProcessingContext context = new Sitecore.Install.Framework.SimpleProcessingContext(); // 
                Sitecore.Install.Items.IItemInstallerEvents events =
                    new Sitecore.Install.Items.DefaultItemInstallerEvents(new Sitecore.Install.Utils.BehaviourOptions(Sitecore.Install.Utils.InstallMode.Overwrite, Sitecore.Install.Utils.MergeMode.Undefined));
                context.AddAspect(events);
                Sitecore.Install.Files.IFileInstallerEvents events1 = new Sitecore.Install.Files.DefaultFileInstallerEvents(true);
                context.AddAspect(events1);
                var inst = new Sitecore.Install.Installer();
                inst.InstallPackage(Sitecore.MainUtil.MapPath(path), context);
            }
        }
    }            
}

No comments:

Post a Comment