I have two publishing target - one is stage and one is production.The publishing on Production should adhere to the publishing restrictions, but publishing on Stage should not look at or discard the valid to and valid from dates and publish under any circumstance.
I have written a publishing pipeline (PipelinePublishProvider). I am not sure how could I manage to overwrite the field values temporarily so it publishes on to stage every-time.
public class StagePublishOverride : PipelinePublishProvider
{
public override PublishHelper CreatePublishHelper(PublishOptions options)
{
Assert.ArgumentNotNull(options, "options");
if (options.TargetDatabase.Name.ToLower() == "stage")
{
Item itemToBePublished = new Item(options.RootItem.ID, options.RootItem.InnerData, new Database("web"));
itemToBePublished.Editing.BeginEdit();
itemToBePublished.Publishing.ValidTo = DateTime.MaxValue;
itemToBePublished.Publishing.ValidFrom = DateTime.MinValue;
itemToBePublished.Editing.EndEdit();
options.RootItem = itemToBePublished;
}
if (options is ExtendedPublishOptions)
return new ExtendedPublishHelper(options as ExtendedPublishOptions);
return new PublishHelper(options);
}
}
public class ExtendedPublishHelper : PublishHelper
{
private readonly ExtendedPublishOptions _options;
public ExtendedPublishHelper(ExtendedPublishOptions options)
: base(options)
{
_options = options;
}
public override Item GetVersionToPublish(Item sourceItem)
{
Assert.ArgumentNotNull(sourceItem, "sourceItem");
if (Options is ExtendedPublishOptions)
{
return sourceItem.Publishing.GetValidVersion(Options.PublishDate, _options.RequireApproval);
}
return sourceItem.Publishing.GetValidVersion(Options.PublishDate, true);
}
}
public class ExtendedPublishOptions : PublishOptions
{
public ExtendedPublishOptions(Database sourceDatabase, Database targetDatabase, PublishMode mode, Language language, DateTime publishDate, bool requireApproval)
: base(sourceDatabase, targetDatabase, mode, language, publishDate)
{
RequireApproval = requireApproval;
}
public bool RequireApproval { get; set; }
}
}
I believe you'll be better off adding a processor to the publishItem pipeline. Here is some UNTESTED code, which I think will serve your purpose:
public class PublishOverride : PublishItemProcessor
{
public override void Process(PublishItemContext context)
{
Assert.ArgumentNotNull((object)context, "context");
if (context.Action != PublishAction.None)
return;
Item sourceItem = this.GetSourceItem(context);
if (sourceItem == null)
return;
var stagingDB = Factory.GetDatabase("Stage");
if (stagingDB != null && !sourceItem.Publishing.NeverPublish && context.PublishContext.PublishOptions.TargetDatabase == stagingDB)
{
context.Action = PublishAction.PublishVersion;
context.VersionToPublish = sourceItem;
}
}
private Item GetSourceItem(PublishItemContext context)
{
Assert.ArgumentNotNull((object)context, "context");
return context.PublishHelper.GetSourceItem(context.ItemId);
}
}
Make sure you patch it in before the DetermineAction processor in the default config. So your config patch would look like this:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:x="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<publishItem>
<processor patch:before="*[#type='Sitecore.Publishing.Pipelines.PublishItem.DetermineAction, Sitecore.Kernel']"
type="YourNamespace.PublishOverride, YourAssembly" />
</publishItem>
</pipelines>
</sitecore>
</configuration>
Related
I have custom action filter and i want to write unit test for that in dotnet core weabpi.
please help.
public class ApplicationIdValidationAttribute: IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
var param = context.ActionArguments["Id"];
var modelState = context.ModelState;
if (param!=null && string.IsNullOrEmpty(param.ToString()))
{
modelState.AddModelError("id", "Application id is required");
context.Result = new BadRequestObjectResult(new ModelStateRequestValidationAdaptor(modelState));
return;
}
if (!Guid.TryParse(param?.ToString(), out Guid applicationGuid))
{
modelState.AddModelError("id", "Application id is not a valid Guid");
context.Result = new BadRequestObjectResult(new ModelStateRequestValidationAdaptor(modelState));
return;
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
I have a problem that whenever I create a process instance in Camunda Process Service, it does not write anything to ACT_HI_OP_LOG. I am not sure why it is not saving the histories into database.
#Component
#Order(Ordering.DEFAULT_ORDER + 1)
public class ProcessEngineConfiguration implements ProcessEnginePlugin {
private String tenantId;
#Override
public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
HistoryLevel historyLevel = new HistoryLevelFull();
processEngineConfiguration.setHistoryLevel(historyLevel);
processEngineConfiguration.setTenantCheckEnabled(true);
// processEngineConfiguration.setHistory(org.camunda.bpm.engine.ProcessEngineConfiguration.HISTORY_FULL);
processEngineConfiguration.setTenantIdProvider(new TenantIdProvider() {
#Override
public String provideTenantIdForProcessInstance(TenantIdProviderProcessInstanceContext ctx) {
return tenantId;
}
#Override
public String provideTenantIdForHistoricDecisionInstance(TenantIdProviderHistoricDecisionInstanceContext ctx) {
return tenantId;
}
#Override
public String provideTenantIdForCaseInstance(TenantIdProviderCaseInstanceContext ctx) {
return tenantId;
}
});
processEngineConfiguration.setJobExecutor(processEngineConfiguration.getJobExecutor());
}
This is how I start the process.
ProcessInstance pi = null;
try {
identityService.setAuthentication(getAuthentication());
pi = runtimeService.startProcessInstanceByKey(flowName, businessKey, variables);
} finally {
identityService.setAuthentication(null);
}
if (pi == null)
return null;
Did you check configuration?
historyLevelCheckEnabled default value is true.
Can you try to set that value false.
If you set that false, this check would not be performed.
Customer has requested, that all links to external pages in our sitecore solution should have a nofollow attribute. Which pipeline should I use to have an access to response html (to change the links before they will be delivered with markup to browser)? Or is there any better solution to accomplish this?
JavaScript is not much helpful here because I am not sure if all search engines are able to run JavaScript.
RenderField processor is also not usable, due to many custom tags in our code
You can use the Sitecore.Pipelines.HttpRequest
And patch after the ExecuteRequest.
On this point you have the fully rendered html, including all cached components from the HTML cache.
Edit add a Example:
#region Using
using System;
using System.IO;
using Sitecore.Pipelines.HttpRequest;
#endregion
namespace MySpace.Sitecore.Pipelines
{
public class MyProcessor : HttpRequestProcessor
{
public override void Process(HttpRequestArgs args)
{
if (!global::Sitecore.Context.PageMode.IsPageEditor)
{
if (!args.Context.Request.RawUrl.Contains(".") || (args.Context.Request.RawUrl.ToLower().Contains(".aspx") && !args.Context.Request.RawUrl.ToLower().StartsWith("/sitecore")))
{
args.Context.Response.Filter = new MyInterestFilter(args.Context.Response.Filter);
}
}
}
#region Stream filter
public class MyInterestFilter : Stream
{
public MyInterestFilter(Stream sink)
{
_sink = sink;
}
private Stream _sink;
#region Properites
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
_sink.Flush();
}
public override long Length
{
get { return 0; }
}
private long _position;
public override long Position
{
get { return _position; }
set { _position = value; }
}
#endregion
#region Methods
public override int Read(byte[] buffer, int offset, int count)
{
return _sink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _sink.Seek(offset, origin);
}
public override void SetLength(long value)
{
_sink.SetLength(value);
}
public override void Close()
{
_sink.Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
byte[] data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
string html = System.Text.Encoding.Default.GetString(buffer);
html = MyReplace(html);
byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
_sink.Write(outdata, 0, outdata.GetLength(0));
}
public static string MyReplace(string html)
{
html = html.Replace("TESTSTRING", "REPLACEDTESTSTRING");
return html;
}
#endregion
}
#endregion
}
}
And set a patch file in the App_Config include directory somethings like this:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<httpRequestBegin>
<processor type="MySpace.Sitecore.Pipelines.MyProcessor, MySpace.Sitecore" patch:after="processor[#type='Sitecore.Pipelines.HttpRequest.ExecuteRequest, Sitecore.Kernel']"/>
</httpRequestBegin>
</pipelines>
</sitecore>
</configuration>
As far as I can tell, the answer is no. The issue I'm seeing comes from the Include(params string[]) method in the System.Web.Optimization.Bundle class. Internally this invokes System.Web.Optimization.IncludeDirectory(string, string, bool), which in turn uses this code:
DirectoryInfo directoryInfo = new DirectoryInfo(
HttpContext.Current.Server.MapPath(directoryVirtualPath));
While it is possible to set HttpContext.Current during a unit test, I can't figure out how to make its .Server.MapPath(string directoryVirtualPath) return a non-null string. Since the DirectoryInfo(string) constructor throws an exception when passed a null argument, such a test will always fail.
What is the .NET team's recommendation for this? Do we have to unit test bundling configurations as part of integration tests or user acceptance tests?
I have some good news for you, for RTM we added a new static property on BundleTable to enable more unit tests:
public static Func<string, string> MapPathMethod;
Edit Updated with a test virtual path provider:
So you can do something like this:
public class TestVirtualPathProvider : VirtualPathProvider {
private string NormalizeVirtualPath(string virtualPath, bool isDirectory = false) {
if (!virtualPath.StartsWith("~")) {
virtualPath = "~" + virtualPath;
}
virtualPath = virtualPath.Replace('\\', '/');
// Normalize directories to always have an ending "/"
if (isDirectory && !virtualPath.EndsWith("/")) {
return virtualPath + "/";
}
return virtualPath;
}
// Files on disk (virtualPath -> file)
private Dictionary<string, VirtualFile> _fileMap = new Dictionary<string, VirtualFile>();
private Dictionary<string, VirtualFile> FileMap {
get { return _fileMap; }
}
public void AddFile(VirtualFile file) {
FileMap[NormalizeVirtualPath(file.VirtualPath)] = file;
}
private Dictionary<string, VirtualDirectory> _directoryMap = new Dictionary<string, VirtualDirectory>();
private Dictionary<string, VirtualDirectory> DirectoryMap {
get { return _directoryMap; }
}
public void AddDirectory(VirtualDirectory dir) {
DirectoryMap[NormalizeVirtualPath(dir.VirtualPath, isDirectory: true)] = dir;
}
public override bool FileExists(string virtualPath) {
return FileMap.ContainsKey(NormalizeVirtualPath(virtualPath));
}
public override bool DirectoryExists(string virtualDir) {
return DirectoryMap.ContainsKey(NormalizeVirtualPath(virtualDir, isDirectory: true));
}
public override VirtualFile GetFile(string virtualPath) {
return FileMap[NormalizeVirtualPath(virtualPath)];
}
public override VirtualDirectory GetDirectory(string virtualDir) {
return DirectoryMap[NormalizeVirtualPath(virtualDir, isDirectory: true)];
}
internal class TestVirtualFile : VirtualFile {
public TestVirtualFile(string virtualPath, string contents)
: base(virtualPath) {
Contents = contents;
}
public string Contents { get; set; }
public override Stream Open() {
return new MemoryStream(UTF8Encoding.Default.GetBytes(Contents));
}
}
internal class TestVirtualDirectory : VirtualDirectory {
public TestVirtualDirectory(string virtualPath)
: base(virtualPath) {
}
public List<VirtualFile> _directoryFiles = new List<VirtualFile>();
public List<VirtualFile> DirectoryFiles {
get {
return _directoryFiles;
}
}
public List<VirtualDirectory> _subDirs = new List<VirtualDirectory>();
public List<VirtualDirectory> SubDirectories {
get {
return _subDirs;
}
}
public override IEnumerable Files {
get {
return DirectoryFiles;
}
}
public override IEnumerable Children {
get { throw new NotImplementedException(); }
}
public override IEnumerable Directories {
get {
return SubDirectories;
}
}
}
And then write a unit test using that like so:
[TestMethod]
public void StyleBundleCustomVPPIncludeVersionSelectsTest() {
//Setup the vpp to contain the files/directories
TestVirtualPathProvider vpp = new TestVirtualPathProvider();
var directory = new TestVirtualPathProvider.TestVirtualDirectory("/dir/");
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style1.0.css", "correct"));
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style.css", "wrong"));
vpp.AddDirectory(directory);
// Setup the bundle
ScriptBundle bundle = new ScriptBundle("~/bundles/test");
bundle.Items.VirtualPathProvider = vpp;
bundle.Include("~/dir/style{version}.css");
// Verify the bundle repsonse
BundleContext context = SetupContext(bundle, vpp);
BundleResponse response = bundle.GetBundleResponse(context);
Assert.AreEqual(#"correct", response.Content);
}
In .Net 4.5 things have slightly changed. Here is a working version of the approved answer updated to accommodate these changes (I am using Autofac). Note the "GenerateBundleResponse" instead of "GetBundleResponse":
[Fact]
public void StyleBundleIncludesVersion()
{
//Setup the vpp to contain the files/directories
var vpp = new TestVirtualPathProvider();
var directory = new TestVirtualPathProvider.TestVirtualDirectory("/dir/");
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style1.0.css", "correct"));
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style.css", "wrong"));
vpp.AddDirectory(directory);
// Setup the bundle
var bundleCollection = new BundleCollection();
var bundle = new ScriptBundle("~/bundles/test");
BundleTable.VirtualPathProvider = vpp;
bundle.Include("~/dir/style{version}.css");
bundleCollection.Add(bundle);
var mockHttpContext = new Mock<HttpContextBase>();
// Verify the bundle repsonse
var context = new BundleContext(mockHttpContext.Object, bundleCollection, vpp.ToString());
var response = bundle.GenerateBundleResponse(context);
Assert.Equal(#"correct", response.Content);
}
What could be the better implementation for STE, I heard about that DbContext is the simplest way to implement a Repo with EF, personally I take advantage of the EntityState, but there is any member on ObjectContext that could deliver more functionallity for my CRUD operations using Repo? at today I'm using a GenericRepository like this one :
public class GenericRepository<TEntity> where TEntity : class
{
internal DbContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(DbContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
}
I forgot to mention that also I'm using Unity, so the calls to Repository are like this way :
[Dependency]
public IUnityContainer Container { get; set; }
public List<Case> GetAll()
{
using (var context = Container.Resolve<ClaimEntities>())
{
var qry = (from c in context.Cases
select c).ToList();
return qry;
}
}
Self tracking entities are feature of ObjectContext - they are not supported in DbContext. If you want STEs you need to swap to ObjectContext API and use STEs T4 template to generate entities instead of your current POCOs.