/// <summary> /// </summary> /// <param name="context"></param> protected override void DoExecute(IMansionContext context) { // get the properties var sectionProperties = GetAttributes(context); // get the section name string sectionName; if (!sectionProperties.TryGetAndRemove(context, "name", out sectionName)) throw new InvalidOperationException("The attribute section name is required"); // get the target field string targetField; sectionProperties.TryGetAndRemove(context, "targetField", out targetField); // push the section properties to the stack using (context.Stack.Push("Section", sectionProperties)) { // render the section if (string.IsNullOrWhiteSpace(targetField)) { using (templateService.Render(context, sectionName)) ExecuteChildTags(context); } else { using (templateService.Render(context, sectionName, targetField)) ExecuteChildTags(context); } } }
/// <summary> /// Creates a filled nodeset. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="properties"></param> /// <param name="records"></param> public RecordSet(IMansionContext context, IPropertyBag properties, IEnumerable<Record> records) : base(properties) { // validate arguments if (records == null) throw new ArgumentNullException("records"); if (properties == null) throw new ArgumentNullException("properties"); // set values foreach (var node in records) RowCollection.Add(node); Set("count", RowCollection.Count); // check for paging var totalRowCount = properties.Get(context, "totalCount", -1); var pageNumber = properties.Get(context, "pageNumber", -1); var rowsPerPage = properties.Get(context, "pageSize", -1); if (totalRowCount != -1 && pageNumber != -1 && rowsPerPage != -1) SetPaging(totalRowCount, pageNumber, rowsPerPage); // check for sort string sortString; if (properties.TryGet(context, "sort", out sortString)) { foreach (var sort in Collections.Sort.Parse(sortString)) AddSort(sort); } }
/// <summary> /// Executes this tag. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> protected override void DoExecute(IMansionContext context) { // get the web context var webContext = context.Cast<IMansionWebContext>(); // get the column Column column; if (!webContext.TryPeekControl(out column)) throw new InvalidOperationException(string.Format("'{0}' must be added to a '{1}'", GetType(), typeof (Column))); // get the property names on which to sort var propertyName = GetRequiredAttribute<string>(context, "on"); // create the filter var sort = new ColumnSort { PropertyName = propertyName }; // allow facets using (webContext.ControlStack.Push(sort)) ExecuteChildTags(webContext); // set the sort to the column column.Sort = sort; }
/// <summary> /// Processes the <paramref name="parameters"/> and turn them into <paramref name="query"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="parameters">The parameters which to process.</param> /// <param name="query">The <see cref="Query"/> in which to set the parameters.</param> protected override void DoProcess(IMansionContext context, IPropertyBag parameters, Query query) { var counter = 0; // check for id, guid or pointer int id; if (parameters.TryGetAndRemove(context, "id", out id)) { query.Add(new IsPropertyEqualSpecification("id", id)); counter++; } string guids; if (parameters.TryGetAndRemove(context, "guid", out guids) && !string.IsNullOrEmpty(guids)) { // split the value var values = guids.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); query.Add(new IsPropertyInSpecification("guid", values)); counter++; } NodePointer pointer; if (parameters.TryGetAndRemove(context, "pointer", out pointer)) { query.Add(new IsPropertyEqualSpecification("id", pointer.Id)); counter++; } // check for ambigous parameters if (counter > 1) throw new InvalidOperationException("Detected an ambigious id parmeters. Remove either id, guid or pointer."); }
/// <summary> /// This method is called just after a node is updated by the repository. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="record"> </param> /// <param name="properties">The properties which were set to the updated <paramref name="record"/>.</param> protected override void DoAfterUpdate(IMansionContext context, Record record, IPropertyBag properties) { // get the propagate property names var propagatePropertyNames = properties.Names.Where(x => x.StartsWith(PropagatePrefix, StringComparison.OrdinalIgnoreCase)); // get the property names who's value is true var propagatedNowProperties = propagatePropertyNames.Where(x => properties.Get(context, x, false)); // loop over all the updated properties and propagated properties foreach (var propagatePropertyName in propagatedNowProperties) { // get the name of the property being propagated var propagatedPropertyName = propagatePropertyName.Substring(PropagatePrefix.Length); // get the propagated property value var propagatedPropertyValue = properties.Get<object>(context, propagatedPropertyName); // retrieve all the children nodes and update them all foreach (var childNode in context.Repository.RetrieveNodeset(context, new PropertyBag { {"parentSource", record}, {"depth", "any"} }).Nodes) { context.Repository.UpdateNode(context, childNode, new PropertyBag { {propagatedPropertyName, propagatedPropertyValue} }); } } }
/// <summary> /// Maps the given <paramref name="dbRecord"/> to <paramref name="properties"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="dbRecord">The <see cref="DbRecord"/> which to map.</param> /// <param name="properties">The <see cref="IPropertyBag"/> in which to store the mapped result.</param> protected override void DoMap(IMansionContext context, DbRecord dbRecord, IPropertyBag properties) { // field indices var idIndex = dbRecord.GetOrdinal("id"); var parentPointerIndex = dbRecord.GetOrdinal("parentPointer"); var nameIndex = dbRecord.GetOrdinal("name"); var parentPathIndex = dbRecord.GetOrdinal("parentPath"); var typeIndex = dbRecord.GetOrdinal("type"); var parentStructureIndex = dbRecord.GetOrdinal("parentStructure"); // assemble the node pointer var pointer = (dbRecord.IsDBNull(parentPointerIndex) ? string.Empty : dbRecord.GetString(parentPointerIndex) + NodePointer.PointerSeparator) + dbRecord.GetInt32(idIndex); var structure = (dbRecord.IsDBNull(parentStructureIndex) ? string.Empty : dbRecord.GetString(parentStructureIndex) + NodePointer.StructureSeparator) + dbRecord.GetString(typeIndex); var path = (dbRecord.IsDBNull(parentPathIndex) ? string.Empty : dbRecord.GetString(parentPathIndex) + NodePointer.PathSeparator) + dbRecord.GetString(nameIndex); var nodePointer = NodePointer.Parse(pointer, structure, path); // set the pointer properties.Set("pointer", nodePointer); properties.Set("path", nodePointer.PathString); properties.Set("structure", nodePointer.StructureString); properties.Set("depth", nodePointer.Depth); properties.Set("name", nodePointer.Name); properties.Set("type", nodePointer.Type); if (nodePointer.HasParent) { properties.Set("parentPointer", nodePointer.Parent); properties.Set("parentId", nodePointer.Parent.Id); } }
/// <summary> /// This method is called just before a node is updated by the repository. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="node">The node which will be modified.</param> /// <param name="modifiedProperties">The updated properties of the node.</param> protected override void DoBeforeUpdate(IMansionContext context, Node node, IPropertyBag modifiedProperties) { // if the name has not changed we are not interested string newName; if (!modifiedProperties.TryGet(context, "name", out newName)) return; // if the name has not changed after normalization we are not interested newName = TagUtilities.Normalize(newName); if (node.Pointer.Name.Equals(newName)) { modifiedProperties.Remove("name"); return; } modifiedProperties.Set("name", newName); // if the tag is renamed to another already existing tag, move all content to that existing tag and delete this one Node existingTag; var tagIndexNode = TagUtilities.RetrieveTagIndexNode(context); if (TagUtilities.TryRetrieveTagNode(context, tagIndexNode, newName, out existingTag)) { // TODO: move all content to the existing tag // TODO: delete this tag } }
/// <summary> /// Constructs an section. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="properties">The descriptor of this section.</param> /// <param name="expression">The expressio of this section.</param> public Section(IMansionContext context, IPropertyBag properties, IExpressionScript expression) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (properties == null) throw new ArgumentNullException("properties"); if (expression == null) throw new ArgumentNullException("expression"); // set values Properties = properties; Expression = expression; Id = Guid.NewGuid().ToString(); Name = Properties.Get<string>(context, "name"); ShouldBeRenderedOnce = !Properties.Get(context, "repeatable", true); TargetField = Properties.Get(context, "field", Name); // check if there is a requires property string requiresExpressionString; if (Properties.TryGet(context, "requires", out requiresExpressionString)) { // assemble the expression var expressionService = context.Nucleus.ResolveSingle<IExpressionScriptService>(); var requiresExpression = expressionService.Parse(context, new LiteralResource(requiresExpressionString)); // execute the expression areRequirementsSatisfied = requiresExpression.Execute<bool>; } else areRequirementsSatisfied = mansionContext => true; }
/// <summary> /// </summary> /// <param name="context"></param> protected override void DoExecute(IMansionContext context) { // validate arguments if (context == null) throw new ArgumentNullException("context"); // get the attributes var attributes = GetAttributes(context); string extension; if (!attributes.TryGet(context, "extension", out extension)) attributes.Set("extension", TemplateServiceConstants.DefaultTemplateExtension); // get the resource paths var resourcePath = applicationResourceService.ParsePath(context, attributes); // get the resources IEnumerable<IResource> resources; if (GetAttribute(context, "checkExists", true)) resources = applicationResourceService.Get(context, resourcePath); else applicationResourceService.TryGet(context, resourcePath, out resources); // open the templates and executes child tags); using (templateService.Open(context, resources)) ExecuteChildTags(context); }
/// <summary> /// Creates an instance of <see cref="ChildType"/> from <paramref name="descriptor"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="descriptor">The <see cref="ChildTypeDescriptor"/>.</param> /// <param name="behavior">The <see cref="CmsBehavior"/>.</param> public static void Create(IMansionContext context, ChildTypeDescriptor descriptor, CmsBehavior behavior) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (descriptor == null) throw new ArgumentNullException("descriptor"); if (behavior == null) throw new ArgumentNullException("behavior"); // get the type var type = descriptor.Properties.Get<ITypeDefinition>(context, "type", null); var baseType = descriptor.Properties.Get<ITypeDefinition>(context, "baseType", null); if (type == null && baseType == null) throw new InvalidOperationException(string.Format("Invalid child type descriptor on type '{0}'. Specify either an type or a baseType.", descriptor.TypeDefinition.Name)); if (type != null && baseType != null) throw new InvalidOperationException(string.Format("Invalid child type descriptor on type '{0}'. Ambigious type detected. Specify either an type or a baseType.", descriptor.TypeDefinition.Name)); if (type != null) CreateChildType(context, descriptor, behavior, type); else { CreateChildType(context, descriptor, behavior, baseType); foreach (var inheritingType in baseType.GetInheritingTypes(context)) CreateChildType(context, descriptor, behavior, inheritingType); } }
/// <summary> /// </summary> /// <param name="context">The application context.</param> protected override void DoExecute(IMansionContext context) { // get all attributes var attributes = GetAttributes(context); // get the target attribute string target; if (!attributes.TryGetAndRemove(context, "target", out target) || string.IsNullOrEmpty(target)) throw new InvalidOperationException("The target attribute is manditory"); bool global; if (!attributes.TryGetAndRemove(context, "global", out global)) global = false; // get the result var results = Get(context, attributes); // push the node to the stack in the target dataspace using (context.Stack.Push(target, results, global)) { // check if the node was found if (results != null && results.RowCount > 0) ExecuteChildTags(context); else { // execute not found tag NotFoundTag notFoundTag; if (TryGetAlternativeChildTag(out notFoundTag)) notFoundTag.Execute(context); } } }
/// <summary> /// Prepares an insert query. /// </summary> /// <param name="context"></param> /// <param name="connection">The connection.</param> /// <param name="transaction">The transaction.</param> /// <param name="sourceNode"></param> /// <param name="targetParentNode"></param> /// <returns></returns> public void Prepare(IMansionContext context, SqlConnection connection, SqlTransaction transaction, Node sourceNode, Node targetParentNode) { // validate arguments if (connection == null) throw new ArgumentNullException("connection"); if (transaction == null) throw new ArgumentNullException("transaction"); if (sourceNode == null) throw new ArgumentNullException("sourceNode"); if (targetParentNode == null) throw new ArgumentNullException("targetParentNode"); // get the properties of the new node var newProperties = new PropertyBag(sourceNode); // if the target pointer is the same as the parent of the source node, generate a new name to distinguish between the two. if (sourceNode.Pointer.Parent == targetParentNode.Pointer) { // get the name of the node var name = sourceNode.Get<string>(context, "name"); // change the name to indicate the copied node newProperties.Set("name", name + CopyPostfix); } // create an insert query command = context.Nucleus.CreateInstance<InsertNodeCommand>(); command.Prepare(context, connection, transaction, targetParentNode.Pointer, newProperties); }
/// <summary> /// </summary> /// <param name="context"></param> protected override void DoExecute(IMansionContext context) { // get the attributes var attributes = GetAttributes(context); // get the XML output pipe var outputPipe = context.OutputPipe as JsonOutputPipe; if (outputPipe == null) throw new InvalidOperationException("No JSON output pipe found on thet stack. Open an JSON output pipe first."); // start the element outputPipe.JsonWriter.WriteStartObject(); // render the attributes foreach (var attribute in attributes) { outputPipe.JsonWriter.WritePropertyName(attribute.Key); outputPipe.JsonWriter.WriteValue(attribute.Value); } // render the children ExecuteChildTags(context); // finish the element outputPipe.JsonWriter.WriteEndObject(); }
/// <summary> /// Processes the <paramref name="parameters"/> and turn them into <paramref name="query"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="parameters">The parameters which to process.</param> /// <param name="query">The <see cref="Query"/> in which to set the parameters.</param> protected override void DoProcess(IMansionContext context, IPropertyBag parameters, Query query) { // check for search string where; if (parameters.TryGetAndRemove(context, "sqlWhere", out where) && !string.IsNullOrEmpty(where)) query.Add(new SqlWhereSpecification(where)); }
/// <summary> /// Performs a search using the specified <paramref name="query"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="query">The <see cref="Query"/> on which to search.</param> /// <returns>Returns the resulting <see cref="RecordSet"/>.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception> /// <exception cref="ConnectionException">Thrown if a error occurred while executing the search query.</exception> public RecordSet Search(IMansionContext context, Query query) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (query == null) throw new ArgumentNullException("query"); // find the root type for this query var rootType = query.TypeHints.FindCommonAncestor(context); // resolve the index definitions of this record var indexDefinitions = indexDefinitionResolver.Resolve(context, rootType); // determine the index which to use to perform the search var indexDefinitionTypeMappingPair = SelectBestIndexForQuery(rootType, query, indexDefinitions); // create a search descriptor var search = new SearchQuery(indexDefinitionTypeMappingPair.Item1, indexDefinitionTypeMappingPair.Item2); // map all the query components to the search descriptor foreach (var component in query.Components) converters.Elect(context, component).Map(context, query, component, search); // execute the query return Search(context, search); }
/// <summary> /// Verifies the root node exists. /// </summary> private void VerifyRootNodeExists(IMansionContext context, bool fix, StringBuilder reportBuilder) { // try to retrieve the root node var rootNode = repository.RetrieveSingleNode(context, new Query() .Add(new IsPropertyEqualSpecification("id", 1)) .Add(StatusSpecification.Is(NodeStatus.Any)) .Add(AllowedRolesSpecification.Any()) .Add(new StorageOnlyQueryComponent()) ); if (rootNode != null) reportBuilder.AppendLine("Succes: Root node was found"); else { if (fix) { repository.ExecuteWithoutTransaction(context, @"-- Insert root node SET IDENTITY_INSERT [dbo].[Nodes] ON; INSERT INTO [dbo].[Nodes] ([id],[name],[type],[depth]) VALUES ('1', 'Root', 'root', '1'); SET IDENTITY_INSERT [dbo].[Nodes] OFF;"); reportBuilder.AppendLine("Succes: created root node"); } else reportBuilder.AppendLine("Error: Root node was not found"); } }
/// <summary> /// Populates the fullText property. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="modifiedProperties">The modified <see cref="IPropertyBag"/>.</param> /// <param name="originalProperties">The original <see cref="IPropertyBag"/>.</param> /// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception> public void Populate(IMansionContext context, IPropertyBag modifiedProperties, IPropertyBag originalProperties) { //validate arguments if (context == null) throw new ArgumentNullException("context"); if (modifiedProperties == null) throw new ArgumentNullException("modifiedProperties"); if (originalProperties == null) throw new ArgumentNullException("originalProperties"); // get all the properties over which to loop var properties = Properties.Get<string>(context, "properties").Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(property => property.Trim()); // assemble the content var buffer = new StringBuilder(); foreach (var property in properties) { // get the content for the given property String content; if (!modifiedProperties.TryGet(context, property, out content)) { if (!originalProperties.TryGet(context, property, out content)) continue; } // strip the HTML content = content.StripHtml(); // add it to the buffer buffer.AppendLine(content); } // if there is full-text content, add it to the full-text property, otherwise set it to null modifiedProperties.Set("fullText", buffer.Length > 0 ? buffer.ToString() : null); }
/// <summary> /// </summary> /// <param name="context"></param> /// <param name="relativePath">The relative path to the resource which to include.</param> /// <returns></returns> public string Evaluate(IMansionContext context, string relativePath) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (string.IsNullOrEmpty(relativePath)) throw new ArgumentNullException("relativePath"); // get the resource var resourcePath = applicationResourceService.ParsePath(context, new PropertyBag { {"path", relativePath} }); // create the buffer var buffer = new StringBuilder(); // loop over all the resources foreach (var script in applicationResourceService.Get(context, resourcePath).Select(resource => expressionScriptService.Parse(context, resource))) { // execute the script and write the result back to the output pipe buffer.AppendLine(script.Execute<string>(context)); } return buffer.ToString(); }
/// <summary> /// Initializes the security for the specified <see cref="IMansionContext"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> public void InitializeSecurityContext(IMansionContext context) { // validate arguments if (context == null) throw new ArgumentNullException("context"); // set users context.SetFrontofficeUserState(InitializeFrontofficeUser(context)); context.SetBackofficeUserState(InitializeBackofficeUser(context)); // push the users to the stack var frontofficeUserProperties = new PropertyBag(context.FrontofficeUserState.Properties) { {"id", context.FrontofficeUserState.Id}, {"isAuthenticated", context.FrontofficeUserState.IsAuthenticated} }; var backofficeUserProperties = new PropertyBag(context.BackofficeUserState.Properties) { {"id", context.BackofficeUserState.Id}, {"isAuthenticated", context.BackofficeUserState.IsAuthenticated} }; context.Stack.Push("FrontofficeUser", frontofficeUserProperties, true).Dispose(); context.Stack.Push("BackofficeUser", backofficeUserProperties, true).Dispose(); context.Stack.Push("User", context.IsBackoffice ? backofficeUserProperties : frontofficeUserProperties, true).Dispose(); }
/// <summary> /// Opens a repository and pushes it to the stack. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <returns>Returns an <see cref="IDisposable"/> which cleans up the opened repository and the stack.</returns> public static IDisposable Open(IMansionContext context) { // validate arguments if (context == null) throw new ArgumentNullException("context"); // resolve the data storaget BaseStorageEngine storageEngine; if (!context.Nucleus.TryResolveSingle(out storageEngine)) throw new InvalidOperationException("There is no data storage engine configured within this application, please register a data store"); var disposableChain = new DisposableChain(); // create the repository IRepository repository = new OrchestratingRepository( context.Nucleus.ResolveSingle<BaseStorageEngine>(), context.Nucleus.Resolve<BaseQueryEngine>(), context.Nucleus.Resolve<BaseIndexEngine>() ); // decorate with listing capabilities repository = new ListeningRepositoryDecorator(repository, context.Nucleus.ResolveSingle<ITypeService>()); // decorate the caching capabilities repository = new CachingRepositoryDecorator(repository, context.Nucleus.ResolveSingle<ICachingService>()); // start the repository disposableChain.Add(repository); repository.Start(context); // push repository to the stack return disposableChain.Add(context.RepositoryStack.Push(repository)); }
/// <summary> /// Retrieves the tag index <see cref="Node"/>. Creates one when no exists. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <returns>Returns the <see cref="Node"/> representing the tag index.</returns> public static Node RetrieveTagIndexNode(IMansionContext context) { // validate arguments if (context == null) throw new ArgumentNullException("context"); // get the repository var repository = context.Repository; // retrieve the root node var rootNode = repository.RetrieveRootNode(context); // retrieve the tag index or create it var tagIndexNode = repository.RetrieveSingleNode(context, new PropertyBag { {"type", "TagIndex"}, {"parentSource", rootNode}, {"depth", "any"} }) ?? repository.CreateNode(context, rootNode, new PropertyBag { {"type", "TagIndex"}, {"name", "Tags"}, {"approved", true} }); return tagIndexNode; }
/// <summary> /// Generates an table sync statement for this table. /// </summary> /// <param name="context">The request context.</param> /// <param name="bulkContext"></param> /// <param name="records"></param> protected override void DoToSyncStatement(IMansionContext context, BulkOperationContext bulkContext, List<Record> records) { // start by clearing the table bulkContext.Add(command => { command.CommandType = CommandType.Text; command.CommandText = string.Format("TRUNCATE TABLE [{0}]", Name); }); // loop through all the properties foreach (var record in records) { // prepare the query var columnText = new StringBuilder(); var valueText = new StringBuilder(); // finish the query var currentRecord = record; bulkContext.Add(command => { // loop through all the columns foreach (var column in Columns) column.ToSyncStatement(context, command, currentRecord, columnText, valueText); // construct the command command.CommandType = CommandType.Text; command.CommandText = string.Format("INSERT INTO [{0}] ({1}) VALUES ({2});", Name, columnText.Trim(), valueText.Trim()); }); } }
/// <summary> /// Invokes a procedure and returns it output. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="procedureName">The name of the section which to render.</param> /// <param name="arguments">The arguments of the procedure.</param> /// <returns></returns> public string Evaluate(IMansionContext context, string procedureName, params object[] arguments) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (string.IsNullOrEmpty(procedureName)) throw new ArgumentNullException("procedureName"); if (arguments == null) throw new ArgumentNullException("arguments"); // get the procedure ScriptTag procedure; if (!context.ProcedureStack.TryPeek(procedureName, out procedure)) throw new InvalidOperationException(string.Format("No procedure found with name '{0}'", procedureName)); // assemble the arguments var procedureArguments = new PropertyBag(); for (var index = 0; index < arguments.Length; ++index) procedureArguments.Set(index.ToString(CultureInfo.InvariantCulture), arguments[index]); // render the control var buffer = new StringBuilder(); using (var pipe = new StringOutputPipe(buffer)) using (context.OutputPipeStack.Push(pipe)) using (context.Stack.Push("Arguments", procedureArguments)) procedure.Execute(context); // make sure the break procedure flag is cleared context.BreakTopMostProcedure = false; // return the buffer return buffer.ToString(); }
/// <summary> /// </summary> /// <param name="context"></param> protected override void DoExecute(IMansionContext context) { // get the XML output pipe var outputPipe = context.OutputPipe as JsonOutputPipe; if (outputPipe == null) throw new InvalidOperationException("No JSON output pipe found on thet stack. Open an JSON output pipe first."); var propertyName = GetAttribute<string>(context, "propertyName"); if (string.IsNullOrEmpty(propertyName)) throw new InvalidOperationException("The propertyName attribute is required."); object content; if (!TryGetAttribute(context, "value", out content)) { // push a memory pipe to the stack var buffer = new StringBuilder(); using (var pipe = new StringOutputPipe(buffer)) using (context.OutputPipeStack.Push(pipe)) ExecuteChildTags(context); content = buffer.ToString(); } // write the attribute outputPipe.JsonWriter.WritePropertyName(propertyName); outputPipe.JsonWriter.WriteValue(content); }
/// <summary> /// Executes this tag. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> protected override void DoExecute(IMansionContext context) { // get the web request var webRequest = context.Cast<IMansionWebContext>(); var outputPipe = (WebOutputPipe) context.OutputPipeStack.FirstOrDefault(x => x is WebOutputPipe); if (outputPipe == null) throw new InvalidOperationException("No web output pipe was found on thet stack."); // set the properties of the output pipe outputPipe.Response.ContentType = GetAttribute(webRequest, "contentType", "text/html"); outputPipe.Encoding = GetAttribute(webRequest, "encoding", Encoding.UTF8); outputPipe.Response.CacheSettings.OutputCacheEnabled = GetAttribute(webRequest, "cache", false); // set the file name outputPipe.Response.Headers.Add("Content-Disposition", "attachment; filename=" + GetRequiredAttribute<string>(context, "fileName")); // optionally set size var sizeInBytes = GetAttribute(context, "fileSize", -1); if (sizeInBytes != -1) outputPipe.Response.Headers.Add("Content-Length", sizeInBytes.ToString(CultureInfo.InvariantCulture)); // push the repsonse pipe to the stack and execute child tags) using (webRequest.OutputPipeStack.Push(outputPipe)) ExecuteChildTags(webRequest); }
/// <summary> /// Tries to revive the user based on the revival properties. /// </summary> /// <param name="context">The security context.</param> /// <param name="revivalProperties">The revival properties.</param> /// <returns>Returns the revived <see cref="UserState"/> or null.</returns> public override UserState ReviveUser(IMansionContext context, IPropertyBag revivalProperties) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (revivalProperties == null) throw new ArgumentNullException("revivalProperties"); // get the id of the from the revival properties Guid id; if (!revivalProperties.TryGet(context, "id", out id)) return null; // retrieve the user by guid var userNode = context.Repository.RetrieveSingleNode(context, new PropertyBag { {"baseType", "User"}, {"guid", id}, {"status", "any"}, {"bypassAuthorization", true}, {"cache", false}, {StorageOnlyQueryComponent.PropertyKey, true} }); if (userNode == null) return null; // create and return the user state return CreateUserState(context, userNode); }
/// <summary> /// Writes <paramref name="values"/> to the output. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="values">The <see cref="IPropertyBag"/> containing the values which to write.</param> public void Write(IMansionContext context, IPropertyBag values) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (values == null) throw new ArgumentNullException("values"); CheckDisposed(); // write out the values for (var index = 0; index < format.ColumnProperties.Length; index++) { // write out the current value when there is one string value; if (values.TryGet(context, format.ColumnProperties[index], out value)) { outputPipe.Writer.Write(format.TextQualifier); outputPipe.Writer.Write(value); outputPipe.Writer.Write(format.TextQualifier); } // write out the column or row delimitor outputPipe.Writer.Write(index == (format.ColumnProperties.Length - 1) ? format.RowDelimitor : format.ColumnDelimitor); } }
/// <summary> /// Generates a random passsword. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <returns>Returns the generated password.</returns> public string Evaluate(IMansionContext context) { // validate arguments if (context == null) throw new ArgumentNullException("context"); var chars = new char[8]; var randomBytes = new byte[1]; using (var rngCsp = new RNGCryptoServiceProvider()) { for (var i = 0; i < 8; i++) { // get a random number within the allowed character range do { rngCsp.GetBytes(randomBytes); } while (!(randomBytes[0] >= 0 && randomBytes[0] < AllowedChars.Length)); // get the character chars[i] = AllowedChars[randomBytes[0]]; } } return new string(chars); }
/// <summary> /// Initializes the application. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> protected override void DoInitialize(IMansionContext context) { // open the repository SqlServerRepository repository; if (!context.Nucleus.TryResolveSingle(out repository)) return; // loop over all the registered types and gather their schema var schemaBuffer = new StringBuilder(); foreach (var type in typeService.LoadAll(context).OrderBy(type => { RootTypeTableDescriptor rootTypeTableDescriptor; return type.TryGetDescriptor(out rootTypeTableDescriptor) ? 0 : 1; })) { // get the schema if available SchemaDescriptor schemaDescriptor; if (!type.TryGetDescriptor(out schemaDescriptor)) continue; // append the schema to the buffer schemaBuffer.Append(schemaDescriptor.GetSchema(context)).AppendLine("; "); } // execute the schema creation repository.ExecuteWithoutTransaction(context, schemaBuffer.ToString()); }
/// <summary> /// Retrieves the taxonomy <see cref="Node"/>. /// </summary> /// <remarks>If the taxonomy node does not exist it will be created.</remarks> /// <param name="repository">The <see cref="IRepository"/> from which to retrieve the root node.</param> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <returns>Returns the taxonomy <see cref="Node"/>.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="repository"/> or <paramref name="context"/> is null.</exception> public static Node RetrieveTaxonomyNode(this IRepository repository, IMansionContext context) { // validate arguments if (repository == null) throw new ArgumentNullException("repository"); if (context == null) throw new ArgumentNullException("context"); // first retrieve the root node var contentIndexRootNode = repository.RetrieveContentIndexRootNode(context); // retrieve the node or create it when it does not exist return repository.RetrieveSingleNode(context, new PropertyBag { {"parentSource", contentIndexRootNode}, {"type", "Taxonomy"}, {"bypassAuthorization", true}, {StorageOnlyQueryComponent.PropertyKey, true} }) ?? repository.CreateNode(context, contentIndexRootNode, new PropertyBag { {"type", "Taxonomy"}, {"name", "Taxonomy"}, {"approved", true} }); }