public void Set <T>(string name, T value) { bool valueSet = false; T existingValue; if (_props.TryGetValue(name, out existingValue)) { if (!existingValue.Equals(value)) { _props.Set(name, value); valueSet = true; } } else { _props.Set(name, value); valueSet = true; } if (valueSet) { OnSettingChanged(new SettingChangeEventArgs(name)); } }
/// <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> /// 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> /// Executes this tag. /// </summary> /// <param name="context">The application context.</param> protected override void DoExecute(IMansionContext context) { // get the fix flag var fix = GetAttribute(context, "fix", false); // create the report dataspace var report = new PropertyBag(); // verify report.Set("result", VerifyIntegrity(context, fix)); // push the report to the stack using (context.Stack.Push("Report", report)) ExecuteChildTags(context); }
private bool SetPropertyBagValue <T>(Expression <Func <T> > propertyExpression, T value) { T curValue; var propertyName = GetPropertyName(propertyExpression); if (!PropertyBag.Get <T>(propertyName, out curValue) || !curValue.Equals(value)) { PropertyBag.Set <T>(propertyName, value); RaisePropertyChanged(propertyExpression); } return(true); }
/// <summary> /// Constructs this provider with the specified <paramref name="children" />. /// </summary> /// <param name="children">The <see cref="XElement" />s from which to get the values.</param> public ChildXmlDatasetProvider(IEnumerable<XElement> children) { // validate arguments if (children == null) throw new ArgumentNullException("children"); // create the dataset dataset = new Dataset(); // loop over all the children and get the content of its children foreach (var child in children) { var properties = new PropertyBag(); foreach (var contentChild in child.Elements()) properties.Set(contentChild.Name.LocalName, contentChild.Value); dataset.AddRow(properties); } }
public void TestEnemyCrushedWhenEnemyDoesNotScore() { var propertyBag = new PropertyBag(); propertyBag.Set(GameObjectProperties.MonsterScoresWhenKilled, false); var monster = new Mock<IMonster>(); monster.Setup(monsterShoots => monsterShoots.Energy).Returns(10); monster.Setup(m => m.Properties).Returns(propertyBag); var boulder = new Mock<IGameObject>(); using (var scoreKeeper = new ScoreKeeper()) { var monsterCrushed = new MonsterCrushed(monster.Object, boulder.Object); Messenger.Default.Send(monsterCrushed); Assert.AreEqual(0, scoreKeeper.CurrentScore); } }
/// <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); }
private static void EncodeSingleFrame(PixelBuffer pixelBuffer, WICFlags flags, Guid guidContainerFormat, Stream stream) { using (var encoder = Factory.CreateEncoder(guidContainerFormat, stream)) using (var propBag = new PropertyBag()) { if (guidContainerFormat == ContainerFormatGuids.Bmp) { try { propBag.Set("EnableV5Header32bppBGRA", true); } catch { } } using (var frame = encoder.CreateNewFrame(propBag)) { EncodeImage(pixelBuffer, flags, frame); encoder.Commit(); } } }
/// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public IEnumerator<IPropertyBag> GetEnumerator() { // make sure this object is not disposed yet CheckDisposed(); // create a buffer var buffer = new StringBuilder(); // read until end of line or end of file var inTextQualifier = false; var firstLineRead = false; var row = new PropertyBag(); var cellIndex = 0; var headerList = new List<string>(); while (true) { // read the current character var currentCharacter = input.Reader.Read(); // check for end of line if (currentCharacter == -1) yield break; // append the character buffer.Append((char) currentCharacter); // check for text qualifier if (buffer.EndsWith(format.TextQualifier)) { // eat the text qualifier buffer.Length -= format.TextQualifier.Length; // toggle the flag inTextQualifier = !inTextQualifier; } else if (inTextQualifier) continue; // check for column delimitor if (buffer.EndsWith(format.ColumnDelimitor)) { // eat the column delimitor buffer.Length -= format.ColumnDelimitor.Length; // get the read value var value = buffer.ToString(); // if the first line is read, store the value in the row property bag if (firstLineRead) row.Set(headerList[cellIndex], value); else { // if the first line contains the header, the value contains a column name, otherwise store the value in the row property bag if (firstLineIsHeader) headerList.Add(value); else { // add a header to the list and store the value headerList.Add(cellIndex.ToString(CultureInfo.InvariantCulture)); row.Set(headerList[cellIndex], value); } } // reset the buffer buffer.Length = 0; // increment the cell index cellIndex++; // keep reading continue; } // check for row delimitor if (buffer.EndsWith(format.RowDelimitor)) { // eat the row delimitor buffer.Length -= format.RowDelimitor.Length; // get the read value var value = buffer.ToString(); buffer.Length = 0; // set the value if (!firstLineRead) { firstLineRead = true; // if the first line contains the header, store the header value if (firstLineIsHeader) { headerList.Add(value); cellIndex = 0; continue; } // add header based on cell index headerList.Add(cellIndex.ToString(CultureInfo.InvariantCulture)); } // store the value row.Set(headerList[cellIndex], value); // return the result yield return row; // reset row = new PropertyBag(); cellIndex = 0; } } }
/// <summary> /// Gets the row. /// </summary> /// <param name="context">The request context.</param> /// <param name="attributes">The attributes of this tag.</param> /// <returns>Returns the result.</returns> protected override IPropertyBag Get(IMansionContext context, IPropertyBag attributes) { // get the web request context var webRequest = context.Cast<IMansionWebContext>(); // get the url Url url; if (!attributes.TryGet(context, "url", out url)) url = webRequest.Request.RequestUrl; // get the area prefix var routeProperties = new PropertyBag(); // if the request was forwarded from a 404, do not parse the route string forwardedFrom404; if (webRequest.Request.Headers.TryGetValue(Constants.ForwardedFrom404HeaderKey, out forwardedFrom404)) { routeProperties.Set("controller", "404"); routeProperties.Set("action", "NotFound"); return routeProperties; } // get the route index var routeUrlIndex = Array.FindIndex(url.PathSegments, x => x.Equals(Constants.RouteUrlPrefix, StringComparison.OrdinalIgnoreCase)); // check if this is no route url if (routeUrlIndex == -1) { // this is no route URL, default controller and action routeProperties.Set("area", GetAttribute<string>(context, "defaultArea")); routeProperties.Set("controller", GetAttribute<string>(context, "defaultController")); routeProperties.Set("action", GetAttribute<string>(context, "defaultAction")); return routeProperties; } // determine the number of route url parts var parameterRouteUrlIndex = Array.FindIndex(url.PathSegments, x => x.Equals(Constants.RouteParameterPrefix, StringComparison.OrdinalIgnoreCase)); var routeUrlPartLength = (parameterRouteUrlIndex != -1 ? parameterRouteUrlIndex : url.PathSegments.Length) - routeUrlIndex; // parse the route parts if (routeUrlIndex != -1 && routeUrlPartLength == 4) { // route url with area routeProperties.Set("area", GetSegment(url, routeUrlIndex + 1)); routeProperties.Set("controller", GetSegment(url, routeUrlIndex + 2)); routeProperties.Set("action", GetSegment(url, routeUrlIndex + 3)); } else if (routeUrlIndex != -1 && routeUrlPartLength == 3) { // route url without area routeProperties.Set("controller", GetSegment(url, routeUrlIndex + 1)); routeProperties.Set("action", GetSegment(url, routeUrlIndex + 2)); } else { // unknown route type throw new InvalidOperationException(string.Format("'{0}' is an invalid route url", url)); } // parse parameters if any if (parameterRouteUrlIndex > -1) { // set all the parameters for (var paremeterIndex = parameterRouteUrlIndex + 1; paremeterIndex < url.PathSegments.Length; paremeterIndex++) routeProperties.Set("routeParameter" + ((paremeterIndex - parameterRouteUrlIndex) - 1), GetSegment(url, paremeterIndex)); } // return the route return routeProperties; }
/// <summary> /// Parses the URL into query parameters. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="url">The <see cref="Url"/> which to parse.</param> /// <param name="queryParameters">The query parameters extracted from <paramref name="url"/>.</param> /// <returns>Returns true when parameters could be extracted, otherwise false.</returns> public bool TryExtractQueryParameters(IMansionWebContext context, Url url, out IPropertyBag queryParameters) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (url == null) throw new ArgumentNullException("url"); // create bag for parameters queryParameters = new PropertyBag(); // check if this is the base url if (url.PathSegments.Length == 0) return false; // determine the id offset var segmentOffset = context.IsBackoffice ? 1 : 0; // check if the is a chance that the ID is in the url if (url.PathSegments.Length <= segmentOffset) return false; // get the last segment which is the document name var candidateId = url.PathSegments[segmentOffset].Trim(Dispatcher.Constants.UrlPartTrimCharacters); // check if the candidate id is an actual number var isNumber = candidateId.IsNumber(); // if it is a number, it is the page id if (isNumber) queryParameters.Set("id", candidateId); return isNumber; }
/// <summary> /// Retrieves a <see cref="Dataset"/> using <paramref name="query"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="query">The query which to execute.</param> /// <returns>Returns a <see cref="Dataset"/> containing the results.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception> public Dataset RetrieveDataset(IMansionContext context, string query) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (string.IsNullOrEmpty(query)) throw new ArgumentNullException("query"); // create the connection and the transaction using (var connection = CreateConnection()) using (var command = connection.CreateCommand()) { // prepare the command command.Connection = connection; command.CommandText = query; command.CommandType = CommandType.Text; // execute the command using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection)) { var dataset = new Dataset(); // looop over all the results while (reader.Read()) { // create the row var row = new PropertyBag(); // map all the properties for (var index = 0; index < reader.FieldCount; index++) row.Set(reader.GetName(index), reader.GetValue(index)); // add the row to the dataset dataset.AddRow(row); } return dataset; } } }