public void Set_Value_Type()
 {
     for (int i = 0; i < 30; i++)
     {
         subject.Set <int>(i);
     }
 }
Beispiel #2
0
        public void Should_Set_ReferenceType_Property()
        {
            var item = new Tuple <string, int>("test", 3);

            subject.Set <Tuple <string, int> >(item);

            var actual = subject.Get <Tuple <string, int> >();

            Assert.Same(item, actual);
        }
		/// <summary>
		/// This method is called just before a node is created by the repository.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="properties">The new properties of the node.</param>
		protected override void DoBeforeCreate(IMansionContext context, IPropertyBag properties)
		{
			base.DoBeforeCreate(context, properties);

			// make sure the idenitifier is lowwercase
			var identifier = properties.Get<string>(context, "identifier").Trim().ToLower();
			properties.Set("identifier", identifier);

			// make sure there is a name
			var name = properties.Get(context, "name", identifier).Trim().ToLower();
			properties.Set("name", name);
		}
		/// <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>
		/// 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>
		/// 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");

			// set the pointer
			properties.Set("id", dbRecord.GetInt32(idIndex));
		}
		/// <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="record"> </param>
		/// <param name="properties">The updated properties of the node.</param>
		protected override void DoBeforeUpdate(IMansionContext context, Record record, IPropertyBag properties)
		{
			base.DoBeforeUpdate(context, record, properties);

			// check if the identifier was updated
			string identifier;
			if (!properties.TryGet(context, "identifier", out identifier))
				return;
			identifier = identifier.Trim().ToLower();
			properties.Set("identifier", identifier);

			// only update the name with the identifier if the previous name was also derived from the identifier
			if (record.Get(context, "name", string.Empty).Equals(record.Get(context, "identifier", string.Empty)))
			{
				var name = properties.Get(context, "name", identifier).Trim().ToLower();
				properties.Set("name", name);
			}
		}
		/// <summary>
		/// Prepares an insert query.
		/// </summary>
		/// <param name="context"></param>
		/// <param name="connection">The connection.</param>
		/// <param name="transaction">The transaction.</param>
		/// <param name="parent"></param>
		/// <param name="properties"></param>
		/// <returns></returns>
		public void Prepare(IMansionContext context, SqlConnection connection, SqlTransaction transaction, NodePointer parent, IPropertyBag properties)
		{
			// validate arguments
			if (connection == null)
				throw new ArgumentNullException("connection");
			if (transaction == null)
				throw new ArgumentNullException("transaction");
			if (parent == null)
				throw new ArgumentNullException("parent");
			if (properties == null)
				throw new ArgumentNullException("properties");

			// get the values
			var name = properties.Get<string>(context, "name", null);
			if (string.IsNullOrWhiteSpace(name))
				throw new InvalidOperationException("The node must have a name");
			var typeName = properties.Get<string>(context, "type", null);
			if (string.IsNullOrWhiteSpace(typeName))
				throw new InvalidOperationException("The node must have a type");

			// retrieve the type
			var type = typeService.Load(context, typeName);

			// get the schema of the root type
			var schema = Resolver.Resolve(context, type);

			// set the full text property
			SqlServerUtilities.PopulateFullTextColumn(context, type, properties, properties);

			// create the new pointer
			name = NodePointer.MakeSafeName(name);
			var newPointer = NodePointer.Parse(string.Join(NodePointer.PointerSeparator, new[] {parent.PointerString, 0.ToString(CultureInfo.InvariantCulture)}), string.Join(NodePointer.StructureSeparator, new[] {parent.StructureString, type.Name}), string.Join(NodePointer.PathSeparator, new[] {parent.PathString, name}));
			properties.Set("_newPointer", newPointer);

			// create the commands
			command = connection.CreateCommand();
			command.CommandType = CommandType.Text;
			command.Transaction = transaction;

			// prepare the query
			var queryBuilder = new ModificationQueryBuilder(command);

			// loop through all the tables in the schema and let them prepare for insert
			foreach (var table in schema.Tables)
				table.ToInsertStatement(context, queryBuilder, properties);

			// finish the complete insert statement
			queryBuilder.AppendQuery("SELECT @ScopeIdentity");

			// set the command text
			command.CommandText = queryBuilder.ToStatement();
		}
		/// <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)
		{
			// set all the column values as properties
			foreach (var ordinals in dbRecord.GetUnreadOrdinals())
			{
				// if the column is empty remove the value from the properties, otherwise set the value from the column
				if (dbRecord.IsDBNull(ordinals))
				{
					object obj;
					properties.TryGetAndRemove(context, dbRecord.GetName(ordinals), out obj);
				}
				else
					properties.Set(dbRecord.GetName(ordinals), dbRecord.GetValue(ordinals));
			}
		}
		/// <summary>
		/// Creates a new node in this repository.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="parent">The parent node.</param>
		/// <param name="newProperties">The properties of the node which to create.</param>
		/// <returns>Returns the created nodes.</returns>
		public Node CreateNode(IMansionContext context, Node parent, IPropertyBag newProperties)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (parent == null)
				throw new ArgumentNullException("parent");
			if (newProperties == null)
				throw new ArgumentNullException("newProperties");
			CheckDisposed();

			// if no allowedRoleGuids are specified, copy the parens
			if (!newProperties.Contains("allowedRoleGuids"))
				newProperties.Set("allowedRoleGuids", parent.Get(context, "allowedRoleGuids", string.Empty));

			// invoke template method
			return DoCreateNode(context, parent, newProperties);
		}
        /// <summary>
        /// Removes a tag name from the <paramref name="properties"/>.
        /// </summary>
        /// <param name="context">The <see cref="IMansionContext"/>.</param>
        /// <param name="properties">The properties containing the current tag names.</param>
        /// <param name="tagName">The name of the tag which to remove.</param>
        public static void RemoveTagName(IMansionContext context, IPropertyBag properties, string tagName)
        {
            // validate arguments
            if (context == null)
                throw new ArgumentNullException("context");
            if (properties == null)
                throw new ArgumentNullException("properties");
            tagName = Normalize(tagName);
            if (string.IsNullOrEmpty(tagName))
                throw new ArgumentNullException("tagName");

            // get the current tag names
            var tagNames = properties.Get(context, "tags", string.Empty).Split(new[] {','}).Select(Normalize).Distinct().ToList();

            // remove the tag
            tagNames.Remove(tagName);

            // set the new tag names
            properties.Set("tags", string.Join(", ", tagNames));
        }
		/// <summary>
		/// Loads the settings from the app.config/web.config.
		/// </summary>
		/// <param name="applicationSettings">The <see cref="IPropertyBag"/> containing the application settings.</param>
		private static void LoadSettingsFromApplicationConfiguration(IPropertyBag applicationSettings)
		{
			// get all the configuration keys
			foreach (var key in ConfigurationManager.AppSettings.AllKeys)
				applicationSettings.Set(key, ConfigurationManager.AppSettings[key]);
		}
        internal static void AddIgnoreUntilReason(this IPropertyBag properties, DateTimeOffset untilDate, string reason)
        {
            string skipReason = string.Format("Ignoring until {0}. {1}", untilDate.ToString("u"), reason);

            properties.Set(PropertyNames.SkipReason, skipReason);
        }
		/// <summary>
		/// Maps the given <paramref name="property"/> to <paramref name="target"/>.
		/// </summary>
		/// <param name="property">The <see cref="JProperty"/>.</param>
		/// <param name="target">The <see cref="IPropertyBag"/>.</param>
		public static void Map(JProperty property, IPropertyBag target)
		{
			// validate arguments
			if (property == null)
				throw new ArgumentNullException("property");
			if (target == null)
				throw new ArgumentNullException("target");

			// check for null
			if (property.Value == null)
				return;

			// get the correct type value
			switch (property.Value.Type)
			{
				case JTokenType.Boolean:
				{
					target.Set(property.Name, property.Value.Value<bool>());
				}
					break;
				case JTokenType.Date:
				{
					target.Set(property.Name, property.Value.Value<DateTime>());
				}
					break;
				case JTokenType.Float:
				{
					target.Set(property.Name, property.Value.Value<float>());
				}
					break;
				case JTokenType.Guid:
				{
					target.Set(property.Name, property.Value.Value<Guid>());
				}
					break;
				case JTokenType.Integer:
				{
					target.Set(property.Name, property.Value.Value<int>());
				}
					break;
				case JTokenType.Null:
				{
					// do not map
				}
					break;
				case JTokenType.String:
				{
					target.Set(property.Name, property.Value.Value<string>());
				}
					break;
				case JTokenType.TimeSpan:
				{
					target.Set(property.Name, property.Value.Value<TimeSpan>());
				}
					break;
				case JTokenType.Uri:
				{
					target.Set(property.Name, property.Value.Value<Uri>());
				}
					break;
				default:
					throw new NotSupportedException(string.Format("Can not map property '{0}' of type '{1}' with value '{2}'", property.Name, property.Type, property.Value));
			}
		}
		/// <summary>
		/// Routes the request to the specified controller action, if the controller action is not specified the the request is routed to the 404 controller.
		/// </summary>
		/// <param name="context">The <see cref="MansionContext"/>.</param>
		/// <param name="route">The <see cref="IPropertyBag"/> containing the route.</param>
		/// <param name="areaName">The name of the area in which the controller lives.</param>
		/// <param name="controllerName">The name of the controller.</param>
		/// <param name="actionName">The name of the action which to invoke.</param>
		private void RouteToControllerAction(IMansionContext context, IPropertyBag route, string areaName, string controllerName, string actionName)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (route == null)
				throw new ArgumentNullException("route");
			if (areaName == null)
				throw new ArgumentNullException("areaName");
			if (string.IsNullOrEmpty(controllerName))
				throw new ArgumentNullException("controllerName");
			if (string.IsNullOrEmpty(actionName))
				throw new ArgumentNullException("actionName");

			// set the route
			route.Set("area", areaName);
			route.Set("controller", controllerName);
			route.Set("action", actionName);

			// get the paths
			var scriptResourcePath = applicationResourceService.ParsePath(context, new PropertyBag
			                                                                       {
			                                                                       	{"path", areaName + "/" + controllerName + "Controller.xinclude"},
			                                                                       	{"overridable", true}
			                                                                       });
			var templateResourcePath = applicationResourceService.ParsePath(context, new PropertyBag
			                                                                         {
			                                                                         	{"path", areaName + "/" + controllerName + "Controller.tpl"},
			                                                                         	{"overridable", true}
			                                                                         });

			// get the resources and check if controller does not exist
			IEnumerable<IResource> scriptResources;
			if (!applicationResourceService.TryGet(context, scriptResourcePath, out scriptResources))
			{
				// controller script not found
				RouteTo404Controller(context, route, string.Empty, "404", "NotFound");
				return;
			}
			IEnumerable<IResource> templateResources;
			applicationResourceService.TryGet(context, templateResourcePath, out templateResources);

			// open the resources
			using (tagScriptService.Open(context, scriptResources))
			using (templateService.Open(context, templateResources))
			{
				// check if action does not exist
				IScript action;
				if (!context.ProcedureStack.TryPeek<IScript>("Handle" + actionName, out action))
				{
					// check if the default action does not exists
					if (!context.ProcedureStack.TryPeek<IScript>("HandleDefault", out action))
					{
						// action and default action not found
						RouteTo404Controller(context, route, string.Empty, "404", "NotFound");
						return;
					}
				}

				// invoke the InitializeController event
				using (context.Stack.Push("Arguments", new PropertyBag()))
				{
					foreach (var handler in context.EventHandlerStack.PeekAll("InitializeController"))
						handler.Execute(context);
				}

				// invoke the action on the controller procedure
				using (context.Stack.Push("Arguments", new PropertyBag()))
					action.Execute(context);
			}
		}
        /// <summary>
        /// Manages the tags.
        /// </summary>
        /// <param name="context">The <see cref="IMansionContext"/>.</param>
        /// <param name="properties">The new properties.</param>
        public static void ToGuids(IMansionContext context, IPropertyBag properties)
        {
            // validate arguments
            if (context == null)
                throw new ArgumentNullException("context");
            if (properties == null)
                throw new ArgumentNullException("properties");

            // get the tag name string
            string tagNameString;
            if (!properties.TryGet(context, "_tags", out tagNameString))
                return;

            // normalize the tag names
            var tagNames = NormalizeNames(tagNameString).ToList();

            // retrieve the tag index node
            var tagIndexNode = RetrieveTagIndexNode(context);

            // loop over all the tag names
            var tagNodes = tagNames.Select(tagName => RetrieveTagNode(context, tagIndexNode, tagName));

            // set the new tag guids
            properties.Set("tagGuids", string.Join(",", tagNodes.Select(x => x.PermanentId)));
            properties.Remove("_tags");
        }
		/// <summary>
		/// Maps the properties from <paramref name="source"/> to <paramref name="target"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="source">The <see cref="Hit"/>.</param>
		/// <param name="property">The <see cref="JProperty"/>.</param>
		/// <param name="target">The <see cref="IPropertyBag"/>.</param>
		protected override void DoMap(IMansionContext context, Hit source, JProperty property, IPropertyBag target)
		{
			// null check
			if (property.Value == null)
				return;

			// expect an array
			var values = (JArray) property.Value;

			target.Set(property.Name, string.Join(",", values.Select(value => value.Value<string>()).ToArray()));
		}
 /// <summary>
 /// This method is called just before a node is created by the repository.
 /// </summary>
 /// <param name="context">The <see cref="IMansionContext"/>.</param>
 /// <param name="parent">The parent node to which the new child will be added.</param>
 /// <param name="newProperties">The new properties of the node.</param>
 protected override void DoBeforeCreate(IMansionContext context, Node parent, IPropertyBag newProperties)
 {
     // make sure the name is normalized
     newProperties.Set("name", TagUtilities.Normalize(newProperties.Get(context, "name", string.Empty)));
 }