示例#1
0
		/// <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;
		}
 public void Get_Value_Type()
 {
     for (int i = 0; i < 30; i++)
     {
         subject.Get <int>();
     }
 }
        /// <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}
                                                                      });
                }
            }
        }
示例#4
0
		/// <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>
		/// Authenticates the user.
		/// </summary>
		/// <param name="context">The security context.</param>
		/// <param name="parameters">The parameters used for authentication.</param>
		/// <returns>Returns the <see cref="AuthenticationResult"/>.</returns>
		protected override AuthenticationResult DoAuthenticate(IMansionContext context, IPropertyBag parameters)
		{
			// get the credentials
			var username = parameters.Get<string>(context, "username");
			if (string.IsNullOrEmpty(username))
			{
				return AuthenticationResult.Failed(new PropertyBag
				                                   {
				                                   	{AuthenticationResult.ReasonPropertyName, AuthenticationResult.NoUsernameSpecifiedReason}
				                                   });
			}
			var password = parameters.Get<string>(context, "password");
			if (string.IsNullOrEmpty(password))
			{
				return AuthenticationResult.Failed(new PropertyBag
				                                   {
				                                   	{AuthenticationResult.ReasonPropertyName, AuthenticationResult.NoPasswordSpecifiedReason}
				                                   });
			}

			// check for incorrect credentials
			if (!username.Equals("System") || !password.Equals("Premotion"))
			{
				return AuthenticationResult.Failed(new PropertyBag
				                                   {
				                                   	{AuthenticationResult.ReasonPropertyName, AuthenticationResult.InvalidCredentialsReason}
				                                   });
			}

			// return the user
			return AuthenticationResult.Success(new UserState(Guid.NewGuid(), this), new PropertyBag());
		}
		/// <summary>
		/// Maps the properties of the row.
		/// </summary>
		/// <param name="context">The <see cref="IMansionWebContext"/>.</param>
		/// <param name="row">The row which to map.</param>
		/// <returns>Returns the mapped result.</returns>
		protected override IPropertyBag DoMapRowProperties(IMansionWebContext context, IPropertyBag row)
		{
			return new PropertyBag
			       {
			       	{"value", row.Get(context, valueProperty, string.Empty)},
			       	{"label", row.Get(context, labelProperty, string.Empty)}
			       };
		}
示例#7
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>
		/// Interprets the input..
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="input">The input which to interpret.</param>
		/// <returns>Returns the interpreted result.</returns>
		protected override IResourcePath DoInterpret(IMansionContext context, IPropertyBag input)
		{
			// get the path
			var path = input.Get<string>(context, "path");
			if (string.IsNullOrEmpty(path))
				throw new InvalidOperationException("The path should not be empty");
			var overridable = input.Get(context, "overridable", true);

			// return the resource path
			return new RelativeResourcePath(path, overridable);
		}
		/// <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>
		/// 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>
		/// Initializes the given <paramref name="column"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="column">The <see cref="PropertyColumn"/> which to initialze.</param>
		/// <param name="properties">The properties.</param>
		/// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception>
		protected static void Initialize(IMansionContext context, PropertyColumn column, IPropertyBag properties)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (column == null)
				throw new ArgumentNullException("column");
			if (properties == null)
				throw new ArgumentNullException("properties");

			// get the allow null flag
			column.AllowNullValue = properties.Get(context, "allowNullValue", false);

			// check if there is an expression
			string expressionString;
			if (properties.TryGet(context, "expression", out expressionString))
			{
				var expressionService = context.Nucleus.ResolveSingle<IExpressionScriptService>();
				column.HasExpression = true;
				column.Expression = expressionService.Parse(context, new LiteralResource(expressionString));
			}

			// get the default value
			string defaultValue;
			if (properties.TryGet(context, "defaultValue", out defaultValue))
			{
				var expressionService = context.Nucleus.ResolveSingle<IExpressionScriptService>();
				var defaultValueExpression = expressionService.Parse(context, new LiteralResource(defaultValue));
				column.DefaultValue = defaultValueExpression.Execute<object>(context);
				column.HasDefaultValue = true;
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="queryBuilder"></param>
		/// <param name="properties"></param>
		protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties)
		{
			// allow identity insert on special cases, most likely used when fixing the repository integrity
			if (!properties.Get(context, "_allowIdenityInsert", false))
				return;

			queryBuilder.PrependQuery("SET IDENTITY_INSERT [dbo].[Nodes] ON;");
			// get the value of the column
			var value = properties.Get<object>(context, PropertyName);

			// add the parameter
			var parameterName = queryBuilder.AddParameter(ColumnName, value);

			// set the column value
			queryBuilder.AddColumnValue(ColumnName, parameterName);
			queryBuilder.AppendQuery("SET IDENTITY_INSERT [dbo].[Nodes] OFF;");
		}
示例#13
0
        public virtual void DefineOwnProperty(Descriptor currentDescriptor)
        {
            string     key = currentDescriptor.Name;
            Descriptor desc;

            if (properties.TryGet(key, out desc) && desc.Owner == this)
            {
                // updating an existing property
                switch (desc.DescriptorType)
                {
                case DescriptorType.Value:
                    switch (currentDescriptor.DescriptorType)
                    {
                    case DescriptorType.Value:
                        properties.Get(key).Set(this, currentDescriptor.Get(this));
                        break;

                    case DescriptorType.Accessor:
                        properties.Delete(key);
                        properties.Put(key, currentDescriptor);
                        break;

                    case DescriptorType.Clr:
                        throw new NotSupportedException();

                    default:
                        break;
                    }
                    break;

                case DescriptorType.Accessor:
                    PropertyDescriptor propDesc = (PropertyDescriptor)desc;
                    if (currentDescriptor.DescriptorType == DescriptorType.Accessor)
                    {
                        propDesc.GetFunction = ((PropertyDescriptor)currentDescriptor).GetFunction ?? propDesc.GetFunction;
                        propDesc.SetFunction = ((PropertyDescriptor)currentDescriptor).SetFunction ?? propDesc.SetFunction;
                    }
                    else
                    {
                        propDesc.Set(this, currentDescriptor.Get(this));
                    }
                    break;

                default:
                    break;
                }
            }
            else
            {
                // add a new property
                if (desc != null)
                {
                    desc.Owner.RedefineProperty(desc.Name); // if we have a cached property
                }
                properties.Put(key, currentDescriptor);
                m_length++;
            }
        }
示例#14
0
        /// <summary>
        /// Gets an <see cref="IScenario"/> from a given NUnit property bad.
        /// </summary>
        /// <returns>The scenario.</returns>
        /// <param name="properties">Properties.</param>
        public static IScenario GetScenario(IPropertyBag properties)
        {
            if (properties.ContainsKey(ScreenplayScenarioKey))
            {
                return((IScenario)properties.Get(ScreenplayScenarioKey));
            }

            return(null);
        }
示例#15
0
        public T Get <T>(string name)
        {
            object result;

            if (_properties.TryGetValue(GetKey <T>(name), out result))
            {
                return((T)result);
            }
            return(_parent == null ? default(T) : _parent.Get <T>(name));
        }
		/// <summary>
		/// Transforms the given <paramref name="source"/> into an ElasticSearch document.
		/// </summary>
		/// <param name="context">the <see cref="IMansionContext"/>.</param>
		/// <param name="source">The <see cref="IPropertyBag"/> which to transform.</param>
		/// <param name="document">The document to which to write the mapped value.</param>
		/// <returns>Returns the resulting document.</returns>
		/// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception>
		protected override void DoTransform(IMansionContext context, IPropertyBag source, Dictionary<string, object> document)
		{
			// get the property value
			var raw = source.Get(context, Field, string.Empty) ?? string.Empty;

			// split on comma, trim all values, remove empty entries
			var values = raw.Split(new[] {','}).Select(x => Normalize(context, x.Trim()).ToString()).Where(x => !string.IsNullOrEmpty(x)).ToArray();

			// write the values to the document
			document.Add(Field, values);
		}
示例#17
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="queryBuilder"></param>
		/// <param name="properties"></param>
		protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties)
		{
			// build the select max order + 1 query only for none root nodes
			var newPointer = properties.Get<NodePointer>(context, "_newPointer");
			queryBuilder.PrependQuery("DECLARE @order int = 1");
			if (newPointer.Depth > 1)
				queryBuilder.PrependQuery(string.Format("SET @order = (SELECT ISNULL(MAX([order]) + 1, 1) FROM [Nodes] WHERE [parentId] = {0})", queryBuilder.AddParameter("parentId", newPointer.Parent.Id, DbType.Int32)));

			// add the column
			queryBuilder.AddColumnValue(PropertyName, "@order");
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="queryBuilder"></param>
		/// <param name="properties"></param>
		protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties)
		{
			var newPointer = properties.Get<NodePointer>(context, "_newPointer");
			queryBuilder.AddColumnValue("name", newPointer.Name.Trim(), DbType.String);
			queryBuilder.AddColumnValue("type", newPointer.Type.Trim(), DbType.String);
			queryBuilder.AddColumnValue("depth", newPointer.Depth, DbType.Int32);

			queryBuilder.AddColumnValue("parentId", newPointer.HasParent ? (object) newPointer.Parent.Id : null, DbType.Int32);
			queryBuilder.AddColumnValue("parentPointer", newPointer.HasParent ? newPointer.Parent.PointerString + NodePointer.PointerSeparator : null, DbType.String);
			queryBuilder.AddColumnValue("parentPath", newPointer.HasParent ? newPointer.Parent.PathString + NodePointer.PathSeparator : null, DbType.String);
			queryBuilder.AddColumnValue("parentStructure", newPointer.HasParent ? newPointer.Parent.StructureString + NodePointer.StructureSeparator : null, DbType.String);
		}
		/// <summary>
		/// Renders a cell of this column.
		/// </summary>
		/// <param name="context">The <see cref="IMansionWebContext"/>.</param>
		/// <param name="templateService">The <see cref="ITemplateService"/>.</param>
		/// <param name="dataset">The <see cref="Dataset"/> rendered in this column.</param>
		/// <param name="row">The being rendered.</param>
		protected override void DoRenderCell(IMansionWebContext context, ITemplateService templateService, Dataset dataset, IPropertyBag row)
		{
			// create the cell properties
			var cellProperties = new PropertyBag
			                     {
			                     	{"value", row.Get<object>(context, propertyName, null)}
			                     };

			// render the cell
			using (context.Stack.Push("CellProperties", cellProperties))
				templateService.Render(context, "GridControlPropertyColumnContent").Dispose();
		}
示例#20
0
        public Jint.Native.Descriptor Get(string name)
        {
            if (lastAccessed != null && lastAccessed.Name == name)
            {
                return(lastAccessed);
            }
            Descriptor descriptor = bag.Get(name);

            if (descriptor != null)
            {
                lastAccessed = descriptor;
            }
            return(descriptor);
        }
        public void DefineOwnProperty(string key, Descriptor currentDescriptor)
        {
            Descriptor desc;

            if (properties.TryGet(key, out desc))
            {
                switch (desc.DescriptorType)
                {
                case DescriptorType.Value:
                    switch (currentDescriptor.DescriptorType)
                    {
                    case DescriptorType.Value:
                        properties.Get(key).Set(this, currentDescriptor.Get(this));
                        break;

                    case DescriptorType.Accessor:
                        properties.Delete(key);
                        properties.Put(key, currentDescriptor);
                        break;

                    case DescriptorType.Clr:
                        throw new NotSupportedException();

                    default:
                        break;
                    }
                    break;

                case DescriptorType.Accessor:
                    PropertyDescriptor propDesc = (PropertyDescriptor)desc;
                    if (currentDescriptor.DescriptorType == DescriptorType.Accessor)
                    {
                        propDesc.GetFunction = ((PropertyDescriptor)currentDescriptor).GetFunction ?? propDesc.GetFunction;
                        propDesc.SetFunction = ((PropertyDescriptor)currentDescriptor).SetFunction ?? propDesc.SetFunction;
                    }
                    else
                    {
                        propDesc.Set(this, currentDescriptor.Get(this));
                    }
                    break;

                default:
                    break;
                }
            }
            else
            {
                properties.Put(key, currentDescriptor);
            }
        }
示例#22
0
        public static T GetValue <T>(this IPropertyBag properties, string key) where T : class
        {
            _dict.Clear();

            foreach (var propeprtyBagKey in properties.Keys)
            {
                _dict[propeprtyBagKey] = properties.Get(propeprtyBagKey);
            }

            object obj;

            if (_dict != null && _dict.TryGetValue(key, out obj) && _dict.Count > 0)
            {
                return(_dict[key] as T);
            }
            return(null);
        }
		/// <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);
			}
		}
示例#24
0
		/// <summary>
		/// Prepares an insert query.
		/// </summary>
		/// <param name="context"></param>
		/// <param name="connection">The connection.</param>
		/// <param name="transaction">The transaction.</param>
		/// <param name="properties"></param>
		/// <returns></returns>
		public void Prepare(IMansionContext context, SqlConnection connection, SqlTransaction transaction, IPropertyBag properties)
		{
			// validate arguments
			if (connection == null)
				throw new ArgumentNullException("connection");
			if (transaction == null)
				throw new ArgumentNullException("transaction");
			if (properties == null)
				throw new ArgumentNullException("properties");

			// get the values
			var typeName = properties.Get<string>(context, "type", null);
			if (string.IsNullOrWhiteSpace(typeName))
				throw new InvalidOperationException("A record 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 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();
		}
示例#25
0
        /// <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>
        /// Renders the specified <paramref name="blockProperties"/> to the output pipe.
        /// </summary>
        /// <param name="context">The <see cref="IMansionContext"/>.</param>
        /// <param name="blockProperties">The <see cref="IPropertyBag"/> of the block which to render.</param>
        /// <param name="targetField">The name of the field to which to render.</param>
        protected override void DoRender(IMansionContext context, IPropertyBag blockProperties, string targetField)
        {
            // first retrieve the block node to display
            Guid displayedBlockGuid;
            if (!blockProperties.TryGet(context, "blockGuid", out displayedBlockGuid))
                throw new InvalidOperationException("Block guid not found for shared block display");
            var displayedBlockNode = context.Repository.RetrieveSingleNode(context, new PropertyBag
                                                                                    {
                                                                                        {"guid", displayedBlockGuid}
                                                                                    });
            if (displayedBlockNode == null)
                throw new InvalidOperationException(string.Format("Could not find block with guid '{0}'", displayedBlockGuid));

            // second, merge the two block properties together
            var mergedBlockProperties = new PropertyBag();
            mergedBlockProperties.Merge(blockProperties);
            mergedBlockProperties.Merge(displayedBlockNode);
            mergedBlockProperties.Set("id", blockProperties.Get<int>(context, "id"));

            // finally re-render the combined block using the portal service
            PortalService.RenderBlock(context, mergedBlockProperties, targetField);
        }
		/// <summary>
		/// </summary>
		/// <param name="context"></param>
		/// <param name="dataspace"></param>
		/// <returns></returns>
		public string Evaluate(IMansionContext context, IPropertyBag dataspace)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (dataspace == null)
				throw new ArgumentNullException("dataspace");

			// write the dataspace out to JSon array
			var buffer = new StringBuilder();
			using (var textWriter = new StringWriter(buffer))
			using (var jsonWriter = new JsonTextWriter(textWriter))
			{
				jsonWriter.WriteStartArray();

				// loop over the values in the dataspace
				foreach (var property in dataspace.Where(x => x.Value != null))
				{
					// get the type
					var propertyType = property.Value.GetType();

					// if this type has no serializer, convert it to string first
					var value = property.Value;
					if (!Serializer.Converters.Any(candidate => candidate.CanConvert(propertyType)))
						value = dataspace.Get<string>(context, property.Key);

					// write the value
					jsonWriter.WriteValue(value);
				}

				jsonWriter.WriteEndArray();
			}

			// return the content of the buffer.
			return buffer.ToString();
		}
        /// <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="node">The modified node.</param>
        /// <param name="modifiedProperties">The properties which were set to the updated <paramref name="node"/>.</param>
        protected override void DoAfterUpdate(IMansionContext context, Node node, IPropertyBag modifiedProperties)
        {
            // loop over all the updated properties to find those who start with _propagate
            foreach (var propagatePropertyName in modifiedProperties.Names.Where(x => x.StartsWith(PropagatePrefix, StringComparison.OrdinalIgnoreCase)))
            {
                // get the name of the property being propagated
                var propagatedPropertyName = propagatePropertyName.Substring(PropagatePrefix.Length);

                // get the propagated property value
                var propagatedPropertyValue = modifiedProperties.Get<object>(context, propagatedPropertyName);

                // retrieve all the children nodes and update them all
                foreach (var childNode in context.Repository.Retrieve(context, new PropertyBag
                                                                               {
                                                                               	{"parentSource", node}, {"depth", "any"}
                                                                               }).Nodes)
                {
                    context.Repository.Update(context, childNode, new PropertyBag
                                                                  {
                                                                  	{propagatedPropertyName, propagatedPropertyValue}
                                                                  });
                }
            }
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="queryBuilder"></param>
		/// <param name="properties"></param>
		protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties)
		{
			// get the value of the column
			var value = GetValue(context, properties.Get<object>(context, PropertyName));

			// add the parameter
			var parameterName = queryBuilder.AddParameter(ColumnName, value);

			// set the column value
			queryBuilder.AddColumnValue(ColumnName, parameterName);
		}
        /// <summary>
        /// Authenticates using ID.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private AuthenticationResult AuthenticateWithId(IMansionContext context, IPropertyBag parameters)
        {
            // get the credentials
            var userId = parameters.Get<int>(context, "userId");

            // perform a query
            var userNode = context.Repository.RetrieveSingleNode(context, new PropertyBag {
                {"baseType", "User"},
                {"id", userId},
                {"status", "any"},
                {"bypassAuthorization", true},
                {"cache", false},
                {StorageOnlyQueryComponent.PropertyKey, true}
            });
            if (userNode == null)
            {
                return AuthenticationResult.Failed(new PropertyBag {
                    {AuthenticationResult.ReasonPropertyName, AuthenticationResult.InvalidCredentialsReason}
                });
            }

            // create and return the user state
            return AuthenticationResult.Success(CreateUserState(context, userNode), new PropertyBag());
        }
示例#31
0
 /// <summary>
 /// Get the first property with the given <paramref name="key"/>, if it can be found, otherwise
 /// returns null.
 /// </summary>
 public object Get(string key)
 {
     return(_source.Get(key));
 }
示例#32
0
		/// <summary>
		/// Send a report email
		/// </summary>
		/// <param name="context"></param>
		/// <param name="jobNode"></param>
		/// <param name="taskDescriptor"></param>
		/// <param name="task"></param>
		/// <param name="taskOutput"></param>
		/// <param name="exception"></param>
		private static void SendErrorReportEmail(IMansionContext context, IPropertyBag jobNode, Type taskDescriptor, Task task,
			StringBuilder taskOutput, Exception exception = null)
		{
			var reportEmailFrom = jobNode.Get<string>(context, "reportEmailFrom", null);
			if (reportEmailFrom.IsNullOrWhiteSpace())
				return;

			var reportEmailTo = jobNode.Get<string>(context, "reportEmailTo", null);
			if (reportEmailTo.IsNullOrWhiteSpace())
				return;

			var mailService = context.Nucleus.ResolveSingle<IMailService>();
			using (var message = mailService.CreateMessage())
			{
				message.To.Add(reportEmailTo);
				message.From = new MailAddress(reportEmailFrom);
				message.Subject = String.Format("Job '{0}' failed while executing task '{1}'", jobNode.Get<string>(context, "name"),
					taskDescriptor.Name);

				message.Body = (exception != null)
					? String.Format("The following exception occurred while executing task '{0}': [{1}] {2}", taskDescriptor.Name,
						exception.GetType().Name, exception.Message)
					: String.Format("The task '{0}' failed and gave the following output: {1}", taskDescriptor.Name, taskOutput);

				task.EnrichErrorReportEmail(message, exception);
				mailService.Send(context, message);
			}
		}
		/// <summary>
		/// Transforms the given <paramref name="source"/> into an ElasticSearch document.
		/// </summary>
		/// <param name="context">the <see cref="IMansionContext"/>.</param>
		/// <param name="source">The <see cref="IPropertyBag"/> which to transform.</param>
		/// <param name="document">The document to which to write the mapped value.</param>
		/// <returns>Returns the resulting document.</returns>
		/// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception>
		protected override void DoTransform(IMansionContext context, IPropertyBag source, Dictionary<string, object> document)
		{
			// just map the value to the document
			document.Add(Field, Normalize(context, source.Get<object>(context, Field)));
		}
        internal static Scope CreateScope(ITest currentTest, Type targetType)
        {
            MethodInfo testMethod = currentTest.Method.MethodInfo;

            object[]     testMethodArguments  = currentTest.Arguments;
            IPropertyBag testMethodProperties = currentTest.Properties;

            if (testMethod == null)
            {
                return(null);
            }

            string testFramework = "NUnit " + targetType?.Assembly?.GetName().Version;
            string testSuite     = testMethod.DeclaringType?.FullName;
            string testName      = testMethod.Name;
            string skipReason    = null;

            Scope scope = Common.TestTracer.StartActive("nunit.test", serviceName: Common.TestTracer.DefaultServiceName);
            Span  span  = scope.Span;

            span.Type = SpanTypes.Test;
            span.SetTraceSamplingPriority(SamplingPriority.AutoKeep);
            span.ResourceName = $"{testSuite}.{testName}";
            span.SetTag(Tags.Origin, TestTags.CIAppTestOriginName);
            span.SetTag(TestTags.Suite, testSuite);
            span.SetTag(TestTags.Name, testName);
            span.SetTag(TestTags.Framework, testFramework);
            span.SetTag(TestTags.Type, TestTags.TypeTest);
            CIEnvironmentValues.DecorateSpan(span);

            var framework = FrameworkDescription.Instance;

            span.SetTag(CommonTags.RuntimeName, framework.Name);
            span.SetTag(CommonTags.RuntimeVersion, framework.ProductVersion);
            span.SetTag(CommonTags.RuntimeArchitecture, framework.ProcessArchitecture);
            span.SetTag(CommonTags.OSArchitecture, framework.OSArchitecture);
            span.SetTag(CommonTags.OSPlatform, framework.OSPlatform);
            span.SetTag(CommonTags.OSVersion, Environment.OSVersion.VersionString);

            // Get test parameters
            ParameterInfo[] methodParameters = testMethod.GetParameters();
            if (methodParameters?.Length > 0)
            {
                TestParameters testParameters = new TestParameters();
                testParameters.Metadata  = new Dictionary <string, object>();
                testParameters.Arguments = new Dictionary <string, object>();
                testParameters.Metadata[TestTags.MetadataTestName] = currentTest.Name;

                for (int i = 0; i < methodParameters.Length; i++)
                {
                    if (testMethodArguments != null && i < testMethodArguments.Length)
                    {
                        testParameters.Arguments[methodParameters[i].Name] = testMethodArguments[i]?.ToString() ?? "(null)";
                    }
                    else
                    {
                        testParameters.Arguments[methodParameters[i].Name] = "(default)";
                    }
                }

                span.SetTag(TestTags.Parameters, testParameters.ToJSON());
            }

            // Get traits
            if (testMethodProperties != null)
            {
                Dictionary <string, List <string> > traits = new Dictionary <string, List <string> >();
                skipReason = (string)testMethodProperties.Get("_SKIPREASON");
                foreach (var key in testMethodProperties.Keys)
                {
                    if (key == "_SKIPREASON" || key == "_JOINTYPE")
                    {
                        continue;
                    }

                    IList value = testMethodProperties[key];
                    if (value != null)
                    {
                        List <string> lstValues = new List <string>();
                        foreach (object valObj in value)
                        {
                            if (valObj is null)
                            {
                                continue;
                            }

                            lstValues.Add(valObj.ToString());
                        }

                        traits[key] = lstValues;
                    }
                    else
                    {
                        traits[key] = null;
                    }
                }

                if (traits.Count > 0)
                {
                    span.SetTag(TestTags.Traits, Datadog.Trace.Vendors.Newtonsoft.Json.JsonConvert.SerializeObject(traits));
                }
            }

            if (skipReason != null)
            {
                FinishSkippedScope(scope, skipReason);
                scope = null;
            }

            span.ResetStartTime();
            return(scope);
        }
		/// <summary>
		/// Interprets the input..
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="input">The input which to interpret.</param>
		/// <returns>Returns the interpreted result.</returns>
		protected override IResourcePath DoInterpret(IMansionContext context, IPropertyBag input)
		{
			// get the path
			var type = input.Get<ITypeDefinition>(context, "type");
			if (type == null)
				throw new InvalidOperationException("The type must be specified");
			var extension = input.Get(context, "extension", string.Empty).TrimStart('.');
			if (string.IsNullOrEmpty(extension))
				throw new InvalidOperationException("The extension must be specified");
			var overridable = input.Get(context, "overridable", true);

			// return the resource path
			return new TypeResourcePath(type.Hierarchy.Select(x => x.Name), extension, overridable);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="queryBuilder"></param>
		/// <param name="record"> </param>
		/// <param name="modifiedProperties"></param>
		protected override void DoToUpdateStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, Record record, IPropertyBag modifiedProperties)
		{
			// allow update of relational column on special cases, most likely used when fixing the repository integrity
			if (modifiedProperties.Get(context, "_allowRelationPropertiesUpdate", false))
			{
				string name;
				if (modifiedProperties.TryGet(context, "name", out name))
					queryBuilder.AddColumnValue("name", name, DbType.String);
				string type;
				if (modifiedProperties.TryGet(context, "type", out type))
					queryBuilder.AddColumnValue("type", type, DbType.String);
				int depth;
				if (modifiedProperties.TryGet(context, "depth", out depth))
					queryBuilder.AddColumnValue("depth", depth, DbType.Int32);
				int parentId;
				if (modifiedProperties.TryGet(context, "parentId", out parentId))
					queryBuilder.AddColumnValue("parentId", parentId, DbType.Int32);
				string parentPointer;
				if (modifiedProperties.TryGet(context, "parentPointer", out parentPointer))
					queryBuilder.AddColumnValue("parentPointer", parentPointer, DbType.String);
				string parentPath;
				if (modifiedProperties.TryGet(context, "parentPath", out parentPath))
					queryBuilder.AddColumnValue("parentPath", parentPath, DbType.String);
				string parentStructure;
				if (modifiedProperties.TryGet(context, "parentStructure", out parentStructure))
					queryBuilder.AddColumnValue("parentStructure", parentStructure, DbType.String);
				return;
			}

			// make sure the relational intgrety is not comprimised
			if (modifiedProperties.Names.Intersect(ReservedPropertyName, StringComparer.OrdinalIgnoreCase).Any())
				throw new InvalidOperationException("The relational properties can not be changed");

			// get the pointer
			NodePointer pointer;
			if (!record.TryGet(context, "pointer", out pointer))
				throw new InvalidOperationException("Could not update this record because it did not contain a pointer");

			//  add the id an pointer parameters
			var idParameterName = queryBuilder.AddParameter("id", pointer.Id, DbType.Int32);
			var pointerParameterName = queryBuilder.AddParameter("pointer", pointer.PointerString + "-%", DbType.String);

			// check if the name changed
			string newName;
			if (modifiedProperties.TryGetAndRemove(context, "name", out newName))
			{
				newName = newName.Trim();
				if (string.IsNullOrEmpty(newName))
					throw new InvalidOperationException("Can not update column name with empty string");
				if (newName.Contains(NodePointer.PathSeparator))
					throw new InvalidOperationException(string.Format("Name '{0}' contains invalid characters", newName));
				if (!pointer.Name.Equals(newName))
				{
					// add the name column modification
					queryBuilder.AddColumnValue("name", newName, DbType.String);

					// update the paths
					var oldPathLengthParameterName = queryBuilder.AddParameter("oldPathLength", pointer.PathString.Length + 1, DbType.String);
					var newPathParameterName = queryBuilder.AddParameter("newPath", NodePointer.Rename(pointer, newName).PathString + NodePointer.PathSeparator, DbType.String);
					queryBuilder.AppendQuery(string.Format(@" UPDATE [Nodes] SET [parentPath] = {0} + RIGHT( [parentPath], LEN( [parentPath] ) - {1} ) WHERE ( [parentId] = {2} OR [parentPointer] LIKE {3} )", newPathParameterName, oldPathLengthParameterName, idParameterName, pointerParameterName));
				}
			}

			// check if the type changed
			string newType;
			if (modifiedProperties.TryGetAndRemove(context, "type", out newType))
			{
				newType = newType.Trim();
				if (string.IsNullOrEmpty(newType))
					throw new InvalidOperationException("Can not update column type with empty string");
				if (newType.Contains(NodePointer.StructureSeparator))
					throw new InvalidOperationException(string.Format("Type '{0}' contains invalid characters", newType));
				if (!string.IsNullOrEmpty(newType) && !pointer.Type.Equals(newType, StringComparison.OrdinalIgnoreCase))
				{
					// add the name column modification
					queryBuilder.AddColumnValue("type", newType, DbType.String);

					// update the structures
					var newStructureParameterName = queryBuilder.AddParameter("newStructure", NodePointer.ChangeType(pointer, newType).StructureString + NodePointer.StructureSeparator, DbType.String);
					var oldStructureLengthParameterName = queryBuilder.AddParameter("oldStructureLength", pointer.StructureString.Length + 1, DbType.Int32);
					queryBuilder.AppendQuery(string.Format("UPDATE [Nodes] SET [parentStructure] = {0} + RIGHT( [parentStructure], LEN( [parentStructure] ) - {1} ) WHERE ( [parentId] = {2} OR [parentPointer] LIKE {3} )", newStructureParameterName, oldStructureLengthParameterName, idParameterName, pointerParameterName));
				}
			}
		}
        /// <summary>
        /// Authenticates using username/password.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private AuthenticationResult AuthenticateWithUsernamePassword(IMansionContext context, IPropertyBag parameters)
        {
            // get the credentials
            var username = parameters.Get(context, "username", string.Empty);
            if (string.IsNullOrEmpty(username))
            {
                return AuthenticationResult.Failed(new PropertyBag {
                    {AuthenticationResult.ReasonPropertyName, AuthenticationResult.NoUsernameSpecifiedReason}
                });
            }
            var password = parameters.Get(context, "password", string.Empty);
            if (string.IsNullOrEmpty(password))
            {
                return AuthenticationResult.Failed(new PropertyBag {
                    {AuthenticationResult.ReasonPropertyName, AuthenticationResult.NoPasswordSpecifiedReason}
                });
            }

            // perform a query
            var userNode = context.Repository.RetrieveSingleNode(context, new PropertyBag {
                {"baseType", "User"},
                {"login", username},
                {"password", password},
                {"status", "any"},
                {"bypassAuthorization", true},
                {"cache", false},
                {StorageOnlyQueryComponent.PropertyKey, true}
            });
            if (userNode == null)
            {
                return AuthenticationResult.Failed(new PropertyBag {
                    {AuthenticationResult.ReasonPropertyName, AuthenticationResult.InvalidCredentialsReason}
                });
            }

            // check against unpublished users
            if (userNode.Status != NodeStatus.Published)
            {
                return AuthenticationResult.Failed(new PropertyBag {
                    {AuthenticationResult.ReasonPropertyName, AuthenticationResult.AccounDeactivatedReason}
                });
            }

            // create and return the user state
            return AuthenticationResult.Success(CreateUserState(context, userNode), new PropertyBag());
        }
示例#38
0
 /// <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)));
 }
示例#39
0
        internal static Scope CreateScope <TContext>(TContext executionContext, Type targetType)
            where TContext : ITestExecutionContext
        {
            ITest      currentTest = executionContext.CurrentTest;
            MethodInfo testMethod  = currentTest.Method.MethodInfo;

            object[]     testMethodArguments  = currentTest.Arguments;
            IPropertyBag testMethodProperties = currentTest.Properties;

            if (testMethod == null)
            {
                return(null);
            }

            string testFramework = "NUnit " + targetType?.Assembly?.GetName().Version;
            string testSuite     = testMethod.DeclaringType?.FullName;
            string testName      = testMethod.Name;
            string skipReason    = null;

            Tracer tracer = Tracer.Instance;
            Scope  scope  = tracer.StartActive("nunit.test");
            Span   span   = scope.Span;

            span.Type = SpanTypes.Test;
            span.SetTraceSamplingPriority(SamplingPriority.AutoKeep);
            span.ResourceName = $"{testSuite}.{testName}";
            span.SetTag(TestTags.Suite, testSuite);
            span.SetTag(TestTags.Name, testName);
            span.SetTag(TestTags.Framework, testFramework);
            span.SetTag(TestTags.Type, TestTags.TypeTest);
            CIEnvironmentValues.DecorateSpan(span);

            var framework = FrameworkDescription.Instance;

            span.SetTag(CommonTags.RuntimeName, framework.Name);
            span.SetTag(CommonTags.RuntimeOSArchitecture, framework.OSArchitecture);
            span.SetTag(CommonTags.RuntimeOSPlatform, framework.OSPlatform);
            span.SetTag(CommonTags.RuntimeProcessArchitecture, framework.ProcessArchitecture);
            span.SetTag(CommonTags.RuntimeVersion, framework.ProductVersion);

            // Get test parameters
            ParameterInfo[] methodParameters = testMethod.GetParameters();
            if (methodParameters?.Length > 0)
            {
                for (int i = 0; i < methodParameters.Length; i++)
                {
                    if (testMethodArguments != null && i < testMethodArguments.Length)
                    {
                        span.SetTag($"{TestTags.Arguments}.{methodParameters[i].Name}", testMethodArguments[i]?.ToString() ?? "(null)");
                    }
                    else
                    {
                        span.SetTag($"{TestTags.Arguments}.{methodParameters[i].Name}", "(default)");
                    }
                }
            }

            // Get traits
            if (testMethodProperties != null)
            {
                skipReason = (string)testMethodProperties.Get("_SKIPREASON");
                foreach (var key in testMethodProperties.Keys)
                {
                    if (key == "_SKIPREASON")
                    {
                        continue;
                    }

                    IList value = testMethodProperties[key];
                    if (value != null)
                    {
                        List <string> lstValues = new List <string>();
                        foreach (object valObj in value)
                        {
                            if (valObj is null)
                            {
                                continue;
                            }

                            lstValues.Add(valObj.ToString());
                        }

                        span.SetTag($"{TestTags.Traits}.{key}", string.Join(", ", lstValues));
                    }
                    else
                    {
                        span.SetTag($"{TestTags.Traits}.{key}", "(null)");
                    }
                }
            }

            if (skipReason != null)
            {
                span.SetTag(TestTags.Status, TestTags.StatusSkip);
                span.SetTag(TestTags.SkipReason, skipReason);
                span.Finish(TimeSpan.Zero);
                scope.Dispose();
                scope = null;
            }

            span.ResetStartTime();
            return(scope);
        }
 /// <summary>
 /// Gets a <see cref="Dataset"/> containing all the columns available for the specified type.
 /// </summary>
 /// <param name="context">The request context.</param>
 /// <param name="attributes">The attributes of this tag.</param>
 /// <returns>Returns the result.</returns>
 protected override Dataset Get(IMansionContext context, IPropertyBag attributes)
 {
     return portalService.GetColumnDataset(context, attributes.Get<ITypeDefinition>(context, "type"));
 }
示例#41
0
        internal static Scope CreateScope(ITest currentTest, Type targetType)
        {
            MethodInfo testMethod = currentTest.Method.MethodInfo;

            object[]     testMethodArguments  = currentTest.Arguments;
            IPropertyBag testMethodProperties = currentTest.Properties;

            if (testMethod == null)
            {
                return(null);
            }

            string testFramework    = "NUnit";
            string fullName         = currentTest.FullName;
            string composedTestName = currentTest.Name;

            string testName   = testMethod.Name;
            string testSuite  = testMethod.DeclaringType?.FullName;
            string testBundle = testMethod.DeclaringType?.Assembly?.GetName().Name;

            // Extract the test suite from the full name to support custom fixture parameters and test declared in base classes.
            if (fullName.EndsWith("." + composedTestName))
            {
                testSuite = fullName.Substring(0, fullName.Length - (composedTestName.Length + 1));
            }

            string skipReason = null;

            Scope scope = Tracer.Instance.StartActiveInternal("nunit.test");
            Span  span  = scope.Span;

            span.Type = SpanTypes.Test;
            span.SetTraceSamplingPriority(SamplingPriorityValues.AutoKeep);
            span.ResourceName = $"{testSuite}.{testName}";
            span.SetTag(Tags.Origin, TestTags.CIAppTestOriginName);
            span.SetTag(Tags.Language, TracerConstants.Language);
            span.SetTag(TestTags.Bundle, testBundle);
            span.SetTag(TestTags.Suite, testSuite);
            span.SetTag(TestTags.Name, testName);
            span.SetTag(TestTags.Framework, testFramework);
            span.SetTag(TestTags.FrameworkVersion, targetType.Assembly?.GetName().Version.ToString());
            span.SetTag(TestTags.Type, TestTags.TypeTest);
            CIEnvironmentValues.Instance.DecorateSpan(span);

            var framework = FrameworkDescription.Instance;

            span.SetTag(CommonTags.LibraryVersion, TracerConstants.AssemblyVersion);
            span.SetTag(CommonTags.RuntimeName, framework.Name);
            span.SetTag(CommonTags.RuntimeVersion, framework.ProductVersion);
            span.SetTag(CommonTags.RuntimeArchitecture, framework.ProcessArchitecture);
            span.SetTag(CommonTags.OSArchitecture, framework.OSArchitecture);
            span.SetTag(CommonTags.OSPlatform, framework.OSPlatform);
            span.SetTag(CommonTags.OSVersion, Environment.OSVersion.VersionString);

            // Get test parameters
            ParameterInfo[] methodParameters = testMethod.GetParameters();
            if (methodParameters?.Length > 0)
            {
                TestParameters testParameters = new TestParameters();
                testParameters.Metadata  = new Dictionary <string, object>();
                testParameters.Arguments = new Dictionary <string, object>();
                testParameters.Metadata[TestTags.MetadataTestName] = currentTest.Name;

                for (int i = 0; i < methodParameters.Length; i++)
                {
                    if (testMethodArguments != null && i < testMethodArguments.Length)
                    {
                        testParameters.Arguments[methodParameters[i].Name] = Common.GetParametersValueData(testMethodArguments[i]);
                    }
                    else
                    {
                        testParameters.Arguments[methodParameters[i].Name] = "(default)";
                    }
                }

                span.SetTag(TestTags.Parameters, testParameters.ToJSON());
            }

            // Get traits
            if (testMethodProperties != null)
            {
                Dictionary <string, List <string> > traits = new Dictionary <string, List <string> >();
                skipReason = (string)testMethodProperties.Get("_SKIPREASON");
                foreach (var key in testMethodProperties.Keys)
                {
                    if (key == "_SKIPREASON" || key == "_JOINTYPE")
                    {
                        continue;
                    }

                    IList value = testMethodProperties[key];
                    if (value != null)
                    {
                        List <string> lstValues = new List <string>();
                        foreach (object valObj in value)
                        {
                            if (valObj is null)
                            {
                                continue;
                            }

                            lstValues.Add(valObj.ToString());
                        }

                        traits[key] = lstValues;
                    }
                    else
                    {
                        traits[key] = null;
                    }
                }

                if (traits.Count > 0)
                {
                    span.SetTag(TestTags.Traits, Vendors.Newtonsoft.Json.JsonConvert.SerializeObject(traits));
                }
            }

            if (skipReason != null)
            {
                FinishSkippedScope(scope, skipReason);
                scope = null;
            }

            span.ResetStartTime();
            Tracer.Instance.TracerManager.Telemetry.IntegrationGeneratedSpan(IntegrationId);
            return(scope);
        }
		/// <summary>
		/// Parses the <paramref name="properties"/> into a <see cref="IResourcePath"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="properties">The properties which to parse.</param>
		/// <returns>Returns the parsed <see cref="IResourcePath"/>.</returns>
		public IResourcePath ParsePath(IMansionContext context, IPropertyBag properties)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (properties == null)
				throw new ArgumentNullException("properties");

			// get the resource base path
			var categoryBasePath = properties.Get(context, "category", "Temp");

			// check if it is an existing resource
			string relativePath;
			if (properties.TryGet(context, "relativePath", out relativePath))
				return new ContentResourcePath(relativePath);

			// check if it is a new file name
			string fileName;
			if (properties.TryGet(context, "fileName", out fileName))
			{
				// get the current date
				var today = DateTime.Today;

				// get the file base name and extension
				var fileBaseName = Path.GetFileNameWithoutExtension(fileName);
				var fileExtension = Path.GetExtension(fileName);

				// make sure the file name is unique
				var index = 0;
				while (File.Exists(ResourceUtils.Combine(physicalBasePath, relativeBasePath, categoryBasePath, today.Year.ToString(CultureInfo.InvariantCulture), today.Month.ToString(CultureInfo.InvariantCulture), fileBaseName + index + fileExtension)))
					index++;

				// create the resource path
				return new ContentResourcePath(ResourceUtils.Combine(categoryBasePath, today.Year.ToString(CultureInfo.InvariantCulture), today.Month.ToString(CultureInfo.InvariantCulture), fileBaseName + index + fileExtension));
			}

			// unkonwn type
			throw new InvalidOperationException("Could not identify resource path");
		}
示例#43
0
 /// <summary>
 /// Get the first property with the given <paramref name="key"/>, if it can be found, otherwise
 /// returns null.
 /// </summary>
 public object Get(string key) => _source.Get(key);