Friday, March 17, 2017

Episerver - Create Content Area Max Item Restriction

Add Attributes to set the validation

This can of course easily be modified to work with some other scenario.

  [AttributeUsage(AttributeTargets.Property)]  
   public class ContentAreaItemsMaxAttribute : ValidationAttribute  
   {  
     private readonly int _max;  
     public ContentAreaItemsMaxAttribute(int max)  
     {  
       _max = max;  
     }  
     public override bool IsValid(object value)  
     {  
       if ((value != null) && !(value is ContentArea))  
       {  
         throw new ValidationException("ContentAreaItemsMaxAttribute is intended only for use with ContentArea properties.");  
       }  
       var contentArea = value as ContentArea;  
       if (contentArea.Count > _max)  
       {  
         ErrorMessage = string.Format("OBS: You can only add {0} products to the block content area.", _max);  
         return false;  
       }  
       return true;  
     }  
     protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)  
     {  
       var result = base.IsValid(value, validationContext);  
       if (result != null && !string.IsNullOrEmpty(result.ErrorMessage))  
       {  
         result.ErrorMessage = string.Format("{0} {1}", validationContext.DisplayName, ErrorMessage);  
       }  
       return result;  
     }  
   }  

Usage:

Use the Attribute:

[ContentAreaItemsMax(3)] public virtual ContentArea SomeProperty{ get; set; }

Thursday, March 2, 2017

Nuget - Creating Package


From the Developer Command Prompt for Vs2015
Type:
nuget spec //In the source dir for the project.

Then
nuget pack name.something.nuspec