private ValueDictionary ParseBEncodeDict(MemoryStream responseStream) { ValueDictionary dictionary1 = null; if ((this.ContentEncoding == "gzip") || (this.ContentEncoding == "x-gzip")) { var stream1 = new GZipStream(responseStream, CompressionMode.Decompress); try { return((ValueDictionary)BEncode.Parse(stream1)); } catch (Exception) { } } try { dictionary1 = (ValueDictionary)BEncode.Parse(responseStream); } catch (Exception exception1) { Console.Write(exception1.StackTrace); } return(dictionary1); }
public static IAssociationLoader <TAssociation> Scalar <TAssociation>(MetaColumn column, IValueSet source) where TAssociation : class { MetaType type = column.DeclaringType; // TODO: Билдер уйдет в DbQueryGenerator. StringBuilder builder = new StringBuilder(); builder.Append("SELECT [") .Append(column.Name) .Append("] FROM "); if (!String.IsNullOrEmpty(type.Schema)) { builder.Append('[').Append(type.Schema).Append("]."); } builder.Append('[').Append(type.Table) .Append("] WHERE "); ValueDictionary arguments = new ValueDictionary(); foreach (MetaMember key in type.Keys) { string memberKey = key.GetMemberKey(); builder.Append('[').Append(memberKey).AppendFormat("] = @{0}", memberKey).Append(" AND "); arguments[memberKey] = source.GetValue <object>(memberKey); } builder.Length -= 5; return(new ScalarMappedAssociationLoader <TAssociation>( new DbCommandDescriptor(builder.ToString(), arguments), column.Binder)); }
private IRouteTableProvider CreateRouteTableProvider() { if (Provider == null) { return(null); } Type providerType = Type.GetType(Provider.Type, false, true); if (providerType == null) { return(null); } if (!typeof(IRouteTableProvider).IsAssignableFrom(providerType)) { throw Error.IncompatibleRouteTableProvider(providerType); } IRouteTableProvider provider = (IRouteTableProvider)ServiceLocator.Instance.GetService(providerType); ValueDictionary settings = new ValueDictionary(); foreach (string key in Provider.Settings.AllKeys) { settings.Add(key, Provider.Settings[key].Value); } provider.Init(settings); return(provider); }
/// <summary> /// Gets the appropriate <see cref="VirtualPathData"/> for /// the provided route <paramref name="key"/> and <paramref name="values"/>, /// or <value>null</value>, if no matching route found. /// </summary> /// <param name="context">The context of the current request.</param> /// <param name="key">The key of the route to use.</param> /// <param name="values">The <see cref="ValueDictionary"/> /// containing the route parameter values.</param> public virtual VirtualPathData GetVirtualPath(RequestContext context, string key, ValueDictionary values) { Precondition.Require(context, () => Error.ArgumentNull("context")); Precondition.Require(values, () => Error.ArgumentNull("values")); if (String.IsNullOrEmpty(key)) { return(GetVirtualPath(context, values)); } RouteBase route = null; bool hasRoute = false; using (GetReadLock()) { hasRoute = _indexedRoutes.TryGetValue(key, out route); } if (hasRoute) { VirtualPathData vp = route.GetVirtualPath(context, values, Variables); if (vp != null) { return(vp); } } return(null); }
/// <summary> /// Convenience method used to generate a link /// using Routing to determine the virtual path. /// </summary> /// <param name="routeKey">The name of the route, if any.</param> /// <param name="action">The action with parameters.</param> /// <typeparam name="TController">The type of the controller.</typeparam> public virtual string Route <TController>(string routeKey, Expression <Action <TController> > action) where TController : IController { Precondition.Require(action, () => Error.ArgumentNull("action")); MethodCallExpression mexp = (action.Body as MethodCallExpression); if (mexp == null) { throw Error.ExpressionMustBeAMethodCall("action"); } if (mexp.Object != action.Parameters[0]) { throw Error.MethodCallMustTargetLambdaArgument("action"); } string actionName = ActionMethodSelector.GetNameOrAlias(mexp.Method); string controllerName = typeof(TController).Name; ValueDictionary rvd = LinqHelper.ExtractArgumentsToDictionary(mexp); rvd = (rvd != null) ? rvd : new ValueDictionary(); return(HttpUtility.HtmlAttributeEncode(GenerateUrl(routeKey, controllerName, actionName, rvd))); }
public RouteVariableAssigner(IValueSet variables) { Precondition.Require(variables, () => Error.ArgumentNull("variables")); _variables = new ValueDictionary(variables); }
/// <summary> /// Initializes a new instance of the /// <see cref="RouteCollection"/> class /// </summary> public RouteCollection() { _variables = new ValueDictionary(); _indexedRoutes = new Dictionary <string, RouteBase>(); _nonIndexedRoutes = new List <RouteBase>(); _lock = new ReaderWriterLock(); }
protected ActionResult Route <TController>(string routeName, Expression <Action <TController> > action, string suffix) where TController : IController { Precondition.Require(action, () => Error.ArgumentNull("action")); MethodCallExpression mexp = (action.Body as MethodCallExpression); if (mexp == null) { throw Error.ExpressionMustBeAMethodCall("action"); } if (mexp.Object != action.Parameters[0]) { throw Error.MethodCallMustTargetLambdaArgument("action"); } ValueDictionary values = LinqHelper.ExtractArgumentsToDictionary(mexp); values = (values != null) ? values : new ValueDictionary(); values["controller"] = typeof(TController).Name; values["action"] = ActionMethodSelector.GetNameOrAlias(mexp.Method); return(Route(routeName, values, suffix)); }
public static IAssociationLoader <IEnumerable <TAssociation> > Multiple <TAssociation>(MetaAssociation association, IValueSet source) { // Gonna move to DbQueryGenerator MetaType otherType = Configuration.Instance.Factory.CreateMapping(typeof(TAssociation)); StringBuilder builder = new StringBuilder(); builder.Append("SELECT "); foreach (MetaMember member in otherType.Members) { builder.Append('[').Append(member.GetMemberKey()).Append("],"); } builder.Length--; builder.Append(" FROM "); if (!String.IsNullOrEmpty(otherType.Schema)) { builder.Append('[').Append(otherType.Schema).Append("]."); } builder.Append('[').Append(otherType.Table).Append("] WHERE [") .Append(association.OtherKey).Append("]=@").Append(association.OtherKey); ValueDictionary arguments = new ValueDictionary(); arguments.Add(association.OtherKey, source.GetValue <object>(association.ThisKey)); return(new MultipleMappedAssociationLoader <TAssociation>(new DbCommandDescriptor(builder.ToString(), arguments))); }
private static string InputBuilder(HtmlControlHelper helper, string type, string name, object value, IDictionary <string, object> attributes) { if (attributes == null) { attributes = new ValueDictionary(); } if (value == null) { attributes.Remove("value"); } HtmlElementBuilder htb = new HtmlElementBuilder("input"); htb.Attributes.Merge(attributes, true); htb.Attributes.Merge("name", name, true); htb.Attributes.Merge("type", type, true); if (value != null) { htb.Attributes.Merge("value", value, true); } return(htb.ToString()); }
protected virtual void Include(string controllerName, string actionName, ValueDictionary arguments) { IControllerFactory factory = ControllerBuilder.Instance.GetControllerFactory(); IController controller = null; try { controller = factory.CreateController(Context, controllerName); Controller c = (controller as Controller); Precondition.Require(c, () => Error.TargetMustSubclassController(controllerName)); using (ChildContextOperator child = c.InitializeChildRequest(Context)) { if (!c.ActionExecutor.InvokeAction(c.Context, actionName, arguments)) { c.HandleUnknownAction(actionName); } } } catch (HttpException ex) { if (ex.GetHttpCode() == 500) { throw; } throw Error.ChildRequestExecutionError(ex); } finally { factory.ReleaseController(controller); } }
public static string CheckBox(this HtmlControlHelper helper, string name, object value, bool isChecked, IDictionary <string, object> attributes) { Precondition.Defined(name, () => Error.ArgumentNull("name")); if (attributes == null) { attributes = new ValueDictionary(); } if (helper.DataSource.Keys.Any(k => k.Equals(name, StringComparison.OrdinalIgnoreCase)) || helper.DataSource.Keys.Any()) { isChecked = helper.DataSource.GetValue <bool>(name); } if (isChecked) { attributes["checked"] = "checked"; } else { attributes.Remove("checked"); } return(InputBuilder(helper, "checkbox", name, value, attributes)); }
public void NegativeIndicesSerializationRegressionTest() { var vd = new ValueDictionary <bool>(true); vd[0] = true; vd[1] = true; vd[-1] = true; Assert.AreEqual(1, vd.NegativeIndices.Count); var txtFile = Path.GetTempFileName(); //vd.Save(txtFile); FileUtil.WriteToXmlFile(vd, txtFile); //var vd2 = ValueDictionary<bool>.Load(txtFile); var vd2 = FileUtil.ReadFromXmlFile <ValueDictionary <bool> >(txtFile); Assert.AreEqual(1, vd2.NegativeIndices.Count); var xmlFile = Path.GetTempFileName(); FileUtil.WriteToXmlFile(vd, xmlFile); var vd3 = FileUtil.ReadFromXmlFile <ValueDictionary <bool> >(xmlFile); Assert.AreEqual(1, vd3.NegativeIndices.Count); }
public static string RadioButton(this HtmlControlHelper helper, string name, object value, bool isChecked, IDictionary <string, object> attributes) { Precondition.Defined(name, () => Error.ArgumentNull("name")); if (attributes == null) { attributes = new ValueDictionary(); } if (helper.DataSource.Keys.Any(k => k.Equals(name, StringComparison.OrdinalIgnoreCase))) { string providedValue = Convert.ToString(value, CultureInfo.InvariantCulture); string actualValue = helper.DataSource.GetValue <string>(name); isChecked = (!String.IsNullOrEmpty(actualValue) && String.Equals(providedValue, actualValue, StringComparison.OrdinalIgnoreCase)); } if (isChecked) { attributes["checked"] = "checked"; } else { attributes.Remove("checked"); } return(InputBuilder(helper, "radio", name, value, attributes)); }
private ValueDictionary parseBEncodeDict(MemoryStream responseStream) { ValueDictionary dictionary = null; if ((this._contentEncoding == "gzip") || (this._contentEncoding == "x-gzip")) { GZipStream d = new GZipStream(responseStream, CompressionMode.Decompress); try { dictionary = (ValueDictionary)BEncode.Parse(d); } catch (Exception) { } return(dictionary); } try { dictionary = (ValueDictionary)BEncode.Parse(responseStream); } catch (Exception exception) { Console.Write(exception.StackTrace); } return(dictionary); }
/// <summary> /// Initializes a new instance of /// the <see cref="RouteData"/> class /// </summary> /// <param name="route">The currently executed route</param> /// <param name="handler">The <see cref="IRouteHandler"/> used /// to handle the request</param> public RouteData(RouteBase route, IRouteHandler handler) { _values = new ValueDictionary(); _tokens = new ValueDictionary(); _route = route; _handler = handler; }
private static ValueDictionary CreateDefaults(IValueSet defaults) { ValueDictionary values = new ValueDictionary(defaults); values.Remove("controller"); values.Remove("action"); return values; }
protected virtual bool Match(HttpContextBase context, Route route, ValueDictionary values, RouteDirection direction) { Precondition.Require(values, () => Error.ArgumentNull("values")); string value = values.GetValue<string>(_parameterName) ?? String.Empty; return _pattern.IsMatch(value); }
private static void VisitVariable(VariableSubsegment segment, ValueDictionary variables) { object value; if (!variables.TryGetValue(segment.VariableName, out value)) throw Error.UndefinedRouteVariable(segment.VariableName); segment.Value = value; }
public void RenderAction(ControllerContext context, string controllerName, string actionName, ValueDictionary arguments) { Precondition.Require(context, () => Error.ArgumentNull("context")); Initialize(context); Include(controllerName, actionName, arguments); }
public WebFormRoute(string url, string virtualPath, ValueDictionary defaults, IEnumerable <IRouteConstraint> constraints, ValueDictionary tokens) : base(url, defaults, constraints, tokens, new WebFormRoutingHandler(virtualPath)) { }
public WebFormRoute(string url, string virtualPath, ValueDictionary defaults, IEnumerable<IRouteConstraint> constraints, ValueDictionary tokens) : base(url, defaults, constraints, tokens, new WebFormRoutingHandler(virtualPath)) { }
private static ValueDictionary CreateKeyBindingData(string keyName, object keyValue) { ValueDictionary values = new ValueDictionary(); values[keyName] = keyValue; return(values); }
protected virtual bool Match(HttpContextBase context, Route route, ValueDictionary values, RouteDirection direction) { if (direction == RouteDirection.UrlGeneration) return true; Precondition.Require(context, () => Error.ArgumentNull("context")); return ((context.Request.HttpMethod & _methods) > 0); }
public HttpStatusResult(int statusCode, string message, IValueSet headers) { Precondition.Require(statusCode > 0, () => Error.ArgumentOutOfRange("statusCode")); _statusCode = statusCode; _message = message; _headers = new ValueDictionary(headers); }
protected virtual bool Match(HttpContextBase context, Route route, ValueDictionary values, RouteDirection direction) { Precondition.Require(values, () => Error.ArgumentNull("values")); string value = values.GetValue <string>(_parameterName) ?? String.Empty; return(_pattern.IsMatch(value)); }
private static ValueDictionary CreateDefaults(IValueSet defaults) { ValueDictionary values = new ValueDictionary(defaults); values.Remove("controller"); values.Remove("action"); return(values); }
public DictionaryValueProvider(IValueSet values, CultureInfo culture) : base(culture) { _values = new ValueDictionary(values); _prefixes = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string key in _values.Keys) _prefixes.UnionWith(GetPrefixes(key)); }
private static bool IsParameterRequired(ParameterSubsegment segment, ValueDictionary defaults, out object value) { value = null; if (segment.IsCatchAll) return false; return !(defaults.TryGetValue(segment.ParameterName, out value)); }
/// <summary> /// Convenience method used to generate a link /// using Routing to determine the virtual path. /// </summary> /// <param name="routeKey">The name of the route, if any.</param> /// <param name="controller">The name of the controller.</param> /// <param name="action">The name of the action.</param> /// <param name="values">The route values.</param> public virtual string Route(string routeKey, string controller, string action, ValueDictionary values) { if (values == null) { values = new ValueDictionary(); } return(HttpUtility.HtmlAttributeEncode(GenerateUrl(routeKey, controller, action, values))); }
public void ConstructorTest() { var vd = new ValueDictionary<bool>(true); Assert.IsTrue(vd.DefaultReturn); vd = new ValueDictionary<bool>(false); Assert.IsFalse(vd.DefaultReturn); var vd2 = new ValueDictionary<DateTime>(new DateTime(1983, 4, 5)); Assert.AreEqual(new DateTime(1983, 4, 5), vd2.DefaultReturn); }
private static XmlElement AppendChild(this XmlElement element, string name, object attributes) { XmlElement child = AppendChild(element, name); ValueDictionary values = new ValueDictionary(attributes); foreach (KeyValuePair<string, object> pair in values) child.SetAttribute(pair.Key.ToLower(), (pair.Value == null) ? String.Empty : pair.Value.ToString()); return child; }
/// <summary> /// Initializes a new instance of the /// <see cref="Route"/> class /// </summary> /// <param name="url">The pattern of the URL to route</param> /// <param name="defaults">Dictionary, containing default values of route /// parameters</param> /// <param name="constraints">Collection of route constraints</param> /// <param name="tokens">Dictionary, containing additional route data</param> /// <param name="handler">The <see cref="IRouteHandler"/>, which is used /// to handle a request</param> public Route(string url, ValueDictionary defaults, IEnumerable<IRouteConstraint> constraints, ValueDictionary tokens, IRouteHandler handler) { _defaults = defaults; _constraints = (constraints == null) ? null : new List<IRouteConstraint>(constraints); _handler = handler; _tokens = tokens; Url = url; }
public DictionaryValueProvider(IValueSet values, CultureInfo culture) : base(culture) { _values = new ValueDictionary(values); _prefixes = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (string key in _values.Keys) { _prefixes.UnionWith(GetPrefixes(key)); } }
private static void VisitComposite(CompositeSubsegment segment, ValueDictionary variables) { foreach (LiteralSubsegment subsegment in segment.Segments) { VariableSubsegment variable = (subsegment as VariableSubsegment); if (variable == null) continue; VisitVariable(variable, variables); } }
protected BaseEnum(TKey key, TValue value) { if (key == null || value == null) { throw new ArgumentNullException(); } Value = value; Key = key; KeyDictionary.Add(key, this); ValueDictionary.Add(value, this); }
public void Constructor_ObjectProvided_CreatesDictionary() { // Arrange // Act var dictionary = new ValueDictionary(new { id = 1, name = "marina" }); // Assert Assert.That(dictionary["id"], Is.EqualTo(1)); Assert.That(dictionary["name"], Is.EqualTo("marina")); }
private static void VisitVariable(VariableSubsegment segment, ValueDictionary variables) { object value; if (!variables.TryGetValue(segment.VariableName, out value)) { throw Error.UndefinedRouteVariable(segment.VariableName); } segment.Value = value; }
public override bool TryGetMember(GetMemberBinder binder, out object result) { T val; result = null; if (ValueDictionary.TryGetValue(binder.Name, out val)) { result = val; return(true); } return(false); }
protected virtual bool Match(HttpContextBase context, Route route, ValueDictionary values, RouteDirection direction) { if (direction == RouteDirection.UrlGeneration) { return(true); } Precondition.Require(context, () => Error.ArgumentNull("context")); return((context.Request.HttpMethod & _methods) > 0); }
/// <summary> /// Initializes a new instance of the /// <see cref="Route"/> class /// </summary> /// <param name="url">The pattern of the URL to route</param> /// <param name="defaults">Dictionary, containing default values of route /// parameters</param> /// <param name="constraints">Collection of route constraints</param> /// <param name="tokens">Dictionary, containing additional route data</param> /// <param name="handler">The <see cref="IRouteHandler"/>, which is used /// to handle a request</param> public Route(string url, ValueDictionary defaults, IEnumerable <IRouteConstraint> constraints, ValueDictionary tokens, IRouteHandler handler) { _defaults = defaults; _constraints = (constraints == null) ? null : new List <IRouteConstraint>(constraints); _handler = handler; _tokens = tokens; Url = url; }
public RouteDefinition(string name, Route route) { Precondition.Defined(name, () => Error.ArgumentNull("name")); Precondition.Require(route, () => Error.ArgumentNull("route")); _name = name; _route = route; _url = route.Url; _defaults = CreateDefaults(route.Defaults); _constraints = new List<RouteConstraintDefinition>(); }
private static IValueSet BindDataSource(IValueProvider provider) { ValueDictionary values = new ValueDictionary(); foreach (string key in provider.Keys) { ValueProviderResult result = provider.GetValue(key); if (result == null) continue; values.Add(key, result.Value); } return values; }
private static void VisitSegment(ContentSegment segment, ValueDictionary variables) { foreach (PathSubsegment subsegment in segment.Segments) { VariableSubsegment variable = (subsegment as VariableSubsegment); CompositeSubsegment composite = (subsegment as CompositeSubsegment); if (variable != null) VisitVariable(variable, variables); else if (composite != null) VisitComposite(composite, variables); } }
public static void Assign(ParsedRoute route, ValueDictionary variables) { Precondition.Require(route, () => Error.ArgumentNull("route")); Precondition.Require(variables, () => Error.ArgumentNull("variables")); foreach (PathSegment segment in route.Segments) { ContentSegment content = (segment as ContentSegment); if (content == null) continue; VisitSegment(content, variables); } }
private static ValueDictionary Deserialize (string input) { try { ValueDictionary data = new ValueDictionary (); JavaScriptSerializer serializer = new JavaScriptSerializer (); object value = serializer.DeserializeObject (input); AppendBindingData (data, String.Empty, value); return data; } catch { return null; } }
public void AllowDefaultReturnsTest() { var vd = new ValueDictionary<bool>(); Assert.IsFalse(vd[0]); vd.AllowDefaultReturns = false; bool error = false; try { Assert.IsFalse(vd[0]); Assert.IsFalse(vd[1]); } catch { error = true; } Assert.IsTrue(error); }
public void ValueDictionaryTest() { var graph = new ValueDictionary { Test = new Dictionary<string, int> { {"Test1", 1}, {"Test2", 2}, {"Test3", 3}, } }; var context = new SerializationTestContext(); var actual = context.SerializeAndDeserialize(graph); Assert.IsNotNull(actual); Assert.IsNotNull(actual.Test); Assert.AreEqual(3, actual.Test.Count); Assert.IsTrue(graph.Test.SequenceEqual(actual.Test, new ValueDictionaryComparer())); }
public void NegativeIndicesSerializationRegressionTest() { var vd = new ValueDictionary<bool>(true); vd[0] = true; vd[1] = true; vd[-1] = true; Assert.AreEqual(1, vd.NegativeIndices.Count); var txtFile = Path.GetTempFileName(); //vd.Save(txtFile); FileUtil.WriteToXmlFile(vd, txtFile); //var vd2 = ValueDictionary<bool>.Load(txtFile); var vd2 = FileUtil.ReadFromXmlFile<ValueDictionary<bool>>(txtFile); Assert.AreEqual(1, vd2.NegativeIndices.Count); var xmlFile = Path.GetTempFileName(); FileUtil.WriteToXmlFile(vd, xmlFile); var vd3 = FileUtil.ReadFromXmlFile<ValueDictionary<bool>>(xmlFile); Assert.AreEqual(1, vd3.NegativeIndices.Count); }
public void SgmlTest1(HtmlProcessor filter, string blog, int topic) { ValueDictionary parameters = new ValueDictionary(); parameters["link-domain"] = "starcafe.ru"; parameters["link-redirect"] = "http://starcafe.ru/redirect"; parameters["url"] = String.Format("http://starcafe.ru/blog/{0}/{1}.html", blog, topic); using (StreamReader sr = new StreamReader( Path.Combine(Environment.CurrentDirectory, "sgml-test.htm"), Encoding.UTF8)) { using (StreamWriter sw = new StreamWriter(Path.Combine(Environment.CurrentDirectory, String.Format("html-test-{0}-{1}.htm", blog, topic)), false, Encoding.UTF8)) { sw.Write(filter.Execute(sr, parameters)); } } }
public RouteConfigurationElement() : base() { _attributes = new ValueDictionary(); }
public BoundUrl Bind(ValueDictionary currentValues, ValueDictionary values, ValueDictionary variables, ValueDictionary defaults) { currentValues = currentValues ?? new ValueDictionary(); values = values ?? new ValueDictionary(); variables = variables ?? new ValueDictionary(); defaults = defaults ?? new ValueDictionary(); ValueDictionary acceptedValues = new ValueDictionary(); HashSet<string> unusedValues = new HashSet<string>( values.Keys, StringComparer.OrdinalIgnoreCase); AssignVariableValues(variables); ForEachParameter(_segments, segment => { object value; object currentValue; string parameterName = segment.ParameterName; bool hasValue = values.TryGetValue(parameterName, out value); if (hasValue) unusedValues.Remove(parameterName); bool hasCurrentValue = currentValues.TryGetValue(parameterName, out currentValue); if (hasValue && hasCurrentValue && !RoutePartsEqual(currentValue, value)) return false; if (hasValue) { if (IsRoutePartNonEmpty(value)) acceptedValues.Add(parameterName, value); } else if (hasCurrentValue) acceptedValues.Add(parameterName, currentValue); return true; }); foreach (KeyValuePair<string, object> kvp in values) { if (IsRoutePartNonEmpty(kvp.Value) && !acceptedValues.ContainsKey(kvp.Key)) acceptedValues.Add(kvp.Key, kvp.Value); } foreach (KeyValuePair<string, object> kvp in currentValues) { if (!acceptedValues.ContainsKey(kvp.Key) && GetParameterSubsegment(_segments, kvp.Key) == null) acceptedValues.Add(kvp.Key, kvp.Value); } ForEachParameter(_segments, segment => { object value; if (!acceptedValues.ContainsKey(segment.ParameterName) && !IsParameterRequired(segment, defaults, out value)) acceptedValues.Add(segment.ParameterName, value); return true; }); if (!ForEachParameter(_segments, segment => { object value; if (IsParameterRequired(segment, defaults, out value) && !acceptedValues.ContainsKey(segment.ParameterName)) return false; return true; })) { return null; } ValueDictionary others = new ValueDictionary( (IDictionary<string, object>)defaults); ForEachParameter(_segments, segment => { others.Remove(segment.ParameterName); return true; }); foreach (KeyValuePair<string, object> kvp in others) { object value; if (values.TryGetValue(kvp.Key, out value)) { unusedValues.Remove(kvp.Key); if (!RoutePartsEqual(value, kvp.Value)) return null; } } return BuildUrl(defaults, acceptedValues, unusedValues); }
private BoundUrl BuildUrl(ValueDictionary defaults, ValueDictionary acceptedValues, HashSet<string> unusedValues) { StringBuilder pathBuilder = new StringBuilder(); StringBuilder segmentBuilder = new StringBuilder(); bool flush = false; foreach (PathSegment segment in _segments) { SeparatorSegment separator = (segment as SeparatorSegment); ContentSegment content = (segment as ContentSegment); if (separator != null) { if (flush && segmentBuilder.Length > 0) { pathBuilder.Append(segmentBuilder.ToString()); segmentBuilder.Length = 0; } flush = false; segmentBuilder.Append(RouteParser.PathSeparator); } if (content != null) { bool segmentEnd = false; foreach (PathSubsegment subsegment in content.Segments) { LiteralSubsegment literal = (subsegment as LiteralSubsegment); ParameterSubsegment parameter = (subsegment as ParameterSubsegment); if (literal != null) { flush = true; segmentBuilder.Append(Uri.EscapeUriString(literal.Literal)); } if(parameter != null) { object acceptedValue; object defaultValue; if (flush && segmentBuilder.Length > 0) { pathBuilder.Append(segmentBuilder.ToString()); segmentBuilder.Length = 0; segmentEnd = true; } flush = false; if (acceptedValues.TryGetValue(parameter.ParameterName, out acceptedValue)) unusedValues.Remove(parameter.ParameterName); defaults.TryGetValue(parameter.ParameterName, out defaultValue); if (RoutePartsEqual(acceptedValue, defaultValue)) { segmentBuilder.Append(Uri.EscapeUriString( Convert.ToString(acceptedValue, CultureInfo.InvariantCulture))); continue; } if (segmentBuilder.Length > 0) { pathBuilder.Append(segmentBuilder.ToString()); segmentBuilder.Length = 0; } pathBuilder.Append(Uri.EscapeUriString(Convert.ToString(acceptedValue, CultureInfo.InvariantCulture))); segmentEnd = true; } } if (segmentEnd && segmentBuilder.Length > 0) { pathBuilder.Append(segmentBuilder.ToString()); segmentBuilder.Length = 0; } } } if (flush && segmentBuilder.Length > 0) pathBuilder.Append(segmentBuilder.ToString()); if (unusedValues.Count > 0) { bool isFirst = true; foreach (string key in unusedValues) { object value; if (acceptedValues.TryGetValue(key, out value)) { pathBuilder.Append(isFirst ? '?' : '&'); isFirst = false; pathBuilder.Append(Uri.EscapeDataString(key.ToLowerInvariant())); pathBuilder.Append('='); pathBuilder.Append(Uri.EscapeDataString( Convert.ToString(value, CultureInfo.InvariantCulture))); } } } return new BoundUrl(pathBuilder.ToString(), acceptedValues); }
private bool MatchContent(ContentSegment segment, string pathSegment, ValueDictionary defaults, ValueDictionary matchedValues) { if (String.IsNullOrEmpty(pathSegment)) { if (segment.Segments.Count > 0) { object value; ParameterSubsegment ps = (segment.Segments.FirstOrDefault( s => (s is ParameterSubsegment)) as ParameterSubsegment); if (ps == null) return false; if (defaults.TryGetValue(ps.ParameterName, out value)) { matchedValues.Add(ps.ParameterName, value); return true; } } return false; } int segmentLength = pathSegment.Length; int segmentIndex = (segment.Segments.Count - 1); ParameterSubsegment lastParameter = null; LiteralSubsegment lastLiteral = null; while (segmentIndex >= 0) { int index = segmentLength; ParameterSubsegment parameter = (segment.Segments[segmentIndex] as ParameterSubsegment); LiteralSubsegment literal = (segment.Segments[segmentIndex] as LiteralSubsegment); if (parameter != null) lastParameter = parameter; if (literal != null) { lastLiteral = literal; int literalIndex = pathSegment.LastIndexOf(literal.Literal, segmentLength - 1, StringComparison.OrdinalIgnoreCase); if (literalIndex == -1) return false; if ((segmentIndex == segment.Segments.Count - 1) && ((literalIndex + literal.Literal.Length) != pathSegment.Length)) return false; index = literalIndex; } if (lastParameter != null && ((lastLiteral != null && parameter == null) || segmentIndex == 0)) { int startIndex; int lastIndex; if (lastLiteral == null) { startIndex = (segmentIndex == 0) ? 0 : index + lastLiteral.Literal.Length; lastIndex = segmentLength; } else if (segmentIndex == 0 && parameter != null) { startIndex = 0; lastIndex = segmentLength; } else { startIndex = index + lastLiteral.Literal.Length; lastIndex = segmentLength - startIndex; } string part = pathSegment.Substring(startIndex, lastIndex); if (String.IsNullOrEmpty(part)) return false; matchedValues.Add(lastParameter.ParameterName, part); lastParameter = null; lastLiteral = null; } segmentLength = index; segmentIndex--; } if (segmentLength != 0) return (segment.Segments[0] is ParameterSubsegment); return true; }
private void MatchCatchAll(ContentSegment segment, IEnumerable<string> remainingSegments, ValueDictionary defaults, ValueDictionary matchedValues) { object value; string remainingPart = String.Join(String.Empty, remainingSegments.ToArray()); ParameterSubsegment parameter = (segment.Segments.FirstOrDefault() as ParameterSubsegment); if (remainingPart.Length > 0) value = remainingPart; else defaults.TryGetValue(parameter.ParameterName, out value); matchedValues.Add(parameter.ParameterName, value); }
public ValueDictionary Match(string virtualPath, ValueDictionary variables, ValueDictionary defaults) { List<string> parts = new List<string>(RouteParser.SplitUrl(virtualPath)); defaults = defaults ?? new ValueDictionary(); variables = variables ?? new ValueDictionary(); ValueDictionary values = new ValueDictionary(); bool hasAdditionalParameters = false; bool isCatchAll = false; AssignVariableValues(variables); for (int i = 0; i < _segments.Count; i++) { SeparatorSegment separator = (_segments[i] as SeparatorSegment); ContentSegment content = (_segments[i] as ContentSegment); if (parts.Count <= i) hasAdditionalParameters = true; string part = (hasAdditionalParameters) ? null : parts[i]; if (separator != null) { if (!hasAdditionalParameters && !RouteParser.IsSeparator(part)) return null; } if (content != null) { if (content.IsCatchAll) { MatchCatchAll(content, parts.Skip(i), defaults, values); isCatchAll = true; } else if (!MatchContent(content, part, defaults, values)) return null; } } if (!isCatchAll && _segments.Count < parts.Count) { for (int j = _segments.Count; j < parts.Count; j++) { if (!RouteParser.IsSeparator(parts[j])) return null; } } if (defaults != null) { foreach (KeyValuePair<string, object> kvp in defaults) { if (!values.ContainsKey(kvp.Key)) values.Add(kvp.Key, kvp.Value); } } return values; }
private void AssignVariableValues(ValueDictionary variables) { // Check if the values were changed int fingerprint = CalculateFingerprint(variables); if (fingerprint == _variableFingerprint) return; RouteVariableAssigner.Assign(this, variables); _variableFingerprint = fingerprint; }
private static int CalculateFingerprint(ValueDictionary values) { int hash = -1; foreach (KeyValuePair<string, object> pair in values) { int keyCode = (pair.Key == null) ? -1 : pair.Key.GetHashCode(); int valueCode = (pair.Value == null) ? -1 : pair.Value.GetHashCode(); hash = CombineHashCodes(hash, CombineHashCodes(keyCode, valueCode)); } return hash; }