public ActionResult CreateNewForm(CreateMacroModel createModel) { Mandate.ParameterNotNull(createModel, "createModel"); Mandate.That <NullReferenceException>(!string.IsNullOrEmpty(createModel.Name)); //validate the model TryUpdateModel(createModel); //if at this point the model state is invalid, return the result which is the CreateNew view if (!ModelState.IsValid) { return(View(createModel)); } //everything is valid, now we need to render out the editor for this macro var editorModel = new MacroEditorModel { Name = createModel.Name, MacroType = createModel.MacroType, Alias = createModel.Name.ToUmbracoAlias(), SelectedItem = "" }; EnsureModelListData(editorModel); return(ProcessSubmit(editorModel)); }
/// <summary> /// Root-level encryption of plain text ctor /// </summary> public PublicKeyEncryptionOnion(byte[] plainData, string asymmetricThumbprint) { if (null == plainData || !plainData.Any()) { throw new ArgumentNullException(nameof(plainData)); } Mandate.That(asymmetricThumbprint, nameof(asymmetricThumbprint)).IsNotNullOrEmpty(); AsymmetricThumbprint = asymmetricThumbprint; InnerOnion = null; using (var aes = new AESCryptoAgent()) using (var rsa = new RSACryptoAgent(asymmetricThumbprint)) { // generate the aes key and use it to encrypt the original plaintext var symmetricKey = aes.GenerateKey(); SymmetricAlgorithmIV = aes.GenerateIV(); SymmetricEncryptedData = aes.Encrypt(plainData, symmetricKey, SymmetricAlgorithmIV); // encrypt the aes key with the public key AsymmetricEncryptedKey = rsa.Encrypt(symmetricKey); } }
/// <summary> /// Returns a list of URLs with the domains assigned based on the list of ancestorsOrSelf. If no domain is assigned to the branch that the entity exists in a null value is returned. /// </summary> /// <param name="ancestorsOrSelf">The ancestorsOrSelf list to create the URL for</param> /// <returns></returns> protected IEnumerable <UrlResolutionResult> GetDomainUrls(IEnumerable <TypedEntity> ancestorsOrSelf) { var reversed = ancestorsOrSelf.Reverse(); var parts = new List <string>(); //need to figure out a domain assigned to this node foreach (var a in reversed) { if (DomainList.ContainsContentId(a.Id)) { //ok, we've found a node with a domain assigned, return a list of URLs with all domains assigned to this id return(DomainList[a.Id] .Select(d => new UrlResolutionResult( (d.Hostname + _httpContext.Request.ApplicationPath.TrimEnd('/') + "/" + string.Join("/", Enumerable.Reverse(parts).ToArray())).TrimEnd('/'), UrlResolutionStatus.SuccessWithHostname)) .ToArray()); } else { var urlAlias = a.InnerAttribute <string>(NodeNameAttributeDefinition.AliasValue, "UrlName"); Mandate.That(!urlAlias.IsNullOrWhiteSpace(), x => new InvalidOperationException("UrlName cannot be empty")); parts.Add(urlAlias); } } //this will occur if no domains are found return(Enumerable.Empty <UrlResolutionResult>()); }
/// <summary> /// N-level encryption of existing onion ctor /// </summary> public PublicKeyEncryptionOnion(PublicKeyEncryptionOnion innerOnion, string asymmetricThumbprint) { Mandate.That(innerOnion, nameof(innerOnion)).IsNotNull(); Mandate.That(asymmetricThumbprint, nameof(asymmetricThumbprint)).IsNotNullOrEmpty(); AsymmetricThumbprint = asymmetricThumbprint; InnerOnion = innerOnion.Clone(); // allocate a new object so we're self contained and the calling code can do whatever it wants with the parameter object InnerOnion.AsymmetricEncryptedKey = null; using (var aes = new AESCryptoAgent()) using (var rsa = new RSACryptoAgent(asymmetricThumbprint)) { // generate the aes key and use it to re-encrypt the original key var symmetricKey = aes.GenerateKey(); SymmetricAlgorithmIV = aes.GenerateIV(); SymmetricEncryptedData = aes.Encrypt(innerOnion.AsymmetricEncryptedKey, symmetricKey, SymmetricAlgorithmIV); // encrypt the aes key with the public key AsymmetricEncryptedKey = rsa.Encrypt(symmetricKey); } // even though we're not using the param onion, we don't want to let it retain the data that's at a lower level of encryption innerOnion.AsymmetricEncryptedKey = null; }
protected virtual void AddRecycleBin(HiveId parentId, FormCollection queryStrings) { //check if this node is the first node in the tree, if so, then append the recycle bin. //if the tree is in dialog mode then ignore if (RecycleBinId.IsNullValueOrEmpty() || (parentId != RootNodeId) || queryStrings.GetValue <bool>(TreeQueryStringParameters.DialogMode)) { return; } var hiveProvider = GetHiveProvider(parentId, queryStrings); using (var uow = hiveProvider.CreateReadonly <IContentStore>()) { var recycleBinEntity = uow.Repositories.Get(RecycleBinId); Mandate.That(recycleBinEntity != null, x => new NullReferenceException("Could not find the Recycle bin entity with Id" + RecycleBinId + " in the repository")); var recycleBinNode = CreateTreeNode(RecycleBinId, queryStrings, "Recycle bin", Url.GetCurrentDashboardUrl()); //TODO: check if bin is empty, if so render the bin_empty.png icon recycleBinNode.Icon = Url.Content(BackOfficeRequestContext.Application.Settings.RebelFolders.DocTypeIconFolder + "/bin.png"); //add the menu items recycleBinNode.AddMenuItem <EmptyRecycleBin>("emptyBinUrl", Url.GetEditorUrl("EmptyBin", null, EditorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings)); recycleBinNode.AddEditorMenuItem <Permissions>(this, "permissionsUrl", "Permissions"); recycleBinNode.AddMenuItem <Reload>(); recycleBinNode.Style.AddCustom("recycle-bin"); //check if it has children recycleBinNode.HasChildren = recycleBinEntity.RelationProxies.GetChildRelations(FixedRelationTypes.DefaultRelationType).Any(); NodeCollection.Add(recycleBinNode); } }
public EncryptedTransmission EncryptAndSign(string plainData, string thumbprintUs, string thumbprintThem, Encoding encoding = null) { if (null == plainData || !plainData.Any()) { throw new ArgumentNullException(nameof(plainData)); } Mandate.That(thumbprintUs, nameof(thumbprintUs)).IsNotNullOrEmpty(); Mandate.That(thumbprintThem, nameof(thumbprintThem)).IsNotNullOrEmpty(); var enc = encoding ?? Encoding.UTF8; var plain = enc.GetBytes(plainData); using (var rsaUs = _rsaCryptoAgentFactory.CreateRSACryptoAgent(thumbprintUs)) using (var rsaThem = _rsaCryptoAgentFactory.CreateRSACryptoAgent(thumbprintThem)) using (var aes = _aesCryptoAgentFactory.CreateAesCryptoAgent(true)) { var sKey = aes.GenerateKey(); var cipherText = aes.Encrypt(plain, sKey, new byte[16]); // use zero-array IV for single key use scenarios var cipherKey = rsaThem.Encrypt(sKey, false); var signature = rsaUs.Sign(plain); return(new EncryptedTransmission(cipherKey, cipherText, signature, enc)); } }
public bool Verify(byte[] plainData, string b64Signature, string thumbprintThem) { if (null == plainData || !plainData.Any()) { throw new ArgumentNullException(nameof(plainData)); } Mandate.That(b64Signature, nameof(b64Signature)).IsNotNullOrEmpty(); Mandate.That(thumbprintThem, nameof(thumbprintThem)).IsNotNullOrEmpty(); byte[] signature; try { signature = Convert.FromBase64String(b64Signature); } catch (FormatException ex) { throw new FormatException("Error converting signature from base64", ex); } using (var rsaThem = _rsaCryptoAgentFactory.CreateRSACryptoAgent(thumbprintThem)) { return(rsaThem.Verify(plainData, signature)); } }
public ProviderMappingGroup(string key, IEnumerable <WildcardUriMatch> matches, IEnumerable <ReadonlyProviderSetup> readers, IEnumerable <ProviderSetup> writers, IFrameworkContext frameworkContext) { Mandate.ParameterNotNullOrEmpty(key, "key"); Mandate.ParameterNotNull(readers, "readers"); Mandate.ParameterNotNull(writers, "writers"); var readerCount = readers.Count(); var writerCount = writers.Count(); Mandate.That(readerCount > 0 || writerCount > 0, x => new ArgumentOutOfRangeException("readers / writers", "ProviderMappingGroup '{0}' must be supplied with at least one reader or writer. Given Readers: {1}, Writers: {2}" .InvariantFormat(key, readerCount, writerCount))); Mandate.ParameterNotNull(frameworkContext, "frameworkContext"); Key = key; FrameworkContext = frameworkContext; WildcardUriMatches = matches; Readers = readers; Writers = writers; }
/// <summary> /// Casts an IFileInfo object as an FSFileInfo, failing if the type is incorrect /// </summary> /// <param name="key"></param> /// <returns></returns> public static FSFileInfo AsFSFileInfo(this IFileInfo key) { var item = key as FSFileInfo; Mandate.That <ArgumentException>(item != null); return(item); }
public MemberGroupEditorController(IBackOfficeRequestContext requestContext) : base(requestContext) { _hive = BackOfficeRequestContext.Application.Hive.GetWriter(new Uri("security://member-groups")); Mandate.That(_hive != null, x => new NullReferenceException("Could not find hive provider for route security://member-groups")); }
public void Mandate_IsBetween() { Exception ex = Assert.Throws <ArgumentOutOfRangeException>(() => Mandate.That(new DateTime(1979, 12, 12), "Test") .IsBetween(DateTime.MinValue, DateTime.MinValue.AddYears(1))); }
/// <summary> /// Executes the action as a ChildAction but maintains the action's result so that it can be retreived /// </summary> /// <typeparam name="TResult"></typeparam> /// <typeparam name="TControllerType"></typeparam> /// <param name="controller"></param> /// <param name="proxyController"></param> /// <param name="methodSelector"></param> /// <param name="area"></param> /// <param name="routeVals"> </param> /// <returns></returns> public static ProxyRequestResult <TResult> ProxyRequestToController <TResult, TControllerType>( this ControllerBase controller, TControllerType proxyController, Expression <Func <TControllerType, TResult> > methodSelector, string area, IEnumerable <KeyValuePair <string, object> > routeVals) where TResult : ActionResult where TControllerType : class { Mandate.ParameterNotNull(proxyController, "proxyController"); Mandate.ParameterNotNull(methodSelector, "methodSelector"); Mandate.That(TypeFinder.IsTypeAssignableFrom <ControllerBase>(proxyController), x => new InvalidOperationException("TControllerType must be of type " + typeof(ControllerBase).FullName)); //validate that proxying is possible, if not an exception is thrown ValidateProxyableRequest(true); var methodInfo = Rebel.Framework.ExpressionHelper.GetMethodInfo(methodSelector); var methodParams = Rebel.Framework.ExpressionHelper.GetMethodParams(methodSelector); //merge values foreach (var i in routeVals.Where(i => !methodParams.ContainsKey(i.Key))) { methodParams.Add(i.Key, i.Value); } return(controller.ExecuteProxiedControllerAction <TResult>( ControllerExtensions.GetControllerName(proxyController.GetType()), methodInfo.Name, area, methodParams)); }
public void Mandate_IsNotNullOrEmpty() { Exception ex = Assert.Throws <ArgumentException>(() => Mandate.That(string.Empty, "Test").IsNotNullOrEmpty()); Exception ex2 = Assert.Throws <ArgumentException>(() => Mandate.That(default(string), "Test").IsNotNullOrEmpty()); }
public SecurityService(IHiveManager hive, IEnumerable <Lazy <Permission, PermissionMetadata> > permissions) { Mandate.That <NullReferenceException>(hive != null); Mandate.That <NullReferenceException>(permissions != null); _hive = hive; _permissions = permissions; }
public DependencyResolverAttributeTypeRegistry() { var dependencyResolver = DependencyResolver.Current; Mandate.That(dependencyResolver != null, x => new InvalidOperationException("DependencyResolver.Current returned null, ensure that IoC is setup")); _internalRegistry = dependencyResolver.GetService <IAttributeTypeRegistry>(); Mandate.That(_internalRegistry != null, x => new InvalidOperationException("Could not resolve an IAttributeTypeRegistry from the DependencyResolver, ensure that one is registered in IoC")); }
public void Mandate_IsNullOrWhiteSpace() { Exception ex = Assert.Throws <ArgumentException>(() => Mandate.That(default(string), "Test").IsNullOrWhiteSpace()); Exception ex2 = Assert.Throws <ArgumentException>(() => Mandate.That(default(string), "Test").IsNullOrWhiteSpace()); }
public ContentEditorController(IBackOfficeRequestContext requestContext) : base(requestContext) { _hive = BackOfficeRequestContext.Application.Hive.GetWriter <IContentStore>(); _readonlyHive = BackOfficeRequestContext.Application.Hive.GetReader <IContentStore>(); Mandate.That(_hive != null, x => new NullReferenceException("Could not find hive provider for route content://")); }
public bool IsPrivateKeyAvailable(string thumbprint) { Mandate.That(thumbprint, nameof(thumbprint)).IsNotNull(); var certCollection = _certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); return(certCollection.Count > 0 && certCollection[0].HasPrivateKey); }
public void Mandate_String_IsLessThanOrEqualTo() { Exception ex = Assert.Throws <ArgumentOutOfRangeException>(() => Mandate.That("1", "Test").IsLengthLessThanOrEqualTo(2)); Exception ex2 = Assert.Throws <ArgumentOutOfRangeException>( () => Mandate.That("12", "Test").IsLengthLessThanOrEqualTo(2)); }
public DecryptedTransmission(byte[] plainData, bool verified, Encoding encoding) { Mandate.That(plainData, nameof(plainData)).IsNotNull(); Mandate.That(encoding, nameof(encoding)).IsNotNull(); PlainData = plainData; Verified = verified; Encoding = encoding; }
/// <summary> /// Returns a compiled view path based on the FQN of the view (embedded resource) /// </summary> /// <returns></returns> public static string Create(string resourcePathWithAssembly) { Mandate.ParameterNotNullOrEmpty(resourcePathWithAssembly, "resourcePathWithAssembly"); Mandate.That <FormatException>(resourcePathWithAssembly.Contains(',')); var parts = resourcePathWithAssembly.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); return(Create(parts[0], parts[1])); }
/// <summary> /// Returns a full virtual path for the code delegate id /// </summary> /// <param name="id"></param> /// <param name="extension"></param> /// <returns></returns> internal static string CreateFullPath(string id, string extension) { Mandate.That <FormatException>(!extension.StartsWith(".")); if (!id.StartsWith(NamePrefix)) { throw new NotSupportedException("The id referenced is an invalid format"); } return(string.Format("~" + PathPrefix + "{0}.{1}", id, extension)); }
/// <summary> /// Gets the media parameters. /// </summary> /// <param name="EntitySchemaToDocumentTypeEditorModel">The media id.</param> /// <returns></returns> public JsonResult GetMediaParameters(HiveId mediaId) { string path = BackOfficeRequestContext.RoutingEngine.GetUrl(mediaId); Mandate.That <NullReferenceException>(!string.IsNullOrEmpty(path)); IEnumerable <object> viewParams = Enumerable.Empty <object>(); var ext = path.Split('.').LastOrDefault().ToLower(); object view; //first look for custom view using (var uow = BackOfficeRequestContext .Application .Hive.OpenReader <IFileStore>(new Uri("storage://templates"))) { var id = new HiveId(new Uri("storage://templates"), "", new HiveIdValue(string.Format("/MediaTemplates/{0}.cshtml", ext))); var customView = uow.Repositories.Get <File>(id); if (customView != null) { view = BuildManager.CreateInstanceFromVirtualPath(customView.RootRelativePath, typeof(object)); } } try { view = BuildManager.CreateInstanceFromVirtualPath( EmbeddedViewPath.GetFullPath(EmbeddedViewPath.Create( string.Format("Umbraco.Cms.Web.PropertyEditors.RichTextBox.TinyMCE.Views.InsertMedia.Types.{0}.cshtml, Umbraco.Cms.Web.PropertyEditors", ext))) , typeof(object)); } catch (TypeLoadException e) { view = BuildManager.CreateInstanceFromVirtualPath( EmbeddedViewPath.GetFullPath(EmbeddedViewPath.Create( "Umbraco.Cms.Web.PropertyEditors.RichTextBox.TinyMCE.Views.InsertMedia.Types.default.cshtml, Umbraco.Cms.Web.PropertyEditors")) , typeof(object)); } if (view != null) { viewParams = view.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(x => new { name = x.Name }); } return(new CustomJsonResult(new { viewParams }.ToJsonString)); }
/// <summary> /// Does the clearing of the collection /// </summary> /// <param name="collection"></param> protected virtual void PerformClear(object collection) { if (_clearMethod == null) { _clearMethod = collection.GetType().GetMethod("Clear"); Mandate.That(_clearMethod != null, x => new NotSupportedException("Cannot modify a non mutable IEnumerable type")); } _clearMethod.Invoke(collection, null); }
/// <summary> /// Does the adding of an item to the collection /// </summary> /// <param name="collection"></param> /// <param name="item"></param> protected virtual void PerformAddItem(object collection, object item) { if (_addMethod == null) { _addMethod = collection.GetType().GetMethod("Add"); Mandate.That(_addMethod != null, x => new NotSupportedException("Cannot modify a non mutable IEnumerable type")); } _addMethod.Invoke(collection, new[] { item }); }
public static SecureString AppendString(this SecureString s, string src) { Mandate.That(src, nameof(src)).IsNotNullOrEmpty(); foreach (var c in src.ToCharArray()) { s.AppendChar(c); } return(s); }
/// <summary> /// Gets an <see cref="IProfile"/> for the current BackOffice User. /// </summary> /// <remarks> /// Requests the current HttpContext, so this method will only work in a web context. /// </remarks> /// <returns><see cref="IProfile"/> containing the Name and Id of the logged in BackOffice User</returns> public IProfile GetCurrentBackOfficeUser() { var context = HttpContext.Current; Mandate.That <Exception>(context != null); var wrapper = new HttpContextWrapper(context); return(GetCurrentBackOfficeUser(wrapper)); }
public PublicAccessService(IHiveManager hive, IMembershipService <Member> membersMembershipService, IFrameworkContext framework) { Mandate.That <NullReferenceException>(hive != null); Mandate.That <NullReferenceException>(membersMembershipService != null); _hive = hive; _members = membersMembershipService; _framework = framework; }
/// <summary> /// Cloning ctor /// </summary> private PublicKeyEncryptionOnion(PublicKeyEncryptionOnion onion) { Mandate.That(onion, nameof(onion)).IsNotNull(); SymmetricEncryptedData = onion.SymmetricEncryptedData; AsymmetricEncryptedKey = onion.AsymmetricEncryptedKey; SymmetricAlgorithmIV = onion.SymmetricAlgorithmIV; AsymmetricThumbprint = onion.AsymmetricThumbprint; InnerOnion = onion.InnerOnion; }
public PermissionsService(IHiveManager hive, IEnumerable <Lazy <Permission, PermissionMetadata> > permissions, IMembershipService <User> usersMembershipService) { Mandate.That <NullReferenceException>(hive != null); Mandate.That <NullReferenceException>(permissions != null); _hive = hive; _permissions = permissions; _users = usersMembershipService; }