Skip to content

Instantly share code, notes, and snippets.

@sohelsd
Created July 27, 2015 19:48
Show Gist options
  • Save sohelsd/8177af3ab22d64876833 to your computer and use it in GitHub Desktop.
Save sohelsd/8177af3ab22d64876833 to your computer and use it in GitHub Desktop.
Sitecore Programmatically publish content.
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Site.Web
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("AutoPub","utility/publish", new { controller = "Utility", action = "Publish" });
}
}
}
using System;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Sitecore.Data.Engines;
using Sitecore.Data.Proxies;
using Sitecore.Exceptions;
using Sitecore.Publishing;
using Sitecore.SecurityModel;
namespace Site.Web.Controllers.Shared
{
public class UtilityController: Controller
{
public JsonResult Publish()
{
//make sure this does not execute on live site
if (Request.Url != null && Request.Url.AbsoluteUri.Contains("site.com"))
{
return new JsonResult
{
Data = "Invalid Request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
var full = Request.QueryString["full"];
// Set up the publish mode
var publishMode = PublishMode.Smart;
if (!string.IsNullOrWhiteSpace(full) &&
(full == "1" || full.Equals("true", StringComparison.InvariantCultureIgnoreCase)))
{
publishMode = PublishMode.Full;
}
using (new SecurityDisabler())
{
//Target database
var webDb = Sitecore.Configuration.Factory.GetDatabase("web");
//Source db
var masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
try
{
foreach (var language in masterDb.Languages)
{
//loops on the languages and do a full republish on the whole sitecore content tree
var options = new PublishOptions(masterDb, webDb, publishMode, language, DateTime.Now) { RootItem = masterDb.Items["/sitecore"], RepublishAll = true, Deep = true };
var myPublisher = new Publisher(options);
myPublisher.Publish();
}
return new JsonResult
{
Data = "Publish to Web has completed",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
catch (Exception ex)
{
return new JsonResult
{
Data = "Could not publish the master database to the web" + ex.Message + ": " + ex.StackTrace,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment