public void ContainsKeyFailsWithNullCollection() { var e = Assert.Throws <ArgumentNullException>(() => NameValueCollectionExtensions.ContainsKey(null, null)); Assert.Equal("collection", e.ParamName); }
public S3Reader(NameValueCollection args) { var S3Config = new AmazonS3Config(); buckets = args["buckets"]; vpath = args["prefix"]; asVpp = NameValueCollectionExtensions.Get(args, "vpp", true); S3Config.CommunicationProtocol = NameValueCollectionExtensions.Get(args, "useSsl", false) ? Amazon.S3.Model.Protocol.HTTPS : Amazon.S3.Model.Protocol.HTTP; S3Config.UseSecureStringForAwsSecretKey = false; if (!string.IsNullOrEmpty(args["accessKeyId"]) && !string.IsNullOrEmpty(args["secretAccessKey"])) { S3Client = new AmazonS3Client(args["accessKeyId"], args["secretAccessKey"], S3Config); } else { S3Client = new AmazonS3Client(null, S3Config); } includeModifiedDate = NameValueCollectionExtensions.Get(args, "includeModifiedDate", includeModifiedDate); includeModifiedDate = NameValueCollectionExtensions.Get(args, "checkForModifiedFiles", includeModifiedDate); RequireImageExtension = NameValueCollectionExtensions.Get(args, "requireImageExtension", RequireImageExtension); UntrustedData = NameValueCollectionExtensions.Get(args, "untrustedData", UntrustedData); CacheUnmodifiedFiles = NameValueCollectionExtensions.Get(args, "cacheUnmodifiedFiles", CacheUnmodifiedFiles); }
public void UpdateFailsWithNullThis() { var e = Assert.Throws <ArgumentNullException>(() => NameValueCollectionExtensions.Update(null, new NameValueCollection())); Assert.Equal("collection", e.ParamName); }
public void AsEnumerableFailsWithNullThis() { var e = Assert.Throws <ArgumentNullException>(() => NameValueCollectionExtensions.AsEnumerable(null)); Assert.Equal("collection", e.ParamName); }
public SqlReaderSettings(System.Collections.Specialized.NameValueCollection args) { if (!string.IsNullOrEmpty(args["prefix"])) { this.PathPrefix = args["prefix"]; } if (!string.IsNullOrEmpty(args["connectionString"])) { this.ConnectionString = args["connectionString"]; } this.ImageIdType = NameValueCollectionExtensions.Get(args, "idType", this.ImageIdType); if (!string.IsNullOrEmpty(args["blobQuery"])) { this.ImageBlobQuery = args["blobQuery"]; } if (!string.IsNullOrEmpty(args["existsQuery"])) { this.ImageExistsQuery = args["existsQuery"]; } if (!string.IsNullOrEmpty(args["modifiedQuery"])) { this.ModifiedDateQuery = args["modifiedQuery"]; } StripFileExtension = !NameValueCollectionExtensions.Get(args, "extensionPartOfId", false); RegisterAsVirtualPathProvider = NameValueCollectionExtensions.Get(args, "vpp", true); RequireImageExtension = NameValueCollectionExtensions.Get(args, "requireImageExtension", RequireImageExtension); UntrustedData = NameValueCollectionExtensions.Get(args, "untrustedData", UntrustedData); CacheUnmodifiedFiles = NameValueCollectionExtensions.Get(args, "cacheUnmodifiedFiles", CacheUnmodifiedFiles); CheckForModifiedFiles = NameValueCollectionExtensions.Get(args, "checkForModifiedFiles", true); QueriesAreStoredProcedures = NameValueCollectionExtensions.Get(args, "queriesAreStoredProcedures", false); }
public S3Reader2(NameValueCollection args) { s3config = new AmazonS3Config(); buckets = args["buckets"]; vpath = args["prefix"]; asVpp = NameValueCollectionExtensions.Get(args, "vpp", true); Region = args["region"] ?? "us-east-1"; s3config.UseHttp = !NameValueCollectionExtensions.Get(args, "useSsl", false); if (!string.IsNullOrEmpty(args["accessKeyId"]) && !string.IsNullOrEmpty(args["secretAccessKey"])) { S3Client = new AmazonS3Client(args["accessKeyId"], args["secretAccessKey"], s3config); } else { S3Client = new AmazonS3Client(null, s3config); } includeModifiedDate = NameValueCollectionExtensions.Get(args, "includeModifiedDate", includeModifiedDate); includeModifiedDate = NameValueCollectionExtensions.Get(args, "checkForModifiedFiles", includeModifiedDate); RequireImageExtension = NameValueCollectionExtensions.Get(args, "requireImageExtension", RequireImageExtension); UntrustedData = NameValueCollectionExtensions.Get(args, "untrustedData", UntrustedData); CacheUnmodifiedFiles = NameValueCollectionExtensions.Get(args, "cacheUnmodifiedFiles", CacheUnmodifiedFiles); }
public IMultiPartBodyBuilder WithFormData(object parameters) { NameValueCollection collection = NameValueCollectionExtensions.CreateNameValueCollection(parameters); formData.Add(collection); return(this); }
public VirtualFolder(NameValueCollection args) : base() { this.VirtualPath = args["virtualPath"]; this.PhysicalPath = args["physicalPath"]; this.RegisterAsVpp = NameValueCollectionExtensions.Get(args, "vpp", true); }
protected override RequestedAction Render(ImageState s) { bool detect = NameValueCollectionExtensions.Get(s.settings, "f.detect", false); bool getlayout = NameValueCollectionExtensions.Get(s.settings, "f.getlayout", false); if (!detect && !getlayout) { return(RequestedAction.None); } var d = new DetectionResponse <Face>(); try { //Only detect faces if it was requested. if (detect) { using (var detector = ConfigureDetection(s.settings)) d.features = detector.DetectFeatures(s.sourceBitmap); } } catch (TypeInitializationException e) { throw e; } catch (Exception e) { d.message = e.Message; } d.PopulateFrom(s); throw d.GetResponseException(s.settings["callback"]); }
public void CopyToWithNullCollectionThrows() { ExceptionHelper.ExpectArgumentNullException( delegate { NameValueCollectionExtensions.CopyTo(null /* collection */, null /* destination */); }, "collection"); }
/// <summary> /// This is where we hijack the resizing process, interrupt it, and send back the json data we created. /// </summary> /// <param name="sender"></param> /// <param name="context"></param> /// <param name="e"></param> void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e) { if (NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "r.detecteyes", false) || NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "r.getlayout", false)) { DetectionResponse <ObjRect> .InjectExceptionHandler(e as ResponseArgs); } }
private bool IsWhitelisted(RemoteRequestEventArgs request) { var rr = c.getNode("remotereader"); var domain = new Uri(request.RemoteUrl).Host; if (rr == null || string.IsNullOrEmpty(domain)) { return(false); } foreach (Node n in rr.childrenByName("allow")) { bool onlyWhenSigned = NameValueCollectionExtensions.Get(n.Attrs, "onlyWhenSigned", false); if (onlyWhenSigned && !request.SignedRequest) { continue; } bool hostMatches = false, regexMatches = false; string host = n.Attrs.Get("domain"); if (!string.IsNullOrEmpty(host)) { if (host.StartsWith("*.", StringComparison.OrdinalIgnoreCase)) { hostMatches = domain.EndsWith(host.Substring(1), StringComparison.OrdinalIgnoreCase); } else { hostMatches = domain.Equals(host, StringComparison.OrdinalIgnoreCase); } if (!hostMatches) { continue; //If any filter doesn't match, skip rule } } string regex = n.Attrs.Get("regex"); if (!string.IsNullOrEmpty(regex)) { var r = new Regex("^" + regex + "$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Singleline); regexMatches = r.IsMatch(request.RemoteUrl); if (!regexMatches) { continue; //If any filter doesn't match, skip rule } } //If all specified filters match, allow the request. //This *is* supposed to be || not &&, because we already deal with non-matching filters via 'continue'. if (hostMatches || regexMatches) { return(true); } } return(false); }
public void ToDictionary_003() { NameValueCollection target = null; var actual = NameValueCollectionExtensions.ToDictionary(target); Assert.IsNotNull(actual); Assert.IsInstanceOfType(actual, typeof(IDictionary <string, object>)); Assert.AreEqual(0, actual.Count); }
/// <summary> /// This is where we hijack the resizing process, interrupt it, and send back the json data we created. /// </summary> /// <param name="sender"></param> /// <param name="context"></param> /// <param name="e"></param> void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e) { bool detect = NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "f.detect", false); bool getlayout = NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "f.getlayout", false); if (!detect && !getlayout) { return; } DetectionResponse <Face> .InjectExceptionHandler(e as ResponseArgs); }
public static IRequestConfiguration WithUrlEncodedBody(this IRequestConfiguration configuration, object parameters) { if (configuration == null) { throw new ArgumentNullException("configuration"); } NameValueCollection collection = NameValueCollectionExtensions.CreateNameValueCollection(parameters); return(configuration .ConfigureRequest(r => r.ContentType = ContentType) .WithBodyBuilder(new UrlEncodedBodyBuilder(collection))); }
public void ToDictionary_001() { var target = new NameValueCollection(); target.Add("Key", "One"); var actual = NameValueCollectionExtensions.ToDictionary(target); Assert.IsInstanceOfType(actual, typeof(IDictionary <string, object>)); Assert.AreEqual(1, actual.Count); Assert.AreEqual("Key", actual.Keys.First()); Assert.AreEqual("One", actual["Key"]); }
public void CopyToWithNullCollectionThrows() { Assert.ThrowsArgumentNull( delegate { NameValueCollectionExtensions.CopyTo( null /* collection */ , null /* destination */ ); }, "collection" ); }
public TextLayer(NameValueCollection attrs) : base(attrs) { Text = attrs["text"]; Vertical = NameValueCollectionExtensions.Get(attrs, "vertical", false); TextColor = ParseUtils.ParseColor(attrs["color"], TextColor); OutlineColor = ParseUtils.ParseColor(attrs["outlineColor"], OutlineColor); GlowColor = ParseUtils.ParseColor(attrs["glowColor"], GlowColor); Font = attrs["font"]; Angle = NameValueCollectionExtensions.Get(attrs, "angle", Angle); FontSize = NameValueCollectionExtensions.Get(attrs, "fontSize", FontSize); Style = NameValueCollectionExtensions.Get(attrs, "style", this.Style); OutlineWidth = NameValueCollectionExtensions.Get(attrs, "outlineWidth", OutlineWidth); GlowWidth = NameValueCollectionExtensions.Get(attrs, "glowWidth", GlowWidth); Rendering = NameValueCollectionExtensions.Get(attrs, "rendering", this.Rendering); }
public Layer(NameValueCollection settings) { Top = DistanceUnit.TryParse(settings["top"]); Left = DistanceUnit.TryParse(settings["left"]); Bottom = DistanceUnit.TryParse(settings["bottom"]); Right = DistanceUnit.TryParse(settings["right"]); Width = DistanceUnit.TryParse(settings["width"]); Height = DistanceUnit.TryParse(settings["height"]); if (!string.IsNullOrEmpty(settings["relativeTo"])) { RelativeTo = settings["relativeTo"]; } DrawAs = NameValueCollectionExtensions.Get(settings, "drawAs", DrawAs); Align = NameValueCollectionExtensions.Get(settings, "align", Align); Fill = NameValueCollectionExtensions.Get(settings, "fill", false); }
public FaceDetection ConfigureDetection(NameValueCollection s) { var f = new FaceDetection(); //Parse min/max faces int[] count = NameValueCollectionExtensions.GetList <int>(s, "f.faces", null, 1, 2); if (count == null) { f.MinFaces = 1; f.MaxFaces = 8; } else if (count.Length > 0) { f.MinFaces = f.MaxFaces = count[0]; if (count.Length > 1) { f.MaxFaces = count[1]; } } //Parse min/default thresholds int[] threshold = NameValueCollectionExtensions.GetList <int>(s, "f.threshold", null, 1, 2); if (threshold != null && threshold.Length > 0) { f.MinConfidenceLevel = f.ConfidenceLevelThreshold = threshold[0]; if (threshold.Length > 1) { f.ConfidenceLevelThreshold = threshold[1]; } } //Parse min size percent f.MinSizePercent = NameValueCollectionExtensions.Get <float>(s, "f.minsize", f.MinSizePercent); //Parse expandsion rules double[] expand = NameValueCollectionExtensions.GetList <double>(s, "f.expand", null, 1, 2); //Exapnd bounding box by requested percentage if (expand != null) { f.ExpandX = expand[0]; f.ExpandY = expand.Length > 1 ? expand[1] : expand[0]; } return(f); }
void Pipeline_PostRewrite(IHttpModule sender, HttpContext context, Configuration.IUrlEventArgs e) { if (NameValueCollectionExtensions.Get(e.QueryString, "iefix", false) && NeedsPngFix(context) && DestFormatPng(e)) { if (Redirect) { //Get the original request URL, and change the 'format' setting to 'gif'. NameValueCollection newValues = new NameValueCollection(); newValues["format"] = "gif"; context.Response.Redirect(PathUtils.MergeOverwriteQueryString(context.Request.RawUrl, newValues), true); } else { e.QueryString["format"] = "gif"; } } e.QueryString.Remove("iefix"); }
protected override RequestedAction PostPrepareSourceBitmap(ImageState s) { if (s.sourceBitmap == null) { return(RequestedAction.None); } bool focusFaces = ("faces".Equals(s.settings["c.focus"], StringComparison.OrdinalIgnoreCase)); bool showFaces = "true".Equals(s.settings["f.show"], StringComparison.OrdinalIgnoreCase); List <Face> faces = null; //Perform face detection for either (or both) situations if (showFaces || focusFaces) { using (var detector = ConfigureDetection(s.settings)) { //Store faces s.Data["faces"] = faces = detector.DetectFeatures(s.sourceBitmap); } //Store points List <PointF> points = new List <PointF>(); foreach (Face r in faces) { points.Add(new PointF(r.X, r.Y)); points.Add(new PointF(r.X2, r.Y2)); } s.layout.AddInvisiblePolygon("faces", points.ToArray()); } //Capture and rewrite requests with &c.focus=faces if (focusFaces) { //Write the face points as focus values List <double> focusPoints = new List <double>(); foreach (Face r in faces) { focusPoints.Add(r.X); focusPoints.Add(r.Y); focusPoints.Add(r.X2); focusPoints.Add(r.Y2); } NameValueCollectionExtensions.SetList <double>(s.settings, "c.focus", focusPoints.ToArray(), false); } return(RequestedAction.None); }
protected override RequestedAction LayoutEffects(ImageState s) { float shadowWidth = s.settings.Get <float>("shadowWidth", 0); if (shadowWidth != 0) { var offset = NameValueCollectionExtensions.GetList <float>(s.settings, "shadowOffset", 0, 2); PointF shadowOffset = offset == null ? new PointF(0, 0) : new PointF(offset[0], offset[1]); //Clone last ring, then offset it - provides the inner bounds of the shadow later s.layout.AddInvisiblePolygon("shadowInner", PolygonMath.MovePoly(s.layout.LastRing.points, shadowOffset)); //Determine the outer bound of the shadow s.layout.AddRing("shadow", PolygonMath.InflatePoly(s.layout.LastRing.points, new float[] { Math.Max(0, shadowWidth - shadowOffset.Y), Math.Max(0, shadowWidth + shadowOffset.X), Math.Max(0, shadowWidth + shadowOffset.Y), Math.Max(0, shadowWidth - shadowOffset.X) })); } return(RequestedAction.None); }
private static object ToneMap(ref FIBITMAP b, bool mayUnloadOriginal, ResizeSettings settings, DecodeCallback callback) { return(callback(ref b, mayUnloadOriginal));//Tone mapping is disabled, not yet functional FIBITMAP m = FIBITMAP.Zero; try { var alg = NameValueCollectionExtensions.Get <ToneMappingAlgorithm>(settings, "fi.tonemap", ToneMappingAlgorithm.None); if (alg == ToneMappingAlgorithm.Drago) { m = FreeImage.TmoDrago03(b, 2.2, 0); } else if (alg == ToneMappingAlgorithm.Reinhard) { m = FreeImage.TmoReinhard05(b, 0, 0); } else if (alg == ToneMappingAlgorithm.Fattal) { m = FreeImage.TmoFattal02(b, 0.5, 0.85); } else { return(callback(ref b, mayUnloadOriginal)); } if (mayUnloadOriginal) { FreeImage.UnloadEx(ref b); } return(callback(ref m, true)); } finally { if (!m.IsNull) { FreeImage.UnloadEx(ref m); } } }
protected void ParseXml(Node n, Config conf) { if (n == null) { return; } OnlyAllowPresets = NameValueCollectionExtensions.Get(n.Attrs, "onlyAllowPresets", OnlyAllowPresets); if (n.Children == null) { return; } foreach (Node c in n.Children) { string name = c.Attrs["name"]; if (c.Name.Equals("preset", StringComparison.OrdinalIgnoreCase)) { //Verify the name is specified and is unique. if (string.IsNullOrEmpty(name) || defaults.ContainsKey(name) || settings.ContainsKey(name)) { conf.configurationSectionIssues.AcceptIssue(new Issue("Presets", "The name attribute for each preset must be specified, and must be unique.", "XML: " + c.ToString(), IssueSeverity.ConfigurationError)); continue; } if (!string.IsNullOrEmpty(c.Attrs["defaults"])) { defaults[name] = new ResizeSettings(c.Attrs["defaults"]); } if (!string.IsNullOrEmpty(c.Attrs["settings"])) { settings[name] = new ResizeSettings(c.Attrs["settings"]); } } } return; }
/// <summary> /// Provides culture-invariant serialization of value types, in lower case for querystring readability. Setting a key to null removes it. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="q"></param> /// <param name="name"></param> /// <param name="val"></param> /// <returns></returns> public TK Set <T>(string name, T?val) where T : struct, IConvertible { return((TK)NameValueCollectionExtensions.Set(this, name, val)); }
/// <summary> /// Serializes the given value by calling .ToString(). If the value is null, the key is removed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="val"></param> /// <returns></returns> public TK SetAsString <T>(string name, T val) where T : class { return((TK)NameValueCollectionExtensions.SetAsString(this, name, val)); }
/// <summary> /// Provides culture-invariant parsing of byte, int, double, float, bool, and enum values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="defaultValue"></param> /// <returns></returns> public T Get <T>(string name, T defaultValue) where T : struct, IConvertible { return(NameValueCollectionExtensions.ParsePrimitive <T>(this[name], defaultValue).Value); }
protected override RequestedAction LayoutImage(ImageState s) { //Only activated if both width and height are specified, and mode=crop. if (s.settings.Mode != FitMode.Crop || s.settings.Width < 0 || s.settings.Height < 0) { return(RequestedAction.None); } //Calculate bounding box for all coordinates specified. double[] focus = NameValueCollectionExtensions.GetList <double>(s.settings, "c.focus", null, 2, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72); if (focus == null) { return(RequestedAction.None); } RectangleF box = PolygonMath.GetBoundingBox(focus); var bounds = new RectangleF(new PointF(0, 0), s.originalSize); //Clip box to original image bounds box = PolygonMath.ClipRectangle(box, bounds); var targetSize = new SizeF(s.settings.Width, s.settings.Height); SizeF copySize; //Now, we can either crop as closely as possible or as loosely as possible. if (NameValueCollectionExtensions.Get <bool>(s.settings, "c.zoom", false) && box.Width > 0 && box.Height > 0) { //Crop close copySize = PolygonMath.ScaleOutside(box.Size, targetSize); } else { //Crop minimally copySize = PolygonMath.ScaleInside(targetSize, bounds.Size); //Ensure it's outside the box if (!PolygonMath.FitsInside(box.Size, copySize)) { copySize = PolygonMath.ScaleOutside(box.Size, copySize); } } //Clip to bounds. box = PolygonMath.ClipRectangle(PolygonMath.ExpandTo(box, copySize), bounds); s.copyRect = box; ///What is the vertical and horizontal aspect ratio different in result pixels? var padding = PolygonMath.ScaleInside(box.Size, targetSize); padding = new SizeF(targetSize.Width - padding.Width, targetSize.Height - padding.Height); //So, if we haven't met the aspect ratio yet, what mode will we pass on? var finalmode = NameValueCollectionExtensions.Get <FitMode>(s.settings, "c.finalmode", FitMode.Pad); //Crop off 1 or 2 pixels instead of padding without worrying too much if (finalmode == FitMode.Pad && padding.Width + padding.Height < 3) { finalmode = FitMode.Crop; } s.settings.Mode = finalmode; return(RequestedAction.None); }
/// <summary> /// Normalizes a command that has two possible names. /// If either of the commands has a null or empty value, those keys are removed. /// If both the the primary and secondary are present, the secondary is removed. /// Otherwise, the secondary is renamed to the primary name. /// </summary> /// <param name="primary"></param> /// <param name="secondary"></param> public ResizeSettings Normalize(string primary, string secondary) { return((ResizeSettings)NameValueCollectionExtensions.Normalize(this, primary, secondary)); }