context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Osu.Objects;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Editor
{
[TestFixture]
public class TestSceneEditorSeekSnapping : EditorClockTestScene
{
public TestSceneEditorSeekSnapping()
{
BeatDivisor.Value = 4;
}
[BackgroundDependencyLoader]
private void load()
{
var testBeatmap = new Beatmap
{
ControlPointInfo = new ControlPointInfo
{
TimingPoints =
{
new TimingControlPoint { Time = 0, BeatLength = 200 },
new TimingControlPoint { Time = 100, BeatLength = 400 },
new TimingControlPoint { Time = 175, BeatLength = 800 },
new TimingControlPoint { Time = 350, BeatLength = 200 },
new TimingControlPoint { Time = 450, BeatLength = 100 },
new TimingControlPoint { Time = 500, BeatLength = 307.69230769230802 }
}
},
HitObjects =
{
new HitCircle { StartTime = 0 },
new HitCircle { StartTime = 5000 }
}
};
Beatmap.Value = CreateWorkingBeatmap(testBeatmap);
Child = new TimingPointVisualiser(testBeatmap, 5000) { Clock = Clock };
}
/// <summary>
/// Tests whether time is correctly seeked without snapping.
/// </summary>
[Test]
public void TestSeekNoSnapping()
{
reset();
// Forwards
AddStep("Seek(0)", () => Clock.Seek(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(33)", () => Clock.Seek(33));
AddAssert("Time = 33", () => Clock.CurrentTime == 33);
AddStep("Seek(89)", () => Clock.Seek(89));
AddAssert("Time = 89", () => Clock.CurrentTime == 89);
// Backwards
AddStep("Seek(25)", () => Clock.Seek(25));
AddAssert("Time = 25", () => Clock.CurrentTime == 25);
AddStep("Seek(0)", () => Clock.Seek(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests whether seeking to exact beat times puts us on the beat time.
/// These are the white/yellow ticks on the graph.
/// </summary>
[Test]
public void TestSeekSnappingOnBeat()
{
reset();
AddStep("Seek(0), Snap", () => Clock.SeekSnapped(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(50), Snap", () => Clock.SeekSnapped(50));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(100), Snap", () => Clock.SeekSnapped(100));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(175), Snap", () => Clock.SeekSnapped(175));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(350), Snap", () => Clock.SeekSnapped(350));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("Seek(400), Snap", () => Clock.SeekSnapped(400));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(450), Snap", () => Clock.SeekSnapped(450));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests whether seeking to somewhere in the middle between beats puts us on the expected beats.
/// For example, snapping between a white/yellow beat should put us on either the yellow or white, depending on which one we're closer too.
/// </summary>
[Test]
public void TestSeekSnappingInBetweenBeat()
{
reset();
AddStep("Seek(24), Snap", () => Clock.SeekSnapped(24));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(26), Snap", () => Clock.SeekSnapped(26));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(150), Snap", () => Clock.SeekSnapped(150));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(170), Snap", () => Clock.SeekSnapped(170));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(274), Snap", () => Clock.SeekSnapped(274));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(276), Snap", () => Clock.SeekSnapped(276));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
}
/// <summary>
/// Tests that when seeking forward with no beat snapping, beats are never explicitly snapped to, nor the next timing point (if we've skipped it).
/// </summary>
[Test]
public void TestSeekForwardNoSnapping()
{
reset();
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 200", () => Clock.CurrentTime == 200);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking forward with beat snapping, all beats are snapped to and timing points are never skipped.
/// </summary>
[Test]
public void TestSeekForwardSnappingOnBeat()
{
reset();
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking forward from in-between two beats, the next beat or timing point is snapped to, and no beats are skipped.
/// This will also test being extremely close to the next beat/timing point, to ensure rounding is not an issue.
/// </summary>
[Test]
public void TestSeekForwardSnappingFromInBetweenBeat()
{
reset();
AddStep("Seek(49)", () => Clock.Seek(49));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(49.999)", () => Clock.Seek(49.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(99)", () => Clock.Seek(99));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(99.999)", () => Clock.Seek(99.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(174)", () => Clock.Seek(174));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(349)", () => Clock.Seek(349));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("Seek(399)", () => Clock.Seek(399));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(449)", () => Clock.Seek(449));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking backward with no beat snapping, beats are never explicitly snapped to, nor the next timing point (if we've skipped it).
/// </summary>
[Test]
public void TestSeekBackwardNoSnapping()
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 150", () => Clock.CurrentTime == 150);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests that when seeking backward with beat snapping, all beats are snapped to and timing points are never skipped.
/// </summary>
[Test]
public void TestSeekBackwardSnappingOnBeat()
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests that when seeking backward from in-between two beats, the previous beat or timing point is snapped to, and no beats are skipped.
/// This will also test being extremely close to the previous beat/timing point, to ensure rounding is not an issue.
/// </summary>
[Test]
public void TestSeekBackwardSnappingFromInBetweenBeat()
{
reset();
AddStep("Seek(451)", () => Clock.Seek(451));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
AddStep("Seek(450.999)", () => Clock.Seek(450.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
AddStep("Seek(401)", () => Clock.Seek(401));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(401.999)", () => Clock.Seek(401.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
}
/// <summary>
/// Tests that there are no rounding issues when snapping to beats within a timing point with a floating-point beatlength.
/// </summary>
[Test]
public void TestSeekingWithFloatingPointBeatLength()
{
reset();
double lastTime = 0;
AddStep("Seek(0)", () => Clock.Seek(0));
for (int i = 0; i < 9; i++)
{
AddStep("SeekForward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekForward(true);
});
AddAssert("Time > lastTime", () => Clock.CurrentTime > lastTime);
}
for (int i = 0; i < 9; i++)
{
AddStep("SeekBackward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekBackward(true);
});
AddAssert("Time < lastTime", () => Clock.CurrentTime < lastTime);
}
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
private void reset()
{
AddStep("Reset", () => Clock.Seek(0));
}
private class TimingPointVisualiser : CompositeDrawable
{
private readonly double length;
private readonly Drawable tracker;
public TimingPointVisualiser(IBeatmap beatmap, double length)
{
this.length = length;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Width = 0.75f;
FillFlowContainer timelineContainer;
InternalChildren = new Drawable[]
{
new Box
{
Name = "Background",
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(85f)
},
new Container
{
Name = "Tracks",
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding(15),
Children = new[]
{
tracker = new Box
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y,
RelativePositionAxes = Axes.X,
Width = 2,
Colour = Color4.Red,
},
timelineContainer = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(0, 5)
},
}
}
};
var timingPoints = beatmap.ControlPointInfo.TimingPoints;
for (int i = 0; i < timingPoints.Count; i++)
{
TimingControlPoint next = i == timingPoints.Count - 1 ? null : timingPoints[i + 1];
timelineContainer.Add(new TimingPointTimeline(timingPoints[i], next?.Time ?? length, length));
}
}
protected override void Update()
{
base.Update();
tracker.X = (float)(Time.Current / length);
}
private class TimingPointTimeline : CompositeDrawable
{
public TimingPointTimeline(TimingControlPoint timingPoint, double endTime, double fullDuration)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Box createMainTick(double time) => new Box
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
RelativePositionAxes = Axes.X,
X = (float)(time / fullDuration),
Height = 10,
Width = 2
};
Box createBeatTick(double time) => new Box
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
RelativePositionAxes = Axes.X,
X = (float)(time / fullDuration),
Height = 5,
Width = 2,
Colour = time > endTime ? Color4.Gray : Color4.Yellow
};
AddInternal(createMainTick(timingPoint.Time));
AddInternal(createMainTick(endTime));
for (double t = timingPoint.Time + timingPoint.BeatLength / 4; t < fullDuration; t += timingPoint.BeatLength / 4)
AddInternal(createBeatTick(t));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using Orleans.GrainDirectory;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.GrainDirectory
{
[Serializable]
internal class ActivationInfo : IActivationInfo
{
public SiloAddress SiloAddress { get; private set; }
public DateTime TimeCreated { get; private set; }
public GrainDirectoryEntryStatus RegistrationStatus { get; set; }
public ActivationInfo(SiloAddress siloAddress, GrainDirectoryEntryStatus registrationStatus)
{
SiloAddress = siloAddress;
TimeCreated = DateTime.UtcNow;
RegistrationStatus = registrationStatus;
}
public ActivationInfo(IActivationInfo iActivationInfo)
{
SiloAddress = iActivationInfo.SiloAddress;
TimeCreated = iActivationInfo.TimeCreated;
RegistrationStatus = iActivationInfo.RegistrationStatus;
}
public bool OkToRemove(UnregistrationCause cause, GlobalConfiguration config)
{
switch (cause)
{
case UnregistrationCause.Force:
return true;
case UnregistrationCause.CacheInvalidation:
return RegistrationStatus == GrainDirectoryEntryStatus.Cached;
case UnregistrationCause.NonexistentActivation:
{
if (RegistrationStatus == GrainDirectoryEntryStatus.Cached)
return true; // cache entries are always removed
var delayparameter = config.DirectoryLazyDeregistrationDelay;
if (delayparameter <= TimeSpan.Zero)
return false; // no lazy deregistration
else
return (TimeCreated <= DateTime.UtcNow - delayparameter);
}
default:
throw new OrleansException("unhandled case");
}
}
public override string ToString()
{
return String.Format("{0}, {1}", SiloAddress, TimeCreated);
}
}
[Serializable]
internal class GrainInfo : IGrainInfo
{
public Dictionary<ActivationId, IActivationInfo> Instances { get; private set; }
public int VersionTag { get; private set; }
public bool SingleInstance { get; private set; }
private static readonly SafeRandom rand;
internal const int NO_ETAG = -1;
static GrainInfo()
{
rand = new SafeRandom();
}
internal GrainInfo()
{
Instances = new Dictionary<ActivationId, IActivationInfo>();
VersionTag = 0;
SingleInstance = false;
}
public bool AddActivation(ActivationId act, SiloAddress silo)
{
if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act))
{
throw new InvalidOperationException(
"Attempting to add a second activation to an existing grain in single activation mode");
}
IActivationInfo info;
if (Instances.TryGetValue(act, out info))
{
if (info.SiloAddress.Equals(silo))
{
// just refresh, no need to generate new VersionTag
return false;
}
}
Instances[act] = new ActivationInfo(silo, GrainDirectoryEntryStatus.ClusterLocal);
VersionTag = rand.Next();
return true;
}
public ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus)
{
SingleInstance = true;
if (Instances.Count > 0)
{
var item = Instances.First();
return ActivationAddress.GetAddress(item.Value.SiloAddress, grain, item.Key);
}
else
{
Instances.Add(act, new ActivationInfo(silo, registrationStatus));
VersionTag = rand.Next();
return ActivationAddress.GetAddress(silo, grain, act);
}
}
public bool RemoveActivation(ActivationId act, UnregistrationCause cause, GlobalConfiguration config, out IActivationInfo info, out bool wasRemoved)
{
info = null;
wasRemoved = false;
if (Instances.TryGetValue(act, out info) && info.OkToRemove(cause, config))
{
Instances.Remove(act);
wasRemoved = true;
VersionTag = rand.Next();
}
return Instances.Count == 0;
}
public Dictionary<SiloAddress, List<ActivationAddress>> Merge(GrainId grain, IGrainInfo other)
{
bool modified = false;
foreach (var pair in other.Instances)
{
if (Instances.ContainsKey(pair.Key)) continue;
Instances[pair.Key] = new ActivationInfo(pair.Value.SiloAddress, pair.Value.RegistrationStatus);
modified = true;
}
if (modified)
{
VersionTag = rand.Next();
}
if (SingleInstance && (Instances.Count > 0))
{
// Grain is supposed to be in single activation mode, but we have two activations!!
// Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value.
var orderedActivations = Instances.OrderBy(pair => pair.Key);
var activationToKeep = orderedActivations.First();
var activationsToDrop = orderedActivations.Skip(1);
Instances.Clear();
Instances.Add(activationToKeep.Key, activationToKeep.Value);
var mapping = new Dictionary<SiloAddress, List<ActivationAddress>>();
foreach (var activationPair in activationsToDrop)
{
var activation = ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key);
List<ActivationAddress> activationsToRemoveOnSilo;
if (!mapping.TryGetValue(activation.Silo, out activationsToRemoveOnSilo))
{
activationsToRemoveOnSilo = mapping[activation.Silo] = new List<ActivationAddress>(1);
}
activationsToRemoveOnSilo.Add(activation);
}
return mapping;
}
return null;
}
public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationId activation, SiloAddress silo)
{
SingleInstance = true;
if (Instances.Count > 0)
{
Instances.Remove(oldActivation);
}
Instances.Add(activation, new ActivationInfo(silo, GrainDirectoryEntryStatus.Cached));
}
public bool UpdateClusterRegistrationStatus(ActivationId activationId, GrainDirectoryEntryStatus status, GrainDirectoryEntryStatus? compareWith = null)
{
IActivationInfo activationInfo;
if (!Instances.TryGetValue(activationId, out activationInfo))
return false;
if (compareWith.HasValue && compareWith.Value != activationInfo.RegistrationStatus)
return false;
activationInfo.RegistrationStatus = status;
return true;
}
}
internal class GrainDirectoryPartition
{
// Should we change this to SortedList<> or SortedDictionary so we can extract chunks better for shipping the full
// parition to a follower, or should we leave it as a Dictionary to get O(1) lookups instead of O(log n), figuring we do
// a lot more lookups and so can sort periodically?
/// <summary>
/// contains a map from grain to its list of activations along with the version (etag) counter for the list
/// </summary>
private Dictionary<GrainId, IGrainInfo> partitionData;
private readonly object lockable;
private readonly Logger log;
private readonly ILoggerFactory loggerFactory;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly GlobalConfiguration globalConfig;
private readonly IInternalGrainFactory grainFactory;
[ThreadStatic]
private static ActivationId[] activationIdsHolder;
[ThreadStatic]
private static IActivationInfo[] activationInfosHolder;
internal int Count { get { return partitionData.Count; } }
public GrainDirectoryPartition(ISiloStatusOracle siloStatusOracle, GlobalConfiguration globalConfig, IInternalGrainFactory grainFactory, ILoggerFactory loggerFactory)
{
partitionData = new Dictionary<GrainId, IGrainInfo>();
lockable = new object();
log = new LoggerWrapper<GrainDirectoryPartition>(loggerFactory);
this.siloStatusOracle = siloStatusOracle;
this.globalConfig = globalConfig;
this.grainFactory = grainFactory;
this.loggerFactory = loggerFactory;
}
private bool IsValidSilo(SiloAddress silo)
{
return this.siloStatusOracle.IsFunctionalDirectory(silo);
}
internal void Clear()
{
lock (lockable)
{
partitionData.Clear();
}
}
/// <summary>
/// Returns all entries stored in the partition as an enumerable collection
/// </summary>
/// <returns></returns>
public Dictionary<GrainId, IGrainInfo> GetItems()
{
lock (lockable)
{
return partitionData.Copy();
}
}
/// <summary>
/// Adds a new activation to the directory partition
/// </summary>
/// <param name="grain"></param>
/// <param name="activation"></param>
/// <param name="silo"></param>
/// <returns>The version associated with this directory mapping</returns>
internal virtual int AddActivation(GrainId grain, ActivationId activation, SiloAddress silo)
{
if (!IsValidSilo(silo))
{
return GrainInfo.NO_ETAG;
}
IGrainInfo grainInfo;
lock (lockable)
{
if (!partitionData.TryGetValue(grain, out grainInfo))
{
partitionData[grain] = grainInfo = new GrainInfo();
}
grainInfo.AddActivation(activation, silo);
}
if (log.IsVerbose3) log.Verbose3("Adding activation for grain {0}", grain.ToString());
return grainInfo.VersionTag;
}
/// <summary>
/// Adds a new activation to the directory partition
/// </summary>
/// <param name="grain"></param>
/// <param name="activation"></param>
/// <param name="silo"></param>
/// <param name="registrationStatus"></param>
/// <returns>The registered ActivationAddress and version associated with this directory mapping</returns>
internal virtual AddressAndTag AddSingleActivation(GrainId grain, ActivationId activation, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus)
{
if (log.IsVerbose3) log.Verbose3("Adding single activation for grain {0}{1}{2}", silo, grain, activation);
AddressAndTag result = new AddressAndTag();
if (!IsValidSilo(silo))
return result;
IGrainInfo grainInfo;
lock (lockable)
{
if (!partitionData.TryGetValue(grain, out grainInfo))
{
partitionData[grain] = grainInfo = new GrainInfo();
}
result.Address = grainInfo.AddSingleActivation(grain, activation, silo, registrationStatus);
result.VersionTag = grainInfo.VersionTag;
}
return result;
}
/// <summary>
/// Removes an activation of the given grain from the partition
/// </summary>
/// <param name="grain">the identity of the grain</param>
/// <param name="activation">the id of the activation</param>
/// <param name="cause">reason for removing the activation</param>
internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause = UnregistrationCause.Force)
{
IActivationInfo ignore1;
bool ignore2;
RemoveActivation(grain, activation, cause, out ignore1, out ignore2);
}
/// <summary>
/// Removes an activation of the given grain from the partition
/// </summary>
/// <param name="grain">the identity of the grain</param>
/// <param name="activation">the id of the activation</param>
/// <param name="cause">reason for removing the activation</param>
/// <param name="entry">returns the entry, if found </param>
/// <param name="wasRemoved">returns whether the entry was actually removed</param>
internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause, out IActivationInfo entry, out bool wasRemoved)
{
wasRemoved = false;
entry = null;
lock (lockable)
{
if (partitionData.ContainsKey(grain) && partitionData[grain].RemoveActivation(activation, cause, globalConfig, out entry, out wasRemoved))
// if the last activation for the grain was removed, we remove the entire grain info
partitionData.Remove(grain);
}
if (log.IsVerbose3)
log.Verbose3("Removing activation for grain {0} cause={1} was_removed={2}", grain.ToString(), cause, wasRemoved);
}
/// <summary>
/// Removes the grain (and, effectively, all its activations) from the diretcory
/// </summary>
/// <param name="grain"></param>
internal void RemoveGrain(GrainId grain)
{
lock (lockable)
{
partitionData.Remove(grain);
}
if (log.IsVerbose3) log.Verbose3("Removing grain {0}", grain.ToString());
}
/// <summary>
/// Returns a list of activations (along with the version number of the list) for the given grain.
/// If the grain is not found, null is returned.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
internal AddressesAndTag LookUpActivations(GrainId grain)
{
var result = new AddressesAndTag();
ActivationId[] activationIds;
IActivationInfo[] activationInfos;
const int arrayReusingThreshold = 100;
int grainInfoInstancesCount;
lock (lockable)
{
IGrainInfo graininfo;
if (!partitionData.TryGetValue(grain, out graininfo))
{
return result;
}
result.VersionTag = graininfo.VersionTag;
grainInfoInstancesCount = graininfo.Instances.Count;
if (grainInfoInstancesCount < arrayReusingThreshold)
{
if ((activationIds = activationIdsHolder) == null)
{
activationIdsHolder = activationIds = new ActivationId[arrayReusingThreshold];
}
if ((activationInfos = activationInfosHolder) == null)
{
activationInfosHolder = activationInfos = new IActivationInfo[arrayReusingThreshold];
}
}
else
{
activationIds = new ActivationId[grainInfoInstancesCount];
activationInfos = new IActivationInfo[grainInfoInstancesCount];
}
graininfo.Instances.Keys.CopyTo(activationIds, 0);
graininfo.Instances.Values.CopyTo(activationInfos, 0);
}
result.Addresses = new List<ActivationAddress>(grainInfoInstancesCount);
for (var i = 0; i < grainInfoInstancesCount; i++)
{
var activationInfo = activationInfos[i];
if (IsValidSilo(activationInfo.SiloAddress))
{
result.Addresses.Add(ActivationAddress.GetAddress(activationInfo.SiloAddress, grain, activationIds[i]));
}
activationInfos[i] = null;
activationIds[i] = null;
}
return result;
}
/// <summary>
/// Returns the activation of a single-activation grain, if present.
/// </summary>
internal GrainDirectoryEntryStatus TryGetActivation(GrainId grain, out ActivationAddress address, out int version)
{
IGrainInfo grainInfo;
address = null;
version = 0;
lock (lockable)
{
if (!partitionData.TryGetValue(grain, out grainInfo))
{
return GrainDirectoryEntryStatus.Invalid;
}
var first = grainInfo.Instances.FirstOrDefault();
if (first.Value != null)
{
address = ActivationAddress.GetAddress(first.Value.SiloAddress, grain, first.Key);
version = grainInfo.VersionTag;
return first.Value.RegistrationStatus;
}
}
return GrainDirectoryEntryStatus.Invalid;
}
/// <summary>
/// Returns the version number of the list of activations for the grain.
/// If the grain is not found, -1 is returned.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
internal int GetGrainETag(GrainId grain)
{
IGrainInfo grainInfo;
lock (lockable)
{
if (!partitionData.TryGetValue(grain, out grainInfo))
{
return GrainInfo.NO_ETAG;
}
return grainInfo.VersionTag;
}
}
/// <summary>
/// Merges one partition into another, assuming partitions are disjoint.
/// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes.
/// </summary>
/// <param name="other"></param>
internal void Merge(GrainDirectoryPartition other)
{
lock (lockable)
{
foreach (var pair in other.partitionData)
{
if (partitionData.ContainsKey(pair.Key))
{
if (log.IsVerbose) log.Verbose("While merging two disjoint partitions, same grain " + pair.Key + " was found in both partitions");
var activationsToDrop = partitionData[pair.Key].Merge(pair.Key, pair.Value);
if (activationsToDrop == null) continue;
foreach (var siloActivations in activationsToDrop)
{
var remoteCatalog = grainFactory.GetSystemTarget<ICatalog>(Constants.CatalogId, siloActivations.Key);
remoteCatalog.DeleteActivations(siloActivations.Value).Ignore();
}
}
else
{
partitionData.Add(pair.Key, pair.Value);
}
}
}
}
/// <summary>
/// Runs through all entries in the partition and moves/copies (depending on the given flag) the
/// entries satisfying the given predicate into a new partition.
/// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes.
/// </summary>
/// <param name="predicate">filter predicate (usually if the given grain is owned by particular silo)</param>
/// <param name="modifyOrigin">flag controling whether the source partition should be modified (i.e., the entries should be moved or just copied) </param>
/// <returns>new grain directory partition containing entries satisfying the given predicate</returns>
internal GrainDirectoryPartition Split(Predicate<GrainId> predicate, bool modifyOrigin)
{
var newDirectory = new GrainDirectoryPartition(this.siloStatusOracle, this.globalConfig, this.grainFactory, this.loggerFactory);
if (modifyOrigin)
{
// SInce we use the "pairs" list to modify the underlying collection below, we need to turn it into an actual list here
List<KeyValuePair<GrainId, IGrainInfo>> pairs;
lock (lockable)
{
pairs = partitionData.Where(pair => predicate(pair.Key)).ToList();
}
foreach (var pair in pairs)
{
newDirectory.partitionData.Add(pair.Key, pair.Value);
}
lock (lockable)
{
foreach (var pair in pairs)
{
partitionData.Remove(pair.Key);
}
}
}
else
{
lock (lockable)
{
foreach (var pair in partitionData.Where(pair => predicate(pair.Key)))
{
newDirectory.partitionData.Add(pair.Key, pair.Value);
}
}
}
return newDirectory;
}
internal List<ActivationAddress> ToListOfActivations(bool singleActivation)
{
var result = new List<ActivationAddress>();
lock (lockable)
{
foreach (var pair in partitionData)
{
var grain = pair.Key;
if (pair.Value.SingleInstance == singleActivation)
{
result.AddRange(pair.Value.Instances.Select(activationPair => ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key))
.Where(addr => IsValidSilo(addr.Silo)));
}
}
}
return result;
}
/// <summary>
/// Sets the internal parition dictionary to the one given as input parameter.
/// This method is supposed to be used by handoff manager to update the old partition with a new partition.
/// </summary>
/// <param name="newPartitionData">new internal partition dictionary</param>
internal void Set(Dictionary<GrainId, IGrainInfo> newPartitionData)
{
partitionData = newPartitionData;
}
/// <summary>
/// Updates partition with a new delta of changes.
/// This method is supposed to be used by handoff manager to update the partition with a set of delta changes.
/// </summary>
/// <param name="newPartitionDelta">dictionary holding a set of delta updates to this partition.
/// If the value for a given key in the delta is valid, then existing entry in the partition is replaced.
/// Otherwise, i.e., if the value is null, the corresponding entry is removed.
/// </param>
internal void Update(Dictionary<GrainId, IGrainInfo> newPartitionDelta)
{
lock (lockable)
{
foreach (GrainId grain in newPartitionDelta.Keys)
{
if (newPartitionDelta[grain] != null)
{
partitionData[grain] = newPartitionDelta[grain];
}
else
{
partitionData.Remove(grain);
}
}
}
}
public override string ToString()
{
var sb = new StringBuilder();
lock (lockable)
{
foreach (var grainEntry in partitionData)
{
foreach (var activationEntry in grainEntry.Value.Instances)
{
sb.Append(" ").Append(grainEntry.Key.ToString()).Append("[" + grainEntry.Value.VersionTag + "]").
Append(" => ").Append(activationEntry.Key.ToString()).
Append(" @ ").AppendLine(activationEntry.Value.ToString());
}
}
}
return sb.ToString();
}
public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationAddress otherClusterAddress)
{
lock (lockable)
{
if (partitionData.ContainsKey(grain))
{
partitionData[grain].CacheOrUpdateRemoteClusterRegistration(grain, oldActivation,
otherClusterAddress.Activation, otherClusterAddress.Silo);
}
else
{
AddSingleActivation(grain, otherClusterAddress.Activation, otherClusterAddress.Silo,
GrainDirectoryEntryStatus.Cached);
}
}
}
public bool UpdateClusterRegistrationStatus(GrainId grain, ActivationId activationId, GrainDirectoryEntryStatus registrationStatus, GrainDirectoryEntryStatus? compareWith = null)
{
lock (lockable)
{
IGrainInfo graininfo;
if (partitionData.TryGetValue(grain, out graininfo))
{
return graininfo.UpdateClusterRegistrationStatus(activationId, registrationStatus, compareWith);
}
return false;
}
}
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using System.Windows.Forms;
namespace LineNumbers
{
[System.ComponentModel.DefaultProperty("ParentRichTextBox")]
public class LineNumbers_For_RichTextBox : System.Windows.Forms.Control
{
private class LineNumberItem
{
internal int LineNumber;
internal Rectangle Rectangle;
internal LineNumberItem(int zLineNumber, Rectangle zRectangle)
{
this.LineNumber = zLineNumber;
this.Rectangle = zRectangle;
}
}
public int getWidth()
{
int w = 25;
// get total lines of richTextBox1
int line = this.ParentRichTextBox.Lines.Length;
if (line <= 99)
{
w = 20 + (int)ParentRichTextBox.Font.Size;
}
else if (line <= 999)
{
w = 30 + (int)ParentRichTextBox.Font.Size;
}
else
{
w = 50 + (int)ParentRichTextBox.Font.Size;
}
return w;
}
public enum LineNumberDockSide : byte
{
None = 0,
Left = 1,
Right = 2,
Height = 4
}
private RichTextBox withEventsField_zParent = null;
private RichTextBox zParent {
get { return withEventsField_zParent; }
set {
if (withEventsField_zParent != null) {
withEventsField_zParent.LocationChanged -= zParent_Changed;
withEventsField_zParent.Move -= zParent_Changed;
withEventsField_zParent.Resize -= zParent_Changed;
withEventsField_zParent.DockChanged -= zParent_Changed;
withEventsField_zParent.TextChanged -= zParent_Changed;
withEventsField_zParent.MultilineChanged -= zParent_Changed;
withEventsField_zParent.HScroll -= zParent_Scroll;
withEventsField_zParent.VScroll -= zParent_Scroll;
withEventsField_zParent.ContentsResized -= zParent_ContentsResized;
withEventsField_zParent.Disposed -= zParent_Disposed;
}
withEventsField_zParent = value;
if (withEventsField_zParent != null) {
withEventsField_zParent.LocationChanged += zParent_Changed;
withEventsField_zParent.Move += zParent_Changed;
withEventsField_zParent.Resize += zParent_Changed;
withEventsField_zParent.DockChanged += zParent_Changed;
withEventsField_zParent.TextChanged += zParent_Changed;
withEventsField_zParent.MultilineChanged += zParent_Changed;
withEventsField_zParent.HScroll += zParent_Scroll;
withEventsField_zParent.VScroll += zParent_Scroll;
withEventsField_zParent.ContentsResized += zParent_ContentsResized;
withEventsField_zParent.Disposed += zParent_Disposed;
}
}
}
//private Windows.Forms.Timer withEventsField_zTimer = new Windows.Forms.Timer();
//private Windows.Forms.Timer zTimer {
//private Timer withEventsField_zTimer = new Windows.Forms.Timer();
private Timer withEventsField_zTimer = new Timer();
private Timer zTimer
{
get { return withEventsField_zTimer; }
set {
if (withEventsField_zTimer != null) {
withEventsField_zTimer.Tick -= zTimer_Tick;
}
withEventsField_zTimer = value;
if (withEventsField_zTimer != null) {
withEventsField_zTimer.Tick += zTimer_Tick;
}
}
}
private bool zAutoSizing = true;
private Size zAutoSizing_Size = new Size(0, 0);
//private Rectangle zContentRectangle = null;
private Rectangle zContentRectangle;
private LineNumberDockSide zDockSide = LineNumberDockSide.Left;
private bool zParentIsScrolling = false;
private bool zSeeThroughMode = false;
private bool zGradient_Show = true;
private System.Drawing.Drawing2D.LinearGradientMode zGradient_Direction = System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
private Color zGradient_StartColor = Color.FromArgb(0, 0, 0, 0);
private Color zGradient_EndColor = Color.LightSteelBlue;
private bool zGridLines_Show = true;
private float zGridLines_Thickness = 1;
private System.Drawing.Drawing2D.DashStyle zGridLines_Style = System.Drawing.Drawing2D.DashStyle.Dot;
private Color zGridLines_Color = Color.SlateGray;
private bool zBorderLines_Show = true;
private float zBorderLines_Thickness = 1;
private System.Drawing.Drawing2D.DashStyle zBorderLines_Style = System.Drawing.Drawing2D.DashStyle.Dot;
private Color zBorderLines_Color = Color.SlateGray;
private bool zMarginLines_Show = true;
private LineNumberDockSide zMarginLines_Side = LineNumberDockSide.Right;
private float zMarginLines_Thickness = 1;
private System.Drawing.Drawing2D.DashStyle zMarginLines_Style = System.Drawing.Drawing2D.DashStyle.Solid;
private Color zMarginLines_Color = Color.SlateGray;
private bool zLineNumbers_Show = true;
private bool zLineNumbers_ShowLeadingZeroes = true;
private bool zLineNumbers_ShowAsHexadecimal = false;
private bool zLineNumbers_ClipByItemRectangle = true;
private Size zLineNumbers_Offset = new Size(0, 0);
private string zLineNumbers_Format = "0";
private System.Drawing.ContentAlignment zLineNumbers_Alignment = ContentAlignment.TopRight;
private bool zLineNumbers_AntiAlias = true;
private List<LineNumberItem> zLNIs = new List<LineNumberItem>();
private Point zPointInParent = new Point(0, 0);
private Point zPointInMe = new Point(0, 0);
private int zParentInMe = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////
public LineNumbers_For_RichTextBox()
{
{
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.Margin = new Padding(0);
this.Padding = new Padding(0, 0, 2, 0);
}
{
zTimer.Enabled = true;
zTimer.Interval = 200;
zTimer.Stop();
}
this.Update_SizeAndPosition();
this.Invalidate();
}
protected override void OnHandleCreated(System.EventArgs e)
{
base.OnHandleCreated(e);
this.AutoSize = false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
[System.ComponentModel.Browsable(false)]
public override bool AutoSize {
get { return base.AutoSize; }
set {
base.AutoSize = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this property to automatically resize the control (and reposition it if needed).")]
[System.ComponentModel.Category("Additional Behavior")]
public bool AutoSizing {
get { return zAutoSizing; }
set {
zAutoSizing = value;
this.Refresh();
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this property to enable LineNumbers for the chosen RichTextBox.")]
[System.ComponentModel.Category("Add LineNumbers to")]
public RichTextBox ParentRichTextBox {
get { return zParent; }
set {
zParent = value;
if (zParent != null) {
this.Parent = zParent.Parent;
zParent.Refresh();
}
this.Text = "";
this.Refresh();
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this property to dock the LineNumbers to a chosen side of the chosen RichTextBox.")]
[System.ComponentModel.Category("Additional Behavior")]
public LineNumberDockSide DockSide {
get { return zDockSide; }
set {
zDockSide = value;
this.Refresh();
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this property to enable the control to act as an overlay ontop of the RichTextBox.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool _SeeThroughMode_ {
get { return zSeeThroughMode; }
set {
zSeeThroughMode = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("BorderLines are shown on all sides of the LineNumber control.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool Show_BorderLines {
get { return zBorderLines_Show; }
set {
zBorderLines_Show = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public Color BorderLines_Color {
get { return zBorderLines_Color; }
set {
zBorderLines_Color = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public float BorderLines_Thickness {
get { return zBorderLines_Thickness; }
set {
zBorderLines_Thickness = Math.Max(1, Math.Min(255, value));
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public System.Drawing.Drawing2D.DashStyle BorderLines_Style
{
get { return zBorderLines_Style; }
set {
if (value == System.Drawing.Drawing2D.DashStyle.Custom)
value = System.Drawing.Drawing2D.DashStyle.Solid;
zBorderLines_Style = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("GridLines are the horizontal divider-lines shown above each LineNumber.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool Show_GridLines {
get { return zGridLines_Show; }
set {
zGridLines_Show = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public Color GridLines_Color {
get { return zGridLines_Color; }
set {
zGridLines_Color = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public float GridLines_Thickness {
get { return zGridLines_Thickness; }
set {
zGridLines_Thickness = Math.Max(1, Math.Min(255, value));
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public System.Drawing.Drawing2D.DashStyle GridLines_Style
{
get { return zGridLines_Style; }
set {
if (value == System.Drawing.Drawing2D.DashStyle.Custom)
value = System.Drawing.Drawing2D.DashStyle.Solid;
zGridLines_Style = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("MarginLines are shown on the Left or Right (or both in Height-mode) of the LineNumber control.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool Show_MarginLines {
get { return zMarginLines_Show; }
set {
zMarginLines_Show = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public LineNumberDockSide MarginLines_Side {
get { return zMarginLines_Side; }
set {
zMarginLines_Side = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public Color MarginLines_Color {
get { return zMarginLines_Color; }
set {
zMarginLines_Color = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public float MarginLines_Thickness {
get { return zMarginLines_Thickness; }
set {
zMarginLines_Thickness = Math.Max(1, Math.Min(255, value));
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public System.Drawing.Drawing2D.DashStyle MarginLines_Style
{
get { return zMarginLines_Style; }
set {
if (value == System.Drawing.Drawing2D.DashStyle.Custom)
value = System.Drawing.Drawing2D.DashStyle.Solid;
zMarginLines_Style = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("The BackgroundGradient is a gradual blend of two colors, shown in the back of each LineNumber's item-area.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool Show_BackgroundGradient {
get { return zGradient_Show; }
set {
zGradient_Show = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public Color BackgroundGradient_AlphaColor {
get { return zGradient_StartColor; }
set {
zGradient_StartColor = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public Color BackgroundGradient_BetaColor {
get { return zGradient_EndColor; }
set {
zGradient_EndColor = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Appearance")]
public System.Drawing.Drawing2D.LinearGradientMode BackgroundGradient_Direction
{
get { return zGradient_Direction; }
set {
zGradient_Direction = value;
this.Invalidate();
}
}
[System.ComponentModel.Category("Additional Behavior")]
public bool Show_LineNrs {
get { return zLineNumbers_Show; }
set {
zLineNumbers_Show = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this to set whether the LineNumbers are allowed to spill out of their item-area, or should be clipped by it.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool LineNrs_ClippedByItemRectangle {
get { return zLineNumbers_ClipByItemRectangle; }
set {
zLineNumbers_ClipByItemRectangle = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this to set whether the LineNumbers should have leading zeroes (based on the total amount of textlines).")]
[System.ComponentModel.Category("Additional Behavior")]
public bool LineNrs_LeadingZeroes {
get { return zLineNumbers_ShowLeadingZeroes; }
set {
zLineNumbers_ShowLeadingZeroes = value;
this.Refresh();
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this to set whether the LineNumbers should be shown as hexadecimal values.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool LineNrs_AsHexadecimal {
get { return zLineNumbers_ShowAsHexadecimal; }
set {
zLineNumbers_ShowAsHexadecimal = value;
this.Refresh();
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this property to manually reposition the LineNumbers, relative to their current location.")]
[System.ComponentModel.Category("Additional Behavior")]
public Size LineNrs_Offset {
get { return zLineNumbers_Offset; }
set {
zLineNumbers_Offset = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this to align the LineNumbers to a chosen corner (or center) within their item-area.")]
[System.ComponentModel.Category("Additional Behavior")]
public System.Drawing.ContentAlignment LineNrs_Alignment {
get { return zLineNumbers_Alignment; }
set {
zLineNumbers_Alignment = value;
this.Invalidate();
}
}
[System.ComponentModel.Description("Use this to apply Anti-Aliasing to the LineNumbers (high quality). Some fonts will look better without it, though.")]
[System.ComponentModel.Category("Additional Behavior")]
public bool LineNrs_AntiAlias {
get { return zLineNumbers_AntiAlias; }
set {
zLineNumbers_AntiAlias = value;
this.Refresh();
this.Invalidate();
}
}
[System.ComponentModel.Browsable(true)]
public override System.Drawing.Font Font {
get { return base.Font; }
set {
base.Font = value;
this.Refresh();
this.Invalidate();
}
}
[System.ComponentModel.DefaultValue("")]
[System.ComponentModel.AmbientValue("")]
[System.ComponentModel.Browsable(false)]
public override string Text {
get { return base.Text; }
set {
base.Text = "";
this.Invalidate();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
protected override void OnSizeChanged(System.EventArgs e)
{
if (this.DesignMode == true)
this.Refresh();
base.OnSizeChanged(e);
this.Invalidate();
}
protected override void OnLocationChanged(System.EventArgs e)
{
if (this.DesignMode == true)
this.Refresh();
base.OnLocationChanged(e);
this.Invalidate();
}
public override void Refresh()
{
// Note: don't change the order here, first the Mybase.Refresh, then the Update_SizeAndPosition.
base.Refresh();
this.Update_SizeAndPosition();
}
/// <summary>
/// This Sub will run whenever Me.Refresh() is called. It applies the AutoSizing and DockSide settings.
/// </summary>
/// <remarks></remarks>
private void Update_SizeAndPosition()
{
if (this.AutoSize == true)
return;
if (this.Dock == DockStyle.Bottom | this.Dock == DockStyle.Fill | this.Dock == DockStyle.Top)
return;
Point zNewLocation = this.Location;
Size zNewSize = this.Size;
if (zAutoSizing == true) {
//switch (true) {
// case zParent == null:
if (zParent == null ){
// --- ReminderMessage sizing
if (zAutoSizing_Size.Width > 0)
zNewSize.Width = zAutoSizing_Size.Width;
if (zAutoSizing_Size.Height > 0)
zNewSize.Height = zAutoSizing_Size.Height;
this.Size = zNewSize;
// break;
}else if (this.Dock == DockStyle.Left | this.Dock == DockStyle.Right){
//--- zParent isNot Nothing for the following cases
//case this.Dock == DockStyle.Left | this.Dock == DockStyle.Right:
if (zAutoSizing_Size.Width > 0)
zNewSize.Width = zAutoSizing_Size.Width;
this.Width = zNewSize.Width;
//break;
}else if (zDockSide != LineNumberDockSide.None){
// --- DockSide is active L/R/H
//case zDockSide != LineNumberDockSide.None:
if (zAutoSizing_Size.Width > 0)
zNewSize.Width = zAutoSizing_Size.Width;
zNewSize.Height = zParent.Height;
if (zDockSide == LineNumberDockSide.Left)
zNewLocation.X = zParent.Left - zNewSize.Width - 1;
if (zDockSide == LineNumberDockSide.Right)
zNewLocation.X = zParent.Right + 1;
zNewLocation.Y = zParent.Top;
this.Location = zNewLocation;
this.Size = zNewSize;
//break;
} else if (zDockSide == LineNumberDockSide.None) {
// --- DockSide = None, but AutoSizing is still setting the Width
//case zDockSide == LineNumberDockSide.None:
if (zAutoSizing_Size.Width > 0)
zNewSize.Width = zAutoSizing_Size.Width;
this.Size = zNewSize;
//break;
}
} else {
// --- No AutoSizing
//switch (true) {
if (zParent == null){
//case zParent == null:
// --- ReminderMessage sizing
if (zAutoSizing_Size.Width > 0)
zNewSize.Width = zAutoSizing_Size.Width;
if (zAutoSizing_Size.Height > 0)
zNewSize.Height = zAutoSizing_Size.Height;
this.Size = zNewSize;
//break;
}else if (zDockSide != LineNumberDockSide.None){
// --- No AutoSizing, but DockSide L/R/H is active so height and position need updates.
//case zDockSide != LineNumberDockSide.None:
zNewSize.Height = zParent.Height;
if (zDockSide == LineNumberDockSide.Left)
zNewLocation.X = zParent.Left - zNewSize.Width - 1;
if (zDockSide == LineNumberDockSide.Right)
zNewLocation.X = zParent.Right + 1;
zNewLocation.Y = zParent.Top;
this.Location = zNewLocation;
this.Size = zNewSize;
//break;
}
}
}
/// <summary>
/// This Sub determines which textlines are visible in the ParentRichTextBox, and makes LineNumberItems (LineNumber + ItemRectangle)
/// for each visible line. They are put into the zLNIs List that will be used by the OnPaint event to draw the LineNumberItems.
/// </summary>
/// <remarks></remarks>
private void Update_VisibleLineNumberItems()
{
// ################
int tmpY;
// ###############
zLNIs.Clear();
zAutoSizing_Size = new Size(0, 0);
zLineNumbers_Format = "0";
//initial setting
// To measure the LineNumber's width, its Format 0 is replaced by w as that is likely to be one of the widest characters in non-monospace fonts.
if (zAutoSizing == true)
zAutoSizing_Size = new Size(TextRenderer.MeasureText(zLineNumbers_Format.Replace('0', 'W'), this.Font).Width, 0);
//zAutoSizing_Size = new Size(TextRenderer.MeasureText(zLineNumbers_Format.Replace("0".ToCharArray(), "W".ToCharArray()), this.Font).Width, 0);
if (zParent == null )
return;
// --- Make sure the LineNumbers are aligning to the same height as the zParent textlines by converting to screencoordinates
// and using that as an offset that gets added to the points for the LineNumberItems
zPointInParent = zParent.PointToScreen(zParent.ClientRectangle.Location);
zPointInMe = this.PointToScreen(new Point(0, 0));
// zParentInMe is the vertical offset to make the LineNumberItems line up with the textlines in zParent.
zParentInMe = zPointInParent.Y - zPointInMe.Y + 1;
// The first visible LineNumber may not be the first visible line of text in the RTB if the LineNumbercontrol's .Top is lower on the form than
// the .Top of the parent RichTextBox. Therefor, zPointInParent will now be used to find zPointInMe's equivalent height in zParent,
// which is needed to find the best StartIndex later on.
zPointInParent = zParent.PointToClient(zPointInMe);
// --- NOTES:
// Additional complication is the fact that when wordwrap is enabled on the RTB, the wordwrapped text spills into the RTB.Lines collection,
// so we need to split the text into lines ourselves, and use the Index of each zSplit-line's first character instead of the RTB's.
string[] zSplit = zParent.Text.Split(Environment.NewLine.ToCharArray());
//int qtdeLinhas = zSplit.Length < 100 ? 100 : zSplit.Length;
var linhasPosiiveis = (Height/FontHeight) ;
if (zSplit.Length < linhasPosiiveis) {
// Just one line in the text = one linenumber
// NOTE: zContentRectangle is built by the zParent.ContentsResized event.
Point zPoint = zParent.GetPositionFromCharIndex(0);
var posicaoAltura = zPoint.Y;
for (int i = 1; i <= linhasPosiiveis; i++)
{
zLNIs.Add(new LineNumberItem(i, new Rectangle(new Point(0, posicaoAltura - 1 + zParentInMe), new Size(this.Width, zContentRectangle.Height - posicaoAltura))));
posicaoAltura += FontHeight;
}
//zLNIs.Add(new LineNumberItem(1, new Rectangle(new Point(0, zPoint.Y - 1 + zParentInMe), new Size(this.Width, zContentRectangle.Height - zPoint.Y))));
// And now we can easily compute the height of the LineNumberItems by comparing each item's Y coordinate with that of the next line.
// There's at least two items in the list, and the last item is a "nextline-placeholder" that will be removed.
for (var zA = 0; zA <= zLNIs.Count - 2; zA++)
{
zLNIs[zA].Rectangle.Height = Math.Max(1, zLNIs[zA + 1].Rectangle.Y - zLNIs[zA].Rectangle.Y);
//zLNIs(zA).Rectangle.Height = Math.Max(1, zLNIs(zA + 1).Rectangle.Y - zLNIs(zA).Rectangle.Y);
}
// Removing the placeholder item
zLNIs.RemoveAt(zLNIs.Count - 1);
// Set the Format to the width of the highest possible number so that LeadingZeroes shows the correct amount of zeroes.
if (zLineNumbers_ShowAsHexadecimal == true)
{
//zLineNumbers_Format = "".PadRight(zSplit.Length.ToString("X").Length, "0");
zLineNumbers_Format = "".PadRight(zLNIs.Count.ToString("X").Length, '0');
}
else
{
//zLineNumbers_Format = "".PadRight(zSplit.Length.ToString().Length, "0");
zLineNumbers_Format = "".PadRight(zLNIs.Count.ToString().Length, '0');
}
} else {
Point pt = new Point(0, 0);
// get First Index & First Line from richTextBox1
int First_Index = ParentRichTextBox.GetCharIndexFromPosition(pt);
int First_Line = ParentRichTextBox.GetLineFromCharIndex(First_Index);
// set X & Y coordinates of Point pt to ClientRectangle Width & Height respectively
pt.X = ClientRectangle.Width;
pt.Y = ClientRectangle.Height;
// get Last Index & Last Line from richTextBox1
int Last_Index = ParentRichTextBox.GetCharIndexFromPosition(pt);
int Last_Line = ParentRichTextBox.GetLineFromCharIndex(Last_Index);
// now add each line number to LineNumberTextBox upto last line
for (int i = First_Line; i <= Last_Line + 2; i++)
{
zLNIs.Add(new LineNumberItem(i + 1, new Rectangle(0, (Last_Index - First_Index)/FontHeight, getWidth(), 1)));
//LineNumberTextBox.Text += i + 1 + "\n";this.Width
}
// Multiple lines, but store only those LineNumberItems for lines that are visible.
TimeSpan zTimeSpan = new TimeSpan(DateTime.Now.Ticks);
Point zPoint = new Point(0, 0);
int zStartIndex = 0;
int zSplitStartLine = 0;
int zA = zParent.Text.Length - 1;
// #########################
//this.FindStartIndex(ref zStartIndex, ref zA, ref zPointInParent.Y);
tmpY = zPointInParent.Y;
this.FindStartIndex(ref zStartIndex, ref zA, ref tmpY);
zPointInParent.Y = tmpY;
// ################
// zStartIndex now holds the index of a character in the first visible line from zParent.Text
// Now it will be pointed at the first character of that line (chr(10) = Linefeed part of the vbCrLf constant)
zStartIndex = Math.Max(0, Math.Min(zParent.Text.Length - 1, zParent.Text.Substring(0, zStartIndex).LastIndexOf(Char.ConvertFromUtf32(10)) + 1));
// We now need to find out which zSplit-line that character is in, by counting the vbCrlf appearances that come before it.
zSplitStartLine = Math.Max(0, zParent.Text.Substring(0, zStartIndex).Split(Environment.NewLine.ToCharArray()).Length - 1);
// zStartIndex starts off pointing at the first character of the first visible line, and will be then be pointed to
// the index of the first character on the next line.
for (zA = zSplitStartLine; zA <= zSplit.Length - 1; zA++)
{
zPoint = zParent.GetPositionFromCharIndex(zStartIndex);
zStartIndex += Math.Max(1, zSplit[zA].Length + 1);
if (zPoint.Y + zParentInMe > this.Height)
break; // TODO: might not be correct. Was : Exit For
// For performance reasons, the list of LineNumberItems (zLNIs) is first built with only the location of its
// itemrectangle being used. The height of those rectangles will be computed afterwards by comparing the items' Y coordinates.
zLNIs.Add(new LineNumberItem(zA + 1, new Rectangle(0, zPoint.Y - 1 + zParentInMe, this.Width, 1)));
if (zParentIsScrolling == true && DateTime.Now.Ticks > zTimeSpan.Ticks + 500000)
{
// The more lines there are in the RTB, the slower the RTB's .GetPositionFromCharIndex() method becomes
// To avoid those delays from interfering with the scrollingspeed, this speedbased exit for is applied (0.05 sec)
// zLNIs will have at least 1 item, and if that's the only one, then change its location to 0,0 to make it readable
if (zLNIs.Count == 1)
zLNIs[0].Rectangle.Y = 0;
// zLNIs(0).Rectangle.Y = 0;
zParentIsScrolling = false;
zTimer.Start();
break; // TODO: might not be correct. Was : Exit For
}
}
if (zLNIs.Count == 0)
return;
// Add an extra placeholder item to the end, to make the heightcomputation easier
if (zA < zSplit.Length)
{
// getting here means the for/next loop was exited before reaching the last zSplit textline
// zStartIndex will still be pointing to the startcharacter of the next line, so we can use that:
zPoint = zParent.GetPositionFromCharIndex(Math.Min(zStartIndex, zParent.Text.Length - 1));
zLNIs.Add(new LineNumberItem(-1, new Rectangle(0, zPoint.Y - 1 + zParentInMe, 0, 0)));
}
else
{
// getting here means the for/next loop ran to the end (zA is now zSplit.Length).
zLNIs.Add(new LineNumberItem(-1, new Rectangle(0, zContentRectangle.Bottom, 0, 0)));
}
// And now we can easily compute the height of the LineNumberItems by comparing each item's Y coordinate with that of the next line.
// There's at least two items in the list, and the last item is a "nextline-placeholder" that will be removed.
for (zA = 0; zA <= zLNIs.Count - 2; zA++)
{
zLNIs[zA].Rectangle.Height = Math.Max(1, zLNIs[zA + 1].Rectangle.Y - zLNIs[zA].Rectangle.Y);
//zLNIs(zA).Rectangle.Height = Math.Max(1, zLNIs(zA + 1).Rectangle.Y - zLNIs(zA).Rectangle.Y);
}
// Removing the placeholder item
zLNIs.RemoveAt(zLNIs.Count - 1);
// Set the Format to the width of the highest possible number so that LeadingZeroes shows the correct amount of zeroes.
if (zLineNumbers_ShowAsHexadecimal == true)
{
//zLineNumbers_Format = "".PadRight(zSplit.Length.ToString("X").Length, "0");
zLineNumbers_Format = "".PadRight(zSplit.Length.ToString("X").Length, '0');
}
else
{
//zLineNumbers_Format = "".PadRight(zSplit.Length.ToString().Length, "0");
zLineNumbers_Format = "".PadRight(zSplit.Length.ToString().Length, '0');
}
}
zAutoSizing_Size.Width = getWidth();
//// To measure the LineNumber's width, its Format 0 is replaced by w as that is likely to be one of the widest characters in non-monospace fonts.
//if (zAutoSizing == true)
// zAutoSizing_Size = new Size(TextRenderer.MeasureText(zLineNumbers_Format.Replace('0', 'W'), this.Font).Width, 0);
// //zAutoSizing_Size = new Size(TextRenderer.MeasureText(zLineNumbers_Format.Replace("0".ToCharArray(), "W".ToCharArray()), this.Font).Width, 0);
}
/// <summary>
/// FindStartIndex is a recursive Sub (one that calls itself) to compute the first visible line that should have a LineNumber.
/// </summary>
/// <param name="zMin"> this will hold the eventual BestStartIndex when the Sub has completed its run.</param>
/// <param name="zMax"></param>
/// <param name="zTarget"></param>
/// <remarks></remarks>
private void FindStartIndex(ref int zMin, ref int zMax, ref int zTarget)
{
// Recursive Sub to compute best starting index - only run when zParent is known to exist
if (zMax == zMin + 1 | zMin == (zMax + zMin) / 2)
return;
if(zParent.GetPositionFromCharIndex((zMax + zMin) / 2).Y == zTarget){
//switch (zParent.GetPositionFromCharIndex((zMax + zMin) / 2).Y) {
// case // ERROR: Case labels with binary operators are unsupported : Equality
// BestStartIndex found
zMin = (zMax + zMin) / 2;
//break;
}
else if (zParent.GetPositionFromCharIndex((zMax + zMin) / 2).Y > zTarget)
{
//case // ERROR: Case labels with binary operators are unsupported : GreaterThan
//zTarget:
// Look again, in lower half
zMax = (zMax + zMin) / 2;
FindStartIndex(ref zMin, ref zMax, ref zTarget);
//break;
}
else if (zParent.GetPositionFromCharIndex((zMax + zMin) / 2).Y < 0)
{
// case // ERROR: Case labels with binary operators are unsupported : LessThan
//0:
// Look again, in top half
zMin = (zMax + zMin) / 2;
FindStartIndex(ref zMin, ref zMax, ref zTarget);
//break;
}
}
/// <summary>
/// OnPaint will go through the enabled elements (vertical ReminderMessage, GridLines, LineNumbers, BorderLines, MarginLines) and will
/// draw them if enabled. At the same time, it will build GraphicsPaths for each of those elements (that are enabled), which will be used
/// in SeeThroughMode (if it's active): the figures in the GraphicsPaths will form a customized outline for the control by setting them as the
/// Region of the LineNumber control. Note: the vertical ReminderMessages are only drawn during designtime.
/// </summary>
/// <param name="e"></param>
/// <remarks></remarks>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// Build the list of visible LineNumberItems (= zLNIs) first. (doesn't take long, so it can stay in OnPaint)
this.Update_VisibleLineNumberItems();
base.OnPaint(e);
// --- QualitySettings
//if (zLineNumbers_AntiAlias == true) {
// e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//} else {
// e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
//}
// --- Local Declarations
string zTextToShow = "";
string zReminderToShow = "";
StringFormat zSF = new StringFormat();
SizeF zTextSize = default(SizeF);
Pen zPen = new Pen(this.ForeColor);
SolidBrush zBrush = new SolidBrush(this.ForeColor);
Point zPoint = new Point(0, 0);
Rectangle zItemClipRectangle = new Rectangle(0, 0, 0, 0);
// NOTE: The GraphicsPaths are only used for SeeThroughMode
// FillMode.Winding: combined outline ( Alternate: XOR'ed outline )
System.Drawing.Drawing2D.GraphicsPath zGP_GridLines = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
System.Drawing.Drawing2D.GraphicsPath zGP_BorderLines = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
System.Drawing.Drawing2D.GraphicsPath zGP_MarginLines = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
System.Drawing.Drawing2D.GraphicsPath zGP_LineNumbers = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
Region zRegion = new Region(base.ClientRectangle);
// ----------------------------------------------
// --- DESIGNTIME / NO VISIBLE ITEMS
if (this.DesignMode == true) {
// Show a vertical reminder message
if (zParent == null) {
zReminderToShow = "-!- Set ParentRichTextBox -!-";
} else {
if (zLNIs.Count == 0)
zReminderToShow = "LineNrs ( " + zParent.Name + " )";
}
if (zReminderToShow.Length > 0) {
// --- Centering and Rotation for the reminder message
e.Graphics.TranslateTransform(this.Width / 2, this.Height / 2);
e.Graphics.RotateTransform(-90);
zSF.Alignment = StringAlignment.Center;
zSF.LineAlignment = StringAlignment.Center;
// --- Show the reminder message (with small shadow)
zTextSize = e.Graphics.MeasureString(zReminderToShow, this.Font, zPoint, zSF);
e.Graphics.DrawString(zReminderToShow, this.Font, Brushes.WhiteSmoke, 1, 1, zSF);
e.Graphics.DrawString(zReminderToShow, this.Font, Brushes.Firebrick, 0, 0, zSF);
e.Graphics.ResetTransform();
//Rectangle zReminderRectangle = new Rectangle(this.Width / 2 - zTextSize.Height / 2, this.Height / 2 - zTextSize.Width / 2, zTextSize.Height, zTextSize.Width);
Rectangle zReminderRectangle = new Rectangle((int)(this.Width / 2 - zTextSize.Height / 2), (int)(this.Height / 2 - zTextSize.Width / 2), (int)(zTextSize.Height), (int)(zTextSize.Width));
zGP_LineNumbers.AddRectangle(zReminderRectangle);
zGP_LineNumbers.CloseFigure();
if (zAutoSizing == true) {
zReminderRectangle.Inflate((int)(zTextSize.Height * 0.2), (int)(zTextSize.Width * 0.1));
//zReminderRectangle.Inflate(zTextSize.Height * 0.2, zTextSize.Width * 0.1);
zAutoSizing_Size = new Size(zReminderRectangle.Width, zReminderRectangle.Height);
}
}
}
// ----------------------------------------------
// --- DESIGN OR RUNTIME / WITH VISIBLE ITEMS (which means zParent exists)
if (zLNIs.Count > 0) {
// The visible LineNumberItems with their BackgroundGradient and GridLines
// Loop through every visible LineNumberItem
System.Drawing.Drawing2D.LinearGradientBrush zLGB = null;
zPen = new Pen(zGridLines_Color, zGridLines_Thickness);
zPen.DashStyle = zGridLines_Style;
zSF.Alignment = StringAlignment.Near;
zSF.LineAlignment = StringAlignment.Near;
//zSF.FormatFlags = StringFormatFlags.FitBlackBox + StringFormatFlags.NoClip + StringFormatFlags.NoWrap;
zSF.FormatFlags = StringFormatFlags.FitBlackBox | StringFormatFlags.NoClip | StringFormatFlags.NoWrap;
for (int zA = 0; zA <= zLNIs.Count - 1; zA++) {
// --- BackgroundGradient
if (zGradient_Show == true) {
//zLGB = new Drawing2D.LinearGradientBrush(zLNIs(zA).Rectangle, zGradient_StartColor, zGradient_EndColor, zGradient_Direction);
zLGB = new System.Drawing.Drawing2D.LinearGradientBrush(zLNIs[zA].Rectangle, zGradient_StartColor, zGradient_EndColor, zGradient_Direction);
e.Graphics.FillRectangle(zLGB, zLNIs[zA].Rectangle);
//e.Graphics.FillRectangle(zLGB, zLNIs(zA).Rectangle);
}
// --- GridLines
if (zGridLines_Show == true) {
e.Graphics.DrawLine(zPen, new Point(0, zLNIs[zA].Rectangle.Y), new Point(this.Width, zLNIs[zA].Rectangle.Y));
//e.Graphics.DrawLine(zPen, new Point(0, zLNIs(zA).Rectangle.Y), new Point(this.Width, zLNIs(zA).Rectangle.Y));
// NOTE: Every item in a GraphicsPath is a closed figure, so instead of adding gridlines as lines, we'll add them
// as rectangles that loop out of sight. Their height uses the zContentRectangle which is the maxsize of
// the ParentRichTextBox's contents.
// NOTE: Slight adjustment needed when the first item has a negative Y coordinate.
// This explains the " - zLNIs(0).Rectangle.Y" (which adds the negative size to the height
// to make sure the rectangle's bottompart stays out of sight)
//zGP_GridLines.AddRectangle(new Rectangle(-zGridLines_Thickness, zLNIs(zA).Rectangle.Y, this.Width + zGridLines_Thickness * 2, this.Height - zLNIs(0).Rectangle.Y + zGridLines_Thickness));
zGP_GridLines.AddRectangle(new Rectangle( (int)(-zGridLines_Thickness),
(int)(zLNIs[zA].Rectangle.Y),
(int)(this.Width + zGridLines_Thickness * 2),
(int)(this.Height - zLNIs[zA].Rectangle.Y + zGridLines_Thickness)
));
zGP_GridLines.CloseFigure();
}
// --- LineNumbers
if (zLineNumbers_Show == true) {
// TextFormatting
if (zLineNumbers_ShowLeadingZeroes == true) {
zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs[zA].LineNumber.ToString("X") : zLNIs[zA].LineNumber.ToString(zLineNumbers_Format));
//zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs(zA).LineNumber.ToString("X") : zLNIs(zA).LineNumber.ToString(zLineNumbers_Format));
} else {
zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs[zA].LineNumber.ToString("X") : zLNIs[zA].LineNumber.ToString());
//zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs(zA).LineNumber.ToString("X") : zLNIs(zA).LineNumber.ToString);
}
// TextSizing
zTextSize = e.Graphics.MeasureString(zTextToShow, this.Font, zPoint, zSF);
// TextAlignment and positioning (zPoint = TopLeftCornerPoint of the text)
// TextAlignment, padding, manual offset (via LineNrs_Offset) and zTextSize are all included in the calculation of zPoint.
switch (zLineNumbers_Alignment) {
case ContentAlignment.TopLeft:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Left + this.Padding.Left + zLineNumbers_Offset.Width), (int)(zLNIs[zA].Rectangle.Top + this.Padding.Top + zLineNumbers_Offset.Height));
break;
case ContentAlignment.MiddleLeft:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Left + this.Padding.Left + zLineNumbers_Offset.Width), (int)(zLNIs[zA].Rectangle.Top + (zLNIs[zA].Rectangle.Height / 2) + zLineNumbers_Offset.Height - zTextSize.Height / 2));
break;
case ContentAlignment.BottomLeft:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Left + this.Padding.Left + zLineNumbers_Offset.Width), (int)(zLNIs[zA].Rectangle.Bottom - this.Padding.Bottom + 1 + zLineNumbers_Offset.Height - zTextSize.Height));
break;
case ContentAlignment.TopCenter:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Width / 2 + zLineNumbers_Offset.Width - zTextSize.Width / 2), (int)(zLNIs[zA].Rectangle.Top + this.Padding.Top + zLineNumbers_Offset.Height));
break;
case ContentAlignment.MiddleCenter:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Width / 2 + zLineNumbers_Offset.Width - zTextSize.Width / 2), (int)(zLNIs[zA].Rectangle.Top + (zLNIs[zA].Rectangle.Height / 2) + zLineNumbers_Offset.Height - zTextSize.Height / 2));
break;
case ContentAlignment.BottomCenter:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Width / 2 + zLineNumbers_Offset.Width - zTextSize.Width / 2), (int)(zLNIs[zA].Rectangle.Bottom - this.Padding.Bottom + 1 + zLineNumbers_Offset.Height - zTextSize.Height));
break;
case ContentAlignment.TopRight:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Right - this.Padding.Right + zLineNumbers_Offset.Width - zTextSize.Width), (int)(zLNIs[zA].Rectangle.Top + this.Padding.Top + zLineNumbers_Offset.Height));
break;
case ContentAlignment.MiddleRight:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Right - this.Padding.Right + zLineNumbers_Offset.Width - zTextSize.Width), (int)(zLNIs[zA].Rectangle.Top + (zLNIs[zA].Rectangle.Height / 2) + zLineNumbers_Offset.Height - zTextSize.Height / 2));
break;
case ContentAlignment.BottomRight:
zPoint = new Point((int)(zLNIs[zA].Rectangle.Right - this.Padding.Right + zLineNumbers_Offset.Width - zTextSize.Width), (int)(zLNIs[zA].Rectangle.Bottom - this.Padding.Bottom + 1 + zLineNumbers_Offset.Height - zTextSize.Height));
break;
}
// TextClipping
zItemClipRectangle = new Rectangle(zPoint, zTextSize.ToSize());
if (zLineNumbers_ClipByItemRectangle == true) {
// If selected, the text will be clipped so that it doesn't spill out of its own LineNumberItem-area.
// Only the part of the text inside the LineNumberItem.Rectangle should be visible, so intersect with the ItemRectangle
// The SetClip method temporary restricts the drawing area of the control for whatever is drawn next.
zItemClipRectangle.Intersect(zLNIs[zA].Rectangle);
e.Graphics.SetClip(zItemClipRectangle);
}
// TextDrawing
e.Graphics.DrawString(zTextToShow, this.Font, zBrush, zPoint, zSF);
e.Graphics.ResetClip();
// The GraphicsPath for the LineNumber is just a rectangle behind the text, to keep the paintingspeed high and avoid ugly artifacts.
zGP_LineNumbers.AddRectangle(zItemClipRectangle);
zGP_LineNumbers.CloseFigure();
}
}
// --- GridLinesThickness and Linestyle in SeeThroughMode. All GraphicsPath lines are drawn as solid to keep the paintingspeed high.
if (zGridLines_Show == true) {
zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
zGP_GridLines.Widen(zPen);
}
// --- Memory CleanUp
if (zLGB != null)
zLGB.Dispose();
}
// ----------------------------------------------
// --- DESIGN OR RUNTIME / ALWAYS
//Point zP_Left = new Point(Math.Floor(zBorderLines_Thickness / 2), Math.Floor(zBorderLines_Thickness / 2));
//Point zP_Right = new Point(this.Width - Math.Ceiling(zBorderLines_Thickness / 2), this.Height - Math.Ceiling(zBorderLines_Thickness / 2));
Point zP_Left = new Point(
(int)(Math.Floor(zBorderLines_Thickness / 2)),
(int)(Math.Floor(zBorderLines_Thickness / 2))
);
Point zP_Right = new Point(
(int)(this.Width - Math.Ceiling(zBorderLines_Thickness / 2)),
(int)(this.Height - Math.Ceiling(zBorderLines_Thickness / 2))
);
// --- BorderLines
Point[] zBorderLines_Points = {
new Point(zP_Left.X, zP_Left.Y),
new Point(zP_Right.X, zP_Left.Y),
new Point(zP_Right.X, zP_Right.Y),
new Point(zP_Left.X, zP_Right.Y),
new Point(zP_Left.X, zP_Left.Y)
};
if (zBorderLines_Show == true) {
zPen = new Pen(zBorderLines_Color, zBorderLines_Thickness);
zPen.DashStyle = zBorderLines_Style;
e.Graphics.DrawLines(zPen, zBorderLines_Points);
zGP_BorderLines.AddLines(zBorderLines_Points);
zGP_BorderLines.CloseFigure();
// BorderThickness and Style for SeeThroughMode
zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
zGP_BorderLines.Widen(zPen);
}
// --- MarginLines
if (zMarginLines_Show == true && zMarginLines_Side > LineNumberDockSide.None) {
zP_Left = new Point((int)(-zMarginLines_Thickness), (int)(-zMarginLines_Thickness));
zP_Right = new Point((int)(this.Width + zMarginLines_Thickness), (int)(this.Height + zMarginLines_Thickness));
zPen = new Pen(zMarginLines_Color, zMarginLines_Thickness);
zPen.DashStyle = zMarginLines_Style;
if (zMarginLines_Side == LineNumberDockSide.Left | zMarginLines_Side == LineNumberDockSide.Height) {
e.Graphics.DrawLine(zPen, new Point(
(int)(Math.Floor(zMarginLines_Thickness / 2)), 0),
new Point(
(int)(Math.Floor(zMarginLines_Thickness / 2)),
this.Height - 1)
);
zP_Left = new Point(
(int)(Math.Ceiling(zMarginLines_Thickness / 2)),
(int)(-zMarginLines_Thickness));
}
if (zMarginLines_Side == LineNumberDockSide.Right | zMarginLines_Side == LineNumberDockSide.Height) {
e.Graphics.DrawLine(zPen, new Point(
(int)(this.Width - Math.Ceiling(zMarginLines_Thickness / 2)), 0),
new Point(
(int)(this.Width - Math.Ceiling(zMarginLines_Thickness / 2)),
(int)(this.Height - 1))
);
zP_Right = new Point(
(int)(this.Width - Math.Ceiling(zMarginLines_Thickness / 2)),
(int)(this.Height + zMarginLines_Thickness)
);
}
// GraphicsPath for the MarginLines(s):
// MarginLines(s) are drawn as a rectangle connecting the zP_Left and zP_Right points, which are either inside or
// outside of sight, depending on whether the MarginLines at that side is visible. zP_Left: TopLeft and ZP_Right: BottomRight
zGP_MarginLines.AddRectangle(new Rectangle(zP_Left, new Size(zP_Right.X - zP_Left.X, zP_Right.Y - zP_Left.Y)));
zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
zGP_MarginLines.Widen(zPen);
}
// ----------------------------------------------
// --- SeeThroughMode
// combine all the GraphicsPaths (= zGP_... ) and set them as the region for the control.
if (zSeeThroughMode == true) {
zRegion.MakeEmpty();
zRegion.Union(zGP_BorderLines);
zRegion.Union(zGP_MarginLines);
zRegion.Union(zGP_GridLines);
zRegion.Union(zGP_LineNumbers);
}
// --- Region
if (zRegion.GetBounds(e.Graphics).IsEmpty == true) {
// Note: If the control is in a condition that would show it as empty, then a border-region is still drawn regardless of it's borders on/off state.
// This is added to make sure that the bounds of the control are never lost (it would remain empty if this was not done).
zGP_BorderLines.AddLines(zBorderLines_Points);
zGP_BorderLines.CloseFigure();
zPen = new Pen(zBorderLines_Color, 1);
zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
zGP_BorderLines.Widen(zPen);
zRegion = new Region(zGP_BorderLines);
}
this.Region = zRegion;
// ----------------------------------------------
// --- Memory CleanUp
if (zPen != null)
zPen.Dispose();
if (zBrush != null)
zPen.Dispose();
if (zRegion != null)
zRegion.Dispose();
if (zGP_GridLines != null)
zGP_GridLines.Dispose();
if (zGP_BorderLines != null)
zGP_BorderLines.Dispose();
if (zGP_MarginLines != null)
zGP_MarginLines.Dispose();
if (zGP_LineNumbers != null)
zGP_LineNumbers.Dispose();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
private void zTimer_Tick(object sender, System.EventArgs e)
{
zParentIsScrolling = false;
zTimer.Stop();
this.Invalidate();
}
private void zParent_Changed(object sender, System.EventArgs e)
{
this.Refresh();
this.Invalidate();
}
private void zParent_Scroll(object sender, System.EventArgs e)
{
zParentIsScrolling = true;
this.Invalidate();
}
private void zParent_ContentsResized(object sender, System.Windows.Forms.ContentsResizedEventArgs e)
{
zContentRectangle = e.NewRectangle;
this.Refresh();
this.Invalidate();
}
private void zParent_Disposed(object sender, System.EventArgs e)
{
this.ParentRichTextBox = null;
this.Refresh();
this.Invalidate();
}
}
}
| |
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using DBus.Protocol;
using System.Diagnostics;
namespace DBus.Transports
{
abstract class Transport
{
readonly object writeLock = new object ();
[ThreadStatic]
static byte[] readBuffer;
protected Connection connection;
public Stream stream;
public long socketHandle;
public event EventHandler WakeUp;
const string DBUS_DAEMON_LAUNCH_COMMAND = "dbus-launch";
public static Transport Create (AddressEntry entry)
{
switch (entry.Method) {
case "tcp":
{
Transport transport = new SocketTransport ();
transport.Open (entry);
return transport;
}
case "unix":
{
if (OSHelpers.PlatformIsUnixoid) {
Transport transport = new UnixNativeTransport ();
transport.Open (entry);
return transport;
}
break;
}
#if ENABLE_PIPES
case "win":
{
Transport transport = new PipeTransport ();
transport.Open (entry);
return transport;
}
#endif
// "autolaunch:" means: the first client user of the dbus library shall spawn the daemon on itself, see dbus 1.7.8 from http://dbus.freedesktop.org/releases/dbus/
case "autolaunch":
{
if (OSHelpers.PlatformIsUnixoid)
break;
string addr = Address.GetSessionBusAddressFromSharedMemory ();
if (string.IsNullOrEmpty (addr)) { // we have to launch the daemon ourselves
string oldDir = Directory.GetCurrentDirectory ();
// Without this, the "current" folder for the new process will be the one where the current
// executable resides, and as a consequence,that folder cannot be relocated/deleted unless the daemon is stopped
Directory.SetCurrentDirectory (Environment.GetFolderPath (Environment.SpecialFolder.System));
Process process = Process.Start (DBUS_DAEMON_LAUNCH_COMMAND);
if (process == null) {
Directory.SetCurrentDirectory (oldDir);
throw new NotSupportedException ("Transport method \"autolaunch:\" - cannot launch dbus daemon '" + DBUS_DAEMON_LAUNCH_COMMAND + "'");
}
// wait for daemon
Stopwatch stopwatch = new Stopwatch ();
stopwatch.Start ();
do {
addr = Address.GetSessionBusAddressFromSharedMemory ();
if (String.IsNullOrEmpty (addr))
Thread.Sleep (100);
} while (String.IsNullOrEmpty (addr) && stopwatch.ElapsedMilliseconds <= 5000);
Directory.SetCurrentDirectory (oldDir);
}
if (string.IsNullOrEmpty (addr))
throw new NotSupportedException ("Transport method \"autolaunch:\" - timeout during access to freshly launched dbus daemon");
return Create (AddressEntry.Parse (addr));
}
}
throw new NotSupportedException ("Transport method \"" + entry.Method + "\" not supported");
}
public abstract void Open (AddressEntry entry);
public abstract string AuthString ();
public abstract void WriteCred ();
public Connection Connection
{
get {
return connection;
} set {
connection = value;
}
}
public Stream Stream {
get {
return stream;
}
set {
stream = value;
}
}
public long SocketHandle {
get {
return socketHandle;
}
set {
socketHandle = value;
}
}
public virtual bool TryGetPeerPid (out uint pid)
{
pid = 0;
return false;
}
public virtual void Disconnect ()
{
stream.Dispose ();
}
protected void FireWakeUp ()
{
if (WakeUp != null)
WakeUp (this, EventArgs.Empty);
}
internal Message ReadMessage ()
{
Message msg;
try {
msg = ReadMessageReal ();
} catch (IOException e) {
if (ProtocolInformation.Verbose)
Console.Error.WriteLine (e.Message);
connection.IsConnected = false;
msg = null;
}
if (connection != null && connection.Monitors != null)
connection.Monitors (msg);
return msg;
}
int Read (byte[] buffer, int offset, int count)
{
int read = 0;
while (read < count) {
int nread = stream.Read (buffer, offset + read, count - read);
if (nread == 0)
break;
read += nread;
}
if (read > count)
throw new Exception ();
return read;
}
Message ReadMessageReal ()
{
byte[] header = null;
byte[] body = null;
int read;
//16 bytes is the size of the fixed part of the header
if (readBuffer == null)
readBuffer = new byte[16];
byte[] hbuf = readBuffer;
read = Read (hbuf, 0, 16);
if (read == 0)
return null;
if (read != 16)
throw new Exception ("Header read length mismatch: " + read + " of expected " + "16");
EndianFlag endianness = (EndianFlag)hbuf[0];
MessageReader reader = new MessageReader (endianness, hbuf);
//discard endian byte, message type and flags, which we don't care about here
reader.Seek (3);
byte version = reader.ReadByte ();
if (version < ProtocolInformation.MinVersion || version > ProtocolInformation.MaxVersion)
throw new NotSupportedException ("Protocol version '" + version.ToString () + "' is not supported");
if (ProtocolInformation.Verbose)
if (version != ProtocolInformation.Version)
Console.Error.WriteLine ("Warning: Protocol version '" + version.ToString () + "' is not explicitly supported but may be compatible");
uint bodyLength = reader.ReadUInt32 ();
//discard serial
reader.ReadUInt32 ();
uint headerLength = reader.ReadUInt32 ();
int bodyLen = (int)bodyLength;
int toRead = (int)headerLength;
//we fixup to include the padding following the header
toRead = ProtocolInformation.Padded (toRead, 8);
long msgLength = toRead + bodyLen;
if (msgLength > ProtocolInformation.MaxMessageLength)
throw new Exception ("Message length " + msgLength + " exceeds maximum allowed " + ProtocolInformation.MaxMessageLength + " bytes");
header = new byte[16 + toRead];
Array.Copy (hbuf, header, 16);
read = Read (header, 16, toRead);
if (read != toRead)
throw new Exception ("Message header length mismatch: " + read + " of expected " + toRead);
//read the body
if (bodyLen != 0) {
body = new byte[bodyLen];
read = Read (body, 0, bodyLen);
if (read != bodyLen)
throw new Exception ("Message body length mismatch: " + read + " of expected " + bodyLen);
}
Message msg = Message.FromReceivedBytes (Connection, header, body);
return msg;
}
internal virtual void WriteMessage (Message msg)
{
lock (writeLock) {
msg.Header.GetHeaderDataToStream (stream);
if (msg.Body != null && msg.Body.Length != 0)
stream.Write (msg.Body, 0, msg.Body.Length);
stream.Flush ();
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
static class CSharpCompilationOptionsExtensions
{
[Fact]
public void WithModuleName()
{
// ModuleName
Assert.Equal(null, TestOptions.ReleaseDll.WithModuleName(null).ModuleName);
TestOptions.ReleaseDll.WithModuleName("").VerifyErrors(
// error CS7087: Name cannot be empty.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(
@"Name cannot be empty.
Parameter name: ModuleName"
));
TestOptions.ReleaseDll.WithModuleName("a\0a").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
TestOptions.ReleaseDll.WithModuleName("a\\b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
TestOptions.ReleaseDll.WithModuleName("a/b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
TestOptions.ReleaseDll.WithModuleName("a:b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
}
public static void VerifyErrors(this CSharpCompilationOptions options, params DiagnosticDescription[] expected)
{
TestOptions.ReleaseDll.WithModuleName("a\uD800b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
options.Errors.Verify(expected);
}
}
public class CSharpCompilationOptionsTests : CSharpTestBase
{
private void TestProperty<T>(
Func<CSharpCompilationOptions, T, CSharpCompilationOptions> factory,
Func<CSharpCompilationOptions, T> getter,
T validNonDefaultValue)
{
var oldOpt1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
var validDefaultValue = getter(oldOpt1);
// we need non-default value to test Equals and GetHashCode
Assert.NotEqual(validNonDefaultValue, validDefaultValue);
// check that the assigned value can be read:
var newOpt1 = factory(oldOpt1, validNonDefaultValue);
Assert.Equal(validNonDefaultValue, getter(newOpt1));
Assert.Equal(0, newOpt1.Errors.Length);
// check that creating new options with the same value yields the same options instance:
var newOpt1_alias = factory(newOpt1, validNonDefaultValue);
Assert.Same(newOpt1_alias, newOpt1);
// check that Equals and GetHashCode work
var newOpt2 = factory(oldOpt1, validNonDefaultValue);
Assert.False(newOpt1.Equals(oldOpt1));
Assert.True(newOpt1.Equals(newOpt2));
Assert.Equal(newOpt1.GetHashCode(), newOpt2.GetHashCode());
// test default(T):
Assert.NotNull(factory(oldOpt1, default(T)));
}
[Fact]
public void Invariants()
{
TestProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary);
TestProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "foo.dll");
TestProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Foo.Bar");
TestProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>");
TestProperty((old, value) => old.WithUsings(value), opt => opt.Usings, ImmutableArray.Create("A", "B"));
TestProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release);
TestProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true);
TestProperty((old, value) => old.WithAllowUnsafe(value), opt => opt.AllowUnsafe, true);
TestProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "foo");
TestProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "foo");
TestProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true);
TestProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium);
TestProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress);
TestProperty((old, value) => old.WithWarningLevel(value), opt => opt.WarningLevel, 3);
TestProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions,
new Dictionary<string, ReportDiagnostic> { { "CS0001", ReportDiagnostic.Error } }.ToImmutableDictionary());
TestProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false);
TestProperty((old, value) => old.WithExtendedCustomDebugInformation(value), opt => opt.ExtendedCustomDebugInformation, false);
TestProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null));
TestProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new AssemblyReferenceResolver(new MetadataFileReferenceResolver(new string[0], null), new MetadataFileReferenceProvider()));
TestProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy()));
TestProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider());
}
[Fact]
public void WithXxx()
{
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName(null).VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: 'null'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "null"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("blah\0foo").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", ""));
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName(null).Errors.Length);
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("blah\0foo").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", ""));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MaxValue).VerifyErrors(
// error CS1672: Invalid option 'Int32.MaxValue' for /platform; must be anycpu, x86, Itanium or x64
Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MinValue).VerifyErrors(
// error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64
Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString()));
var defaultWarnings = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
Assert.Equal(ReportDiagnostic.Default, defaultWarnings.GeneralDiagnosticOption);
Assert.Equal(4, defaultWarnings.WarningLevel);
Assert.Equal(ReportDiagnostic.Error, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Error).GeneralDiagnosticOption);
Assert.Equal(ReportDiagnostic.Default, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Default).GeneralDiagnosticOption);
}
[Fact]
public void WithUsings()
{
var actual1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new[] { "A", "B" }).Usings;
Assert.True(actual1.SequenceEqual(new[] { "A", "B" }));
var actual2 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(Enumerable.Repeat("A", 1)).Usings;
Assert.True(actual2.SequenceEqual(Enumerable.Repeat("A", 1)));
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings(null).Usings.Count());
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings((string[])null).Usings.Count());
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { null }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'null'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ""));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "blah\0foo" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0foo"));
}
[Fact]
public void WithWarnings()
{
var warnings = new Dictionary<string, ReportDiagnostic>
{
{ MessageProvider.Instance.GetIdForErrorCode(1), ReportDiagnostic.Error },
{ MessageProvider.Instance.GetIdForErrorCode(2), ReportDiagnostic.Suppress },
{ MessageProvider.Instance.GetIdForErrorCode(3), ReportDiagnostic.Warn }
};
Assert.Equal(3, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(warnings).SpecificDiagnosticOptions.Count);
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(null).SpecificDiagnosticOptions.Count);
Assert.Equal(1, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(1).WarningLevel);
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(-1).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '-1'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(5).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '5'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "5"));
}
[Fact]
public void ConstructorValidation()
{
new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { null }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'null'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ""));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "blah\0foo" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0foo"));
Assert.Equal("Script", new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: null).ScriptClassName);
new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "blah\0foo").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", ""));
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: null).Errors.Length);
new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "blah\0foo").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", ""));
new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: (Platform)Int32.MinValue).VerifyErrors(
// error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64
Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: -1).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '-1'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: 5).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '5'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "5"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors();
new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors();
new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(
Diagnostic(ErrorCode.ERR_BadPrefer32OnLib));
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(
Diagnostic(ErrorCode.ERR_BadPrefer32OnLib));
}
/// <summary>
/// If this test fails, please update the <see cref="CSharpCompilationOptions.GetHashCode"/>
/// and <see cref="CSharpCompilationOptions.Equals(CSharpCompilationOptions)"/> methods to
/// make sure they are doing the right thing with your new field and then update the baseline
/// here.
/// </summary>
[Fact]
public void TestFieldsForEqualsAndGetHashCode()
{
ReflectionAssert.AssertPublicAndInternalFieldsAndProperties(
typeof(CSharpCompilationOptions),
"AllowUnsafe",
"Usings");
}
[Fact]
public void TestEqualitySemantics()
{
Assert.Equal(CreateCSharpCompilationOptions(), CreateCSharpCompilationOptions());
}
private static CSharpCompilationOptions CreateCSharpCompilationOptions()
{
string moduleName = null;
string mainTypeName = null;
string scriptClassName = null;
IEnumerable<string> usings = null;
OptimizationLevel optimizationLevel = OptimizationLevel.Debug;
bool checkOverflow = false;
bool allowUnsafe = false;
string cryptoKeyContainer = null;
string cryptoKeyFile = null;
bool? delaySign = null;
Platform platform = 0;
ReportDiagnostic generalDiagnosticOption = 0;
int warningLevel = 0;
IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions = null;
bool concurrentBuild = false;
bool extendedCustomDebugInformation = true;
XmlReferenceResolver xmlReferenceResolver = new XmlFileResolver(null);
SourceReferenceResolver sourceReferenceResolver = new SourceFileResolver(ImmutableArray<string>.Empty, null);
MetadataReferenceResolver metadataReferenceResolver = new AssemblyReferenceResolver(new MetadataFileReferenceResolver(ImmutableArray<string>.Empty, null), MetadataFileReferenceProvider.Default);
AssemblyIdentityComparer assemblyIdentityComparer = AssemblyIdentityComparer.Default; // Currently uses reference equality
StrongNameProvider strongNameProvider = new DesktopStrongNameProvider();
MetadataImportOptions metadataImportOptions = 0;
ImmutableArray<string> features = ImmutableArray<string>.Empty;
return new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings,
optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign,
platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions,
concurrentBuild, extendedCustomDebugInformation, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver,
assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features);
}
[Fact]
public void Serializability1()
{
VerifySerializability(new CSharpSerializableCompilationOptions(new CSharpCompilationOptions(
outputKind: OutputKind.WindowsApplication,
usings: new[] { "F", "G" },
generalDiagnosticOption: ReportDiagnostic.Hidden,
specificDiagnosticOptions: new[] { KeyValuePair.Create("CS0001", ReportDiagnostic.Suppress) })));
}
[Fact]
public void Serializability2()
{
var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp3, DocumentationMode.Diagnose, SourceCodeKind.Interactive);
var compilationOptions = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
moduleName: "M",
optimizationLevel: OptimizationLevel.Release);
compilationOptions = compilationOptions.
WithConcurrentBuild(!compilationOptions.ConcurrentBuild).
WithExtendedCustomDebugInformation(!compilationOptions.ExtendedCustomDebugInformation);
var deserializedCompilationOptions = VerifySerializability(new CSharpSerializableCompilationOptions(compilationOptions)).Options;
Assert.Equal(compilationOptions.OutputKind, deserializedCompilationOptions.OutputKind);
Assert.Equal(compilationOptions.ModuleName, deserializedCompilationOptions.ModuleName);
Assert.Equal(compilationOptions.OptimizationLevel, deserializedCompilationOptions.OptimizationLevel);
Assert.Equal(compilationOptions.ConcurrentBuild, deserializedCompilationOptions.ConcurrentBuild);
Assert.Equal(compilationOptions.ExtendedCustomDebugInformation, deserializedCompilationOptions.ExtendedCustomDebugInformation);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Cloud.Dialogflow.V2
{
/// <summary>Resource name for the <c>Session</c> resource.</summary>
public sealed partial class SessionName : gax::IResourceName, sys::IEquatable<SessionName>
{
/// <summary>The possible contents of <see cref="SessionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/agent/sessions/{session}</c>.</summary>
ProjectSession = 1,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </summary>
ProjectEnvironmentUserSession = 2,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </summary>
ProjectLocationSession = 3,
/// <summary>
/// A resource name with pattern
/// <c>
/// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </summary>
ProjectLocationEnvironmentUserSession = 4,
}
private static gax::PathTemplate s_projectSession = new gax::PathTemplate("projects/{project}/agent/sessions/{session}");
private static gax::PathTemplate s_projectEnvironmentUserSession = new gax::PathTemplate("projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}");
private static gax::PathTemplate s_projectLocationSession = new gax::PathTemplate("projects/{project}/locations/{location}/agent/sessions/{session}");
private static gax::PathTemplate s_projectLocationEnvironmentUserSession = new gax::PathTemplate("projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}");
/// <summary>Creates a <see cref="SessionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SessionName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static SessionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SessionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern <c>projects/{project}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectSession(string projectId, string sessionId) =>
new SessionName(ResourceNameType.ProjectSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectEnvironmentUserSession(string projectId, string environmentId, string userId, string sessionId) =>
new SessionName(ResourceNameType.ProjectEnvironmentUserSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectLocationSession(string projectId, string locationId, string sessionId) =>
new SessionName(ResourceNameType.ProjectLocationSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectLocationEnvironmentUserSession(string projectId, string locationId, string environmentId, string userId, string sessionId) =>
new SessionName(ResourceNameType.ProjectLocationEnvironmentUserSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </returns>
public static string Format(string projectId, string sessionId) => FormatProjectSession(projectId, sessionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </returns>
public static string FormatProjectSession(string projectId, string sessionId) =>
s_projectSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </returns>
public static string FormatProjectEnvironmentUserSession(string projectId, string environmentId, string userId, string sessionId) =>
s_projectEnvironmentUserSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </returns>
public static string FormatProjectLocationSession(string projectId, string locationId, string sessionId) =>
s_projectLocationSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </returns>
public static string FormatProjectLocationEnvironmentUserSession(string projectId, string locationId, string environmentId, string userId, string sessionId) =>
s_projectLocationEnvironmentUserSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>Parses the given resource name string into a new <see cref="SessionName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SessionName"/> if successful.</returns>
public static SessionName Parse(string sessionName) => Parse(sessionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SessionName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SessionName"/> if successful.</returns>
public static SessionName Parse(string sessionName, bool allowUnparsed) =>
TryParse(sessionName, allowUnparsed, out SessionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sessionName, out SessionName result) => TryParse(sessionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sessionName, bool allowUnparsed, out SessionName result)
{
gax::GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName));
gax::TemplatedResourceName resourceName;
if (s_projectSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectSession(resourceName[0], resourceName[1]);
return true;
}
if (s_projectEnvironmentUserSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectEnvironmentUserSession(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (s_projectLocationSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectLocationSession(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectLocationEnvironmentUserSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectLocationEnvironmentUserSession(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sessionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SessionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string environmentId = null, string locationId = null, string projectId = null, string sessionId = null, string userId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
EnvironmentId = environmentId;
LocationId = locationId;
ProjectId = projectId;
SessionId = sessionId;
UserId = userId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SessionName"/> class from the component parts of pattern
/// <c>projects/{project}/agent/sessions/{session}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
public SessionName(string projectId, string sessionId) : this(ResourceNameType.ProjectSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Environment</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string EnvironmentId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Session</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string SessionId { get; }
/// <summary>
/// The <c>User</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string UserId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectSession: return s_projectSession.Expand(ProjectId, SessionId);
case ResourceNameType.ProjectEnvironmentUserSession: return s_projectEnvironmentUserSession.Expand(ProjectId, EnvironmentId, UserId, SessionId);
case ResourceNameType.ProjectLocationSession: return s_projectLocationSession.Expand(ProjectId, LocationId, SessionId);
case ResourceNameType.ProjectLocationEnvironmentUserSession: return s_projectLocationEnvironmentUserSession.Expand(ProjectId, LocationId, EnvironmentId, UserId, SessionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SessionName);
/// <inheritdoc/>
public bool Equals(SessionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SessionName a, SessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SessionName a, SessionName b) => !(a == b);
}
public partial class DetectIntentRequest
{
/// <summary>
/// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property.
/// </summary>
public SessionName SessionAsSessionName
{
get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true);
set => Session = value?.ToString() ?? "";
}
}
public partial class StreamingDetectIntentRequest
{
/// <summary>
/// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property.
/// </summary>
public SessionName SessionAsSessionName
{
get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true);
set => Session = value?.ToString() ?? "";
}
}
}
| |
#region Copyright notice and license
// Copyright 2015-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
using CommandLine.Text;
using Google.Apis.Auth.OAuth2;
using Google.Protobuf;
using Grpc.Auth;
using Grpc.Core;
using Grpc.Core.Utils;
using Grpc.Testing;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace Grpc.IntegrationTesting
{
public class InteropClient
{
private class ClientOptions
{
[Option("server_host", DefaultValue = "127.0.0.1")]
public string ServerHost { get; set; }
[Option("server_host_override", DefaultValue = TestCredentials.DefaultHostOverride)]
public string ServerHostOverride { get; set; }
[Option("server_port", Required = true)]
public int ServerPort { get; set; }
[Option("test_case", DefaultValue = "large_unary")]
public string TestCase { get; set; }
// Deliberately using nullable bool type to allow --use_tls=true syntax (as opposed to --use_tls)
[Option("use_tls", DefaultValue = false)]
public bool? UseTls { get; set; }
// Deliberately using nullable bool type to allow --use_test_ca=true syntax (as opposed to --use_test_ca)
[Option("use_test_ca", DefaultValue = false)]
public bool? UseTestCa { get; set; }
[Option("default_service_account", Required = false)]
public string DefaultServiceAccount { get; set; }
[Option("oauth_scope", Required = false)]
public string OAuthScope { get; set; }
[Option("service_account_key_file", Required = false)]
public string ServiceAccountKeyFile { get; set; }
[HelpOption]
public string GetUsage()
{
var help = new HelpText
{
Heading = "gRPC C# interop testing client",
AddDashesToOption = true
};
help.AddPreOptionsLine("Usage:");
help.AddOptions(this);
return help;
}
}
ClientOptions options;
private InteropClient(ClientOptions options)
{
this.options = options;
}
public static void Run(string[] args)
{
var options = new ClientOptions();
if (!Parser.Default.ParseArguments(args, options))
{
Environment.Exit(1);
}
var interopClient = new InteropClient(options);
interopClient.Run().Wait();
}
private async Task Run()
{
var credentials = await CreateCredentialsAsync();
List<ChannelOption> channelOptions = null;
if (!string.IsNullOrEmpty(options.ServerHostOverride))
{
channelOptions = new List<ChannelOption>
{
new ChannelOption(ChannelOptions.SslTargetNameOverride, options.ServerHostOverride)
};
}
var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions);
await RunTestCaseAsync(channel, options);
await channel.ShutdownAsync();
}
private async Task<ChannelCredentials> CreateCredentialsAsync()
{
var credentials = ChannelCredentials.Insecure;
if (options.UseTls.Value)
{
credentials = options.UseTestCa.Value ? TestCredentials.CreateSslCredentials() : new SslCredentials();
}
if (options.TestCase == "jwt_token_creds")
{
var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();
Assert.IsTrue(googleCredential.IsCreateScopedRequired);
credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials());
}
if (options.TestCase == "compute_engine_creds")
{
var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();
Assert.IsFalse(googleCredential.IsCreateScopedRequired);
credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials());
}
return credentials;
}
private async Task RunTestCaseAsync(Channel channel, ClientOptions options)
{
var client = new TestService.TestServiceClient(channel);
switch (options.TestCase)
{
case "empty_unary":
RunEmptyUnary(client);
break;
case "large_unary":
RunLargeUnary(client);
break;
case "client_streaming":
await RunClientStreamingAsync(client);
break;
case "server_streaming":
await RunServerStreamingAsync(client);
break;
case "ping_pong":
await RunPingPongAsync(client);
break;
case "empty_stream":
await RunEmptyStreamAsync(client);
break;
case "compute_engine_creds":
RunComputeEngineCreds(client, options.DefaultServiceAccount, options.OAuthScope);
break;
case "jwt_token_creds":
RunJwtTokenCreds(client);
break;
case "oauth2_auth_token":
await RunOAuth2AuthTokenAsync(client, options.OAuthScope);
break;
case "per_rpc_creds":
await RunPerRpcCredsAsync(client, options.OAuthScope);
break;
case "cancel_after_begin":
await RunCancelAfterBeginAsync(client);
break;
case "cancel_after_first_response":
await RunCancelAfterFirstResponseAsync(client);
break;
case "timeout_on_sleeping_server":
await RunTimeoutOnSleepingServerAsync(client);
break;
case "custom_metadata":
await RunCustomMetadataAsync(client);
break;
case "status_code_and_message":
await RunStatusCodeAndMessageAsync(client);
break;
case "unimplemented_method":
RunUnimplementedMethod(new UnimplementedService.UnimplementedServiceClient(channel));
break;
default:
throw new ArgumentException("Unknown test case " + options.TestCase);
}
}
public static void RunEmptyUnary(TestService.TestServiceClient client)
{
Console.WriteLine("running empty_unary");
var response = client.EmptyCall(new Empty());
Assert.IsNotNull(response);
Console.WriteLine("Passed!");
}
public static void RunLargeUnary(TestService.TestServiceClient client)
{
Console.WriteLine("running large_unary");
var request = new SimpleRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseSize = 314159,
Payload = CreateZerosPayload(271828)
};
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Console.WriteLine("Passed!");
}
public static async Task RunClientStreamingAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running client_streaming");
var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => new StreamingInputCallRequest { Payload = CreateZerosPayload(size) });
using (var call = client.StreamingInputCall())
{
await call.RequestStream.WriteAllAsync(bodySizes);
var response = await call.ResponseAsync;
Assert.AreEqual(74922, response.AggregatedPayloadSize);
}
Console.WriteLine("Passed!");
}
public static async Task RunServerStreamingAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running server_streaming");
var bodySizes = new List<int> { 31415, 9, 2653, 58979 };
var request = new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { bodySizes.ConvertAll((size) => new ResponseParameters { Size = size }) }
};
using (var call = client.StreamingOutputCall(request))
{
var responseList = await call.ResponseStream.ToListAsync();
foreach (var res in responseList)
{
Assert.AreEqual(PayloadType.COMPRESSABLE, res.Payload.Type);
}
CollectionAssert.AreEqual(bodySizes, responseList.ConvertAll((item) => item.Payload.Body.Length));
}
Console.WriteLine("Passed!");
}
public static async Task RunPingPongAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running ping_pong");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 31415 } },
Payload = CreateZerosPayload(27182)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 9 } },
Payload = CreateZerosPayload(8)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 2653 } },
Payload = CreateZerosPayload(1828)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 58979 } },
Payload = CreateZerosPayload(45904)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(58979, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
Console.WriteLine("Passed!");
}
public static async Task RunEmptyStreamAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running empty_stream");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.CompleteAsync();
var responseList = await call.ResponseStream.ToListAsync();
Assert.AreEqual(0, responseList.Count);
}
Console.WriteLine("Passed!");
}
public static void RunComputeEngineCreds(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope)
{
Console.WriteLine("running compute_engine_creds");
var request = new SimpleRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseSize = 314159,
Payload = CreateZerosPayload(271828),
FillUsername = true,
FillOauthScope = true
};
// not setting credentials here because they were set on channel already
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.False(string.IsNullOrEmpty(response.OauthScope));
Assert.True(oauthScope.Contains(response.OauthScope));
Assert.AreEqual(defaultServiceAccount, response.Username);
Console.WriteLine("Passed!");
}
public static void RunJwtTokenCreds(TestService.TestServiceClient client)
{
Console.WriteLine("running jwt_token_creds");
var request = new SimpleRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseSize = 314159,
Payload = CreateZerosPayload(271828),
FillUsername = true,
};
// not setting credentials here because they were set on channel already
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope)
{
Console.WriteLine("running oauth2_auth_token");
ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope });
string oauth2Token = await credential.GetAccessTokenForRequestAsync();
var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token);
var request = new SimpleRequest
{
FillUsername = true,
FillOauthScope = true
};
var response = client.UnaryCall(request, new CallOptions(credentials: credentials));
Assert.False(string.IsNullOrEmpty(response.OauthScope));
Assert.True(oauthScope.Contains(response.OauthScope));
Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope)
{
Console.WriteLine("running per_rpc_creds");
ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync();
var credentials = googleCredential.ToCallCredentials();
var request = new SimpleRequest
{
FillUsername = true,
};
var response = client.UnaryCall(request, new CallOptions(credentials: credentials));
Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunCancelAfterBeginAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running cancel_after_begin");
var cts = new CancellationTokenSource();
using (var call = client.StreamingInputCall(cancellationToken: cts.Token))
{
// TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it.
await Task.Delay(1000);
cts.Cancel();
var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseAsync);
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
Console.WriteLine("Passed!");
}
public static async Task RunCancelAfterFirstResponseAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running cancel_after_first_response");
var cts = new CancellationTokenSource();
using (var call = client.FullDuplexCall(cancellationToken: cts.Token))
{
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 31415 } },
Payload = CreateZerosPayload(27182)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
cts.Cancel();
var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
Console.WriteLine("Passed!");
}
public static async Task RunTimeoutOnSleepingServerAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running timeout_on_sleeping_server");
var deadline = DateTime.UtcNow.AddMilliseconds(1);
using (var call = client.FullDuplexCall(deadline: deadline))
{
try
{
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { Payload = CreateZerosPayload(27182) });
}
catch (InvalidOperationException)
{
// Deadline was reached before write has started. Eat the exception and continue.
}
catch (RpcException)
{
// Deadline was reached before write has started. Eat the exception and continue.
}
var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
// We can't guarantee the status code always DeadlineExceeded. See issue #2685.
Assert.Contains(ex.Status.StatusCode, new[] { StatusCode.DeadlineExceeded, StatusCode.Internal });
}
Console.WriteLine("Passed!");
}
public static async Task RunCustomMetadataAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running custom_metadata");
{
// step 1: test unary call
var request = new SimpleRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseSize = 314159,
Payload = CreateZerosPayload(271828)
};
var call = client.UnaryCallAsync(request, headers: CreateTestMetadata());
await call.ResponseAsync;
var responseHeaders = await call.ResponseHeadersAsync;
var responseTrailers = call.GetTrailers();
Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value);
CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes);
}
{
// step 2: test full duplex call
var request = new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 31415 } },
Payload = CreateZerosPayload(27182)
};
var call = client.FullDuplexCall(headers: CreateTestMetadata());
var responseHeaders = await call.ResponseHeadersAsync;
await call.RequestStream.WriteAsync(request);
await call.RequestStream.CompleteAsync();
await call.ResponseStream.ToListAsync();
var responseTrailers = call.GetTrailers();
Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value);
CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes);
}
Console.WriteLine("Passed!");
}
public static async Task RunStatusCodeAndMessageAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running status_code_and_message");
var echoStatus = new EchoStatus
{
Code = 2,
Message = "test status message"
};
{
// step 1: test unary call
var request = new SimpleRequest { ResponseStatus = echoStatus };
var e = Assert.Throws<RpcException>(() => client.UnaryCall(request));
Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
Assert.AreEqual(echoStatus.Message, e.Status.Detail);
}
{
// step 2: test full duplex call
var request = new StreamingOutputCallRequest { ResponseStatus = echoStatus };
var call = client.FullDuplexCall();
await call.RequestStream.WriteAsync(request);
await call.RequestStream.CompleteAsync();
var e = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.ToListAsync());
Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
Assert.AreEqual(echoStatus.Message, e.Status.Detail);
}
Console.WriteLine("Passed!");
}
public static void RunUnimplementedMethod(UnimplementedService.UnimplementedServiceClient client)
{
Console.WriteLine("running unimplemented_method");
var e = Assert.Throws<RpcException>(() => client.UnimplementedCall(new Empty()));
Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode);
Assert.AreEqual("", e.Status.Detail);
Console.WriteLine("Passed!");
}
private static Payload CreateZerosPayload(int size)
{
return new Payload { Body = ByteString.CopyFrom(new byte[size]) };
}
// extracts the client_email field from service account file used for auth test cases
private static string GetEmailFromServiceAccountFile()
{
string keyFile = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
Assert.IsNotNull(keyFile);
var jobject = JObject.Parse(File.ReadAllText(keyFile));
string email = jobject.GetValue("client_email").Value<string>();
Assert.IsTrue(email.Length > 0); // spec requires nonempty client email.
return email;
}
private static Metadata CreateTestMetadata()
{
return new Metadata
{
{"x-grpc-test-echo-initial", "test_initial_metadata_value"},
{"x-grpc-test-echo-trailing-bin", new byte[] {0xab, 0xab, 0xab}}
};
}
}
}
| |
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using ImGuiNET;
namespace ImGuizmoNET
{
public static unsafe partial class ImGuizmo
{
public static void AllowAxisFlip(bool value)
{
byte native_value = value ? (byte)1 : (byte)0;
ImGuizmoNative.ImGuizmo_AllowAxisFlip(native_value);
}
public static void BeginFrame()
{
ImGuizmoNative.ImGuizmo_BeginFrame();
}
public static void DecomposeMatrixToComponents(ref float matrix, ref float translation, ref float rotation, ref float scale)
{
fixed (float* native_matrix = &matrix)
{
fixed (float* native_translation = &translation)
{
fixed (float* native_rotation = &rotation)
{
fixed (float* native_scale = &scale)
{
ImGuizmoNative.ImGuizmo_DecomposeMatrixToComponents(native_matrix, native_translation, native_rotation, native_scale);
}
}
}
}
}
public static void DrawCubes(ref float view, ref float projection, ref float matrices, int matrixCount)
{
fixed (float* native_view = &view)
{
fixed (float* native_projection = &projection)
{
fixed (float* native_matrices = &matrices)
{
ImGuizmoNative.ImGuizmo_DrawCubes(native_view, native_projection, native_matrices, matrixCount);
}
}
}
}
public static void DrawGrid(ref float view, ref float projection, ref float matrix, float gridSize)
{
fixed (float* native_view = &view)
{
fixed (float* native_projection = &projection)
{
fixed (float* native_matrix = &matrix)
{
ImGuizmoNative.ImGuizmo_DrawGrid(native_view, native_projection, native_matrix, gridSize);
}
}
}
}
public static void Enable(bool enable)
{
byte native_enable = enable ? (byte)1 : (byte)0;
ImGuizmoNative.ImGuizmo_Enable(native_enable);
}
public static bool IsOver()
{
byte ret = ImGuizmoNative.ImGuizmo_IsOverNil();
return ret != 0;
}
public static bool IsOver(OPERATION op)
{
byte ret = ImGuizmoNative.ImGuizmo_IsOverOPERATION(op);
return ret != 0;
}
public static bool IsUsing()
{
byte ret = ImGuizmoNative.ImGuizmo_IsUsing();
return ret != 0;
}
public static bool Manipulate(ref float view, ref float projection, OPERATION operation, MODE mode, ref float matrix)
{
float* deltaMatrix = null;
float* snap = null;
float* localBounds = null;
float* boundsSnap = null;
fixed (float* native_view = &view)
{
fixed (float* native_projection = &projection)
{
fixed (float* native_matrix = &matrix)
{
byte ret = ImGuizmoNative.ImGuizmo_Manipulate(native_view, native_projection, operation, mode, native_matrix, deltaMatrix, snap, localBounds, boundsSnap);
return ret != 0;
}
}
}
}
public static bool Manipulate(ref float view, ref float projection, OPERATION operation, MODE mode, ref float matrix, ref float deltaMatrix)
{
float* snap = null;
float* localBounds = null;
float* boundsSnap = null;
fixed (float* native_view = &view)
{
fixed (float* native_projection = &projection)
{
fixed (float* native_matrix = &matrix)
{
fixed (float* native_deltaMatrix = &deltaMatrix)
{
byte ret = ImGuizmoNative.ImGuizmo_Manipulate(native_view, native_projection, operation, mode, native_matrix, native_deltaMatrix, snap, localBounds, boundsSnap);
return ret != 0;
}
}
}
}
}
public static bool Manipulate(ref float view, ref float projection, OPERATION operation, MODE mode, ref float matrix, ref float deltaMatrix, ref float snap)
{
float* localBounds = null;
float* boundsSnap = null;
fixed (float* native_view = &view)
{
fixed (float* native_projection = &projection)
{
fixed (float* native_matrix = &matrix)
{
fixed (float* native_deltaMatrix = &deltaMatrix)
{
fixed (float* native_snap = &snap)
{
byte ret = ImGuizmoNative.ImGuizmo_Manipulate(native_view, native_projection, operation, mode, native_matrix, native_deltaMatrix, native_snap, localBounds, boundsSnap);
return ret != 0;
}
}
}
}
}
}
public static bool Manipulate(ref float view, ref float projection, OPERATION operation, MODE mode, ref float matrix, ref float deltaMatrix, ref float snap, ref float localBounds)
{
float* boundsSnap = null;
fixed (float* native_view = &view)
{
fixed (float* native_projection = &projection)
{
fixed (float* native_matrix = &matrix)
{
fixed (float* native_deltaMatrix = &deltaMatrix)
{
fixed (float* native_snap = &snap)
{
fixed (float* native_localBounds = &localBounds)
{
byte ret = ImGuizmoNative.ImGuizmo_Manipulate(native_view, native_projection, operation, mode, native_matrix, native_deltaMatrix, native_snap, native_localBounds, boundsSnap);
return ret != 0;
}
}
}
}
}
}
}
public static bool Manipulate(ref float view, ref float projection, OPERATION operation, MODE mode, ref float matrix, ref float deltaMatrix, ref float snap, ref float localBounds, ref float boundsSnap)
{
fixed (float* native_view = &view)
{
fixed (float* native_projection = &projection)
{
fixed (float* native_matrix = &matrix)
{
fixed (float* native_deltaMatrix = &deltaMatrix)
{
fixed (float* native_snap = &snap)
{
fixed (float* native_localBounds = &localBounds)
{
fixed (float* native_boundsSnap = &boundsSnap)
{
byte ret = ImGuizmoNative.ImGuizmo_Manipulate(native_view, native_projection, operation, mode, native_matrix, native_deltaMatrix, native_snap, native_localBounds, native_boundsSnap);
return ret != 0;
}
}
}
}
}
}
}
}
public static void RecomposeMatrixFromComponents(ref float translation, ref float rotation, ref float scale, ref float matrix)
{
fixed (float* native_translation = &translation)
{
fixed (float* native_rotation = &rotation)
{
fixed (float* native_scale = &scale)
{
fixed (float* native_matrix = &matrix)
{
ImGuizmoNative.ImGuizmo_RecomposeMatrixFromComponents(native_translation, native_rotation, native_scale, native_matrix);
}
}
}
}
}
public static void SetDrawlist()
{
ImDrawList* drawlist = null;
ImGuizmoNative.ImGuizmo_SetDrawlist(drawlist);
}
public static void SetDrawlist(ImDrawListPtr drawlist)
{
ImDrawList* native_drawlist = drawlist.NativePtr;
ImGuizmoNative.ImGuizmo_SetDrawlist(native_drawlist);
}
public static void SetGizmoSizeClipSpace(float value)
{
ImGuizmoNative.ImGuizmo_SetGizmoSizeClipSpace(value);
}
public static void SetID(int id)
{
ImGuizmoNative.ImGuizmo_SetID(id);
}
public static void SetImGuiContext(IntPtr ctx)
{
ImGuizmoNative.ImGuizmo_SetImGuiContext(ctx);
}
public static void SetOrthographic(bool isOrthographic)
{
byte native_isOrthographic = isOrthographic ? (byte)1 : (byte)0;
ImGuizmoNative.ImGuizmo_SetOrthographic(native_isOrthographic);
}
public static void SetRect(float x, float y, float width, float height)
{
ImGuizmoNative.ImGuizmo_SetRect(x, y, width, height);
}
public static void ViewManipulate(ref float view, float length, Vector2 position, Vector2 size, uint backgroundColor)
{
fixed (float* native_view = &view)
{
ImGuizmoNative.ImGuizmo_ViewManipulate(native_view, length, position, size, backgroundColor);
}
}
}
}
| |
using System;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Reactive.Subjects;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
namespace ReactiveUIMicro.Xaml
{
/// <summary>
/// Describes a stock error icon situation - it is up to the UI to decide
/// how to interpret these icons.
/// </summary>
public enum StockUserErrorIcon {
Critical,
Error,
Question,
Warning,
Notice,
};
/// <summary>
/// RecoveryOptionResult describes to the code throwing the UserError what
/// to do once the error is resolved.
/// </summary>
public enum RecoveryOptionResult {
/// <summary>
/// The operation should be cancelled, but it is no longer an error.
/// </summary>
CancelOperation,
/// <summary>
/// The operation should be retried with the same parameters.
/// </summary>
RetryOperation,
/// <summary>
/// Recovery failed or not possible, you should rethrow as an
/// Exception.
/// </summary>
FailOperation,
};
/// <summary>
/// User Errors are similar to Exceptions, except that they are intended
/// to be displayed to the user. As such, your error messages should be
/// phrased in a friendly way. When a UserError is thrown, code higher up
/// in the stack has a chance to resolve the UserError via a user
/// interaction.
///
/// Code can also add "Recovery Options" which resolve user errors: for
/// example an "Out of Disk Space" error might have an "Open Explorer"
/// recovery option.
/// </summary>
public class UserError : ReactiveObject
{
public UserError(
string errorMessage,
string errorCauseOrResolution = null,
IEnumerable<RecoveryCommand> recoveryOptions = null,
Dictionary<string, object> contextInfo = null,
Exception innerException = null)
{
RecoveryOptions = new ReactiveCollection<RecoveryCommand>(recoveryOptions ?? Enumerable.Empty<RecoveryCommand>());
ErrorCauseOrResolution = errorCauseOrResolution;
ContextInfo = contextInfo ?? new Dictionary<string, object>();
UserErrorIcon = StockUserErrorIcon.Warning;
InnerException = innerException;
ErrorMessage = errorMessage;
#if WINRT
// NB: I want to do something with CallerMemberNameAttribute here
// eventually
Domain = "";
#else
Domain = Assembly.GetCallingAssembly().FullName;
#endif
}
/// <summary>
/// The component that originally threw the error - if this is not
/// supplied, it defaults to the assembly name.
/// </summary>
public string Domain { get; protected set; }
/// <summary>
/// A Dictionary that allows UserErrors to contain arbitrary
/// application data.
/// </summary>
public Dictionary<string, object> ContextInfo { get; protected set; }
ReactiveCollection<RecoveryCommand> _RecoveryOptions;
/// <summary>
/// The list of available Recovery Options that will be presented to
/// the user to resolve the issue - these usually correspond to
/// buttons in the dialog.
/// </summary>
public ReactiveCollection<RecoveryCommand> RecoveryOptions {
get { return _RecoveryOptions; }
protected set { this.RaiseAndSetIfChanged(x => x.RecoveryOptions, ref _RecoveryOptions, value); }
}
/// <summary>
/// The "Newspaper Headline" of the message being conveyed to the
/// user. This should be one line, short, and informative.
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Additional optional information to describe what is happening, or
/// the resolution to an information-only error (i.e. a dialog to tell
/// the user that something has happened)
/// </summary>
public string ErrorCauseOrResolution { get; set; }
/// <summary>
/// This object is either a custom icon (usually an ImageSource), or
/// it can also be a StockUserErrorIcon. It can also be an
/// application-defined type that the handlers know to interpret.
/// </summary>
public object UserErrorIcon { get; set; }
/// <summary>
/// Optionally, The actual Exception that warranted throwing the
/// UserError.
/// </summary>
public Exception InnerException { get; protected set; }
//
// Static API
//
[ThreadStatic] static Func<UserError, IObservable<RecoveryOptionResult>> overriddenRegisteredUserErrorHandlers;
static readonly List<Func<UserError, IObservable<RecoveryOptionResult>>> registeredUserErrorHandlers = new List<Func<UserError, IObservable<RecoveryOptionResult>>>();
/// <summary>
/// Initiate a user interaction (i.e. "Throw the error to the user to
/// deal with") - this method is the simplest way to prompt the user
/// that an error has occurred.
/// </summary>
/// <param name="errorMessage">The message to show to the user. The
/// upper level handlers registered with RegisterHandler are
/// ultimately responsible for displaying this information.</param>
/// <param name="innerException">The Exception that was thrown, if
/// relevant - this will *not* ever be shown to the user.</param>
/// <returns>An Observable representing the action the code should
/// attempt to take, if any.</returns>
public static IObservable<RecoveryOptionResult> Throw(string errorMessage, Exception innerException = null)
{
return Throw(new UserError(errorMessage, innerException: innerException));
}
/// <summary>
/// Initiate a user interaction (i.e. "Throw the error to the user to
/// deal with").
/// </summary>
/// <param name="error">The UserError to show to the user. The
/// upper level handlers registered with RegisterHandler are
/// ultimately responsible for displaying this information. </param>
/// <returns></returns>
public static IObservable<RecoveryOptionResult> Throw(UserError error)
{
var handlers = (overriddenRegisteredUserErrorHandlers != null) ?
new[] { overriddenRegisteredUserErrorHandlers } :
registeredUserErrorHandlers.ToArray().Reverse();
// NB: This is a little complicated - here's the idea: we have a
// list of handlers that we're running down *in order*. If we find
// one that doesn't return null, we're going to return this as an
// Observable with one item (the result).
//
// If *none* of the handlers are interested in this UserError, we're
// going to OnError the Observable.
var handler = handlers.Select(x => x(error)).FirstOrDefault(x => x != null) ?? Observable.Empty<RecoveryOptionResult>()
.Concat(Observable.Throw<RecoveryOptionResult>(new UnhandledUserErrorException(error)));
var ret = handler.Take(1).PublishLast();
ret.Connect();
return ret;
}
/// <summary>
/// Register code to handle a UserError. Registered handlers are
/// called in reverse order to their registration (i.e. the newest
/// handler is called first), and they each have a chance to handle a
/// UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler(Func<UserError, IObservable<RecoveryOptionResult>> errorHandler)
{
registeredUserErrorHandlers.Add(errorHandler);
return Disposable.Create(() => registeredUserErrorHandlers.Remove(errorHandler));
}
/// <summary>
/// Register code to handle a specific type of UserError. Registered
/// handlers are called in reverse order to their registration (i.e.
/// the newest handler is called first), and they each have a chance
/// to handle a UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler<TException>(Func<TException, IObservable<RecoveryOptionResult>> errorHandler)
where TException : UserError
{
return RegisterHandler(x => {
if (!(x is TException)) {
return null;
}
return errorHandler((TException) x);
});
}
/// <summary>
/// Register code to handle a UserError. Registered handlers are
/// called in reverse order to their registration (i.e. the newest
/// handler is called first), and they each have a chance to handle a
/// UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler(Func<UserError, Task<RecoveryOptionResult>> errorHandler)
{
return RegisterHandler(x => errorHandler(x).ToObservable());
}
/// <summary>
/// Register code to handle a specific type of UserError. Registered
/// handlers are called in reverse order to their registration (i.e.
/// the newest handler is called first), and they each have a chance
/// to handle a UserError.
///
/// If a Handler cannot resolve a UserError, it should return null
/// instead of an Observable result.
/// </summary>
/// <param name="errorHandler">A method that can handle a UserError,
/// usually by presenting it to the user. If the handler cannot handle
/// the error, it should return null.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable RegisterHandler<TException>(Func<TException, Task<RecoveryOptionResult>> errorHandler)
where TException : UserError
{
return RegisterHandler(x => {
if (!(x is TException)) {
return null;
}
return errorHandler((TException)x).ToObservable();
});
}
/// <summary>
/// This method is a convenience wrapper around RegisterHandler that
/// adds the specified RecoveryCommand to any UserErrors that match
/// its filter.
/// </summary>
/// <param name="command">The RecoveryCommand to add.</param>
/// <param name="filter">An optional filter to determine which
/// UserErrors to add the command to.</param>
/// <returns>An IDisposable which will unregister the handler.</returns>
public static IDisposable AddRecoveryOption(RecoveryCommand command, Func<UserError, bool> filter = null)
{
return RegisterHandler(x => {
if (filter != null && !filter(x)) {
return null;
}
if (!x.RecoveryOptions.Contains(command)) {
x.RecoveryOptions.Add(command);
}
return Observable.Empty<RecoveryOptionResult>();
});
}
/// <summary>
/// This method replaces *all* UserError handlers with the specified
/// handler. Use it for testing code that may throw UserErrors.
/// </summary>
/// <param name="errorHandler">The replacement UserError handler.</param>
/// <returns>An IDisposable which will unregister the test handler.</returns>
public static IDisposable OverrideHandlersForTesting(Func<UserError, IObservable<RecoveryOptionResult>> errorHandler)
{
overriddenRegisteredUserErrorHandlers = errorHandler;
return Disposable.Create(() => overriddenRegisteredUserErrorHandlers = null);
}
/// <summary>
/// This method replaces *all* UserError handlers with the specified
/// handler. Use it for testing code that may throw UserErrors.
/// </summary>
/// <param name="errorHandler">The replacement UserError handler.</param>
/// <returns>An IDisposable which will unregister the test handler.</returns>
public static IDisposable OverrideHandlersForTesting(Func<UserError, RecoveryOptionResult> errorHandler)
{
return OverrideHandlersForTesting(x => Observable.Return(errorHandler(x)));
}
}
/// <summary>
/// This Exception will be thrown when a UserError is not handled by any
/// of the registered handlers.
/// </summary>
public class UnhandledUserErrorException : Exception
{
public UnhandledUserErrorException(UserError error) : base(error.ErrorMessage, error.InnerException)
{
ReportedError = error;
}
public UserError ReportedError { get; protected set; }
}
/// <summary>
/// RecoveryCommand is a straightforward implementation of a recovery
/// command - this class represents a command presented to the user
/// (usually in the form of a button) that will help resolve or mitigate a
/// UserError.
/// </summary>
public class RecoveryCommand : ReactiveCommand
{
public bool IsDefault { get; set; }
public bool IsCancel { get; set; }
public string CommandName { get; protected set; }
public RecoveryOptionResult? RecoveryResult { get; set; }
/// <summary>
/// Constructs a RecoveryCommand.
/// </summary>
/// <param name="commandName">The user-visible name of this Command.</param>
/// <param name="handler">A convenience handler - equivalent to
/// Subscribing to the command and setting the RecoveryResult.</param>
public RecoveryCommand(string commandName, Func<object, RecoveryOptionResult> handler = null)
{
CommandName = commandName;
if (handler != null) {
this.Subscribe(x => RecoveryResult = handler(x));
}
}
public static RecoveryCommand Ok {
get { var ret = new RecoveryCommand("Ok") { IsDefault = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.RetryOperation); return ret; }
}
public static RecoveryCommand Cancel {
get { var ret = new RecoveryCommand("Cancel") { IsCancel = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.FailOperation); return ret; }
}
public static RecoveryCommand Yes {
get { var ret = new RecoveryCommand("Yes") { IsDefault = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.RetryOperation); return ret; }
}
public static RecoveryCommand No {
get { var ret = new RecoveryCommand("No") { IsCancel = true }; ret.Subscribe(_ => ret.RecoveryResult = RecoveryOptionResult.FailOperation); return ret; }
}
}
}
// vim: tw=120 ts=4 sw=4 et :
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeDynaItem (dynamic root object).<br/>
/// This is a generated <see cref="ProductTypeDynaItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="ProductTypeDynaColl"/> collection.
/// </remarks>
[Serializable]
public partial class ProductTypeDynaItem : BusinessBase<ProductTypeDynaItem>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductTypeId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id");
/// <summary>
/// Gets the Product Type Id.
/// </summary>
/// <value>The Product Type Id.</value>
public int ProductTypeId
{
get { return GetProperty(ProductTypeIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeDynaItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeDynaItem()
{
// Use factory methods and do not use direct creation.
Saved += OnProductTypeDynaItemSaved;
ProductTypeDynaItemSaved += ProductTypeDynaItemSavedHandler;
}
#endregion
#region Cache Invalidation
// TODO: edit "ProductTypeDynaItem.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: ProductTypeDynaItemSaved += ProductTypeDynaItemSavedHandler;
private void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
// this runs on the client
ProductTypeCachedList.InvalidateCache();
ProductTypeCachedNVL.InvalidateCache();
}
/// <summary>
/// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e)
{
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server &&
e.Operation == DataPortalOperations.Update)
{
// this runs on the server
ProductTypeCachedNVL.InvalidateCache();
}
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="ProductTypeDynaItem"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(ProductTypeIdProperty, System.Threading.Interlocked.Decrement(ref _lastId));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="ProductTypeDynaItem"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void DataPortal_Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId"));
LoadProperty(NameProperty, dr.GetString("Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="ProductTypeDynaItem"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false))
{
using (var cmd = new SqlCommand("dbo.AddProductTypeDynaItem", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(ProductTypeIdProperty, (int) cmd.Parameters["@ProductTypeId"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductTypeDynaItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false))
{
using (var cmd = new SqlCommand("dbo.UpdateProductTypeDynaItem", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="ProductTypeDynaItem"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(ProductTypeId);
}
/// <summary>
/// Deletes the <see cref="ProductTypeDynaItem"/> object from database.
/// </summary>
/// <param name="productTypeId">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
protected void DataPortal_Delete(int productTypeId)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false))
{
using (var cmd = new SqlCommand("dbo.DeleteProductTypeDynaItem", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductTypeId", productTypeId).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, productTypeId);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Saved Event
// TODO: edit "ProductTypeDynaItem.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: Saved += OnProductTypeDynaItemSaved;
private void OnProductTypeDynaItemSaved(object sender, Csla.Core.SavedEventArgs e)
{
if (ProductTypeDynaItemSaved != null)
ProductTypeDynaItemSaved(sender, e);
}
/// <summary> Use this event to signal a <see cref="ProductTypeDynaItem"/> object was saved.</summary>
public static event EventHandler<Csla.Core.SavedEventArgs> ProductTypeDynaItemSaved;
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE4.1 hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public abstract class Sse41 : Ssse3
{
internal Sse41() { }
public new static bool IsSupported { get { return false; } }
public new abstract class X64 : Sse2.X64
{
internal X64() { }
public new static bool IsSupported { get { return false; } }
/// <summary>
/// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
/// PEXTRQ reg/m64, xmm, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static long Extract(Vector128<long> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
/// PEXTRQ reg/m64, xmm, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static ulong Extract(Vector128<ulong> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
/// PINSRQ xmm, reg/m64, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static Vector128<long> Insert(Vector128<long> value, long data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
/// PINSRQ xmm, reg/m64, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static Vector128<ulong> Insert(Vector128<ulong> value, ulong data, byte index) { throw new PlatformNotSupportedException(); }
}
/// <summary>
/// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
/// PBLENDW xmm, xmm/m128 imm8
/// </summary>
public static Vector128<short> Blend(Vector128<short> left, Vector128<short> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
/// PBLENDW xmm, xmm/m128 imm8
/// </summary>
public static Vector128<ushort> Blend(Vector128<ushort> left, Vector128<ushort> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8)
/// BLENDPS xmm, xmm/m128, imm8
/// </summary>
public static Vector128<float> Blend(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8)
/// BLENDPD xmm, xmm/m128, imm8
/// </summary>
public static Vector128<double> Blend(Vector128<double> left, Vector128<double> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// </summary>
public static Vector128<sbyte> BlendVariable(Vector128<sbyte> left, Vector128<sbyte> right, Vector128<sbyte> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// </summary>
public static Vector128<byte> BlendVariable(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<short> BlendVariable(Vector128<short> left, Vector128<short> right, Vector128<short> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<ushort> BlendVariable(Vector128<ushort> left, Vector128<ushort> right, Vector128<ushort> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<int> BlendVariable(Vector128<int> left, Vector128<int> right, Vector128<int> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<uint> BlendVariable(Vector128<uint> left, Vector128<uint> right, Vector128<uint> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<long> BlendVariable(Vector128<long> left, Vector128<long> right, Vector128<long> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<ulong> BlendVariable(Vector128<ulong> left, Vector128<ulong> right, Vector128<ulong> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask)
/// BLENDVPS xmm, xmm/m128, xmm0
/// </summary>
public static Vector128<float> BlendVariable(Vector128<float> left, Vector128<float> right, Vector128<float> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask)
/// BLENDVPD xmm, xmm/m128, xmm0
/// </summary>
public static Vector128<double> BlendVariable(Vector128<double> left, Vector128<double> right, Vector128<double> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ps (__m128 a)
/// ROUNDPS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> Ceiling(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_pd (__m128d a)
/// ROUNDPD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> Ceiling(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_sd (__m128d a)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> CeilingScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ss (__m128 a)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> CeilingScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_sd (__m128d a, __m128d b)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> CeilingScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ss (__m128 a, __m128 b)
/// ROUNDSS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> CeilingScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
/// PCMPEQQ xmm, xmm/m128
/// </summary>
public static Vector128<long> CompareEqual(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
/// PCMPEQQ xmm, xmm/m128
/// </summary>
public static Vector128<ulong> CompareEqual(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi16 (__m128i a)
/// PMOVSXBW xmm, xmm/m64
/// </summary>
public static Vector128<short> ConvertToVector128Int16(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi16 (__m128i a)
/// PMOVZXBW xmm, xmm/m64
/// </summary>
public static Vector128<short> ConvertToVector128Int16(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi32 (__m128i a)
/// PMOVSXBD xmm, xmm/m32
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi32 (__m128i a)
/// PMOVZXBD xmm, xmm/m32
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi16_epi32 (__m128i a)
/// PMOVSXWD xmm, xmm/m64
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<short> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu16_epi32 (__m128i a)
/// PMOVZXWD xmm, xmm/m64
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi64 (__m128i a)
/// PMOVSXBQ xmm, xmm/m16
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi64 (__m128i a)
/// PMOVZXBQ xmm, xmm/m16
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi16_epi64 (__m128i a)
/// PMOVSXWQ xmm, xmm/m32
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<short> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu16_epi64 (__m128i a)
/// PMOVZXWQ xmm, xmm/m32
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi32_epi64 (__m128i a)
/// PMOVSXDQ xmm, xmm/m64
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<int> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu32_epi64 (__m128i a)
/// PMOVZXDQ xmm, xmm/m64
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<uint> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_dp_ps (__m128 a, __m128 b, const int imm8)
/// DPPS xmm, xmm/m128, imm8
/// </summary>
public static Vector128<float> DotProduct(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_dp_pd (__m128d a, __m128d b, const int imm8)
/// DPPD xmm, xmm/m128, imm8
/// </summary>
public static Vector128<double> DotProduct(Vector128<double> left, Vector128<double> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi8 (__m128i a, const int imm8)
/// PEXTRB reg/m8, xmm, imm8
/// </summary>
public static byte Extract(Vector128<byte> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi32 (__m128i a, const int imm8)
/// PEXTRD reg/m32, xmm, imm8
/// </summary>
public static int Extract(Vector128<int> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi32 (__m128i a, const int imm8)
/// PEXTRD reg/m32, xmm, imm8
/// </summary>
public static uint Extract(Vector128<uint> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_ps (__m128 a, const int imm8)
/// EXTRACTPS xmm, xmm/m32, imm8
/// </summary>
public static float Extract(Vector128<float> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ps (__m128 a)
/// ROUNDPS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> Floor(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_pd (__m128d a)
/// ROUNDPD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> Floor(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_sd (__m128d a)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> FloorScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ss (__m128 a)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> FloorScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_sd (__m128d a, __m128d b)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> FloorScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ss (__m128 a, __m128 b)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> FloorScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
/// PINSRB xmm, reg/m8, imm8
/// </summary>
public static Vector128<sbyte> Insert(Vector128<sbyte> value, sbyte data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
/// PINSRB xmm, reg/m8, imm8
/// </summary>
public static Vector128<byte> Insert(Vector128<byte> value, byte data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
/// PINSRD xmm, reg/m32, imm8
/// </summary>
public static Vector128<int> Insert(Vector128<int> value, int data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
/// PINSRD xmm, reg/m32, imm8
/// </summary>
public static Vector128<uint> Insert(Vector128<uint> value, uint data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8)
/// INSERTPS xmm, xmm/m32, imm8
/// </summary>
public static Vector128<float> Insert(Vector128<float> value, Vector128<float> data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epi8 (__m128i a, __m128i b)
/// PMAXSB xmm, xmm/m128
/// </summary>
public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epu16 (__m128i a, __m128i b)
/// PMAXUW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epi32 (__m128i a, __m128i b)
/// PMAXSD xmm, xmm/m128
/// </summary>
public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epu32 (__m128i a, __m128i b)
/// PMAXUD xmm, xmm/m128
/// </summary>
public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epi8 (__m128i a, __m128i b)
/// PMINSB xmm, xmm/m128
/// </summary>
public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epu16 (__m128i a, __m128i b)
/// PMINUW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epi32 (__m128i a, __m128i b)
/// PMINSD xmm, xmm/m128
/// </summary>
public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epu32 (__m128i a, __m128i b)
/// PMINUD xmm, xmm/m128
/// </summary>
public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_minpos_epu16 (__m128i a)
/// PHMINPOSUW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> MinHorizontal(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8)
/// MPSADBW xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> MultipleSumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right, byte mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mul_epi32 (__m128i a, __m128i b)
/// PMULDQ xmm, xmm/m128
/// </summary>
public static Vector128<long> Multiply(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mullo_epi32 (__m128i a, __m128i b)
/// PMULLD xmm, xmm/m128
/// </summary>
public static Vector128<int> MultiplyLow(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mullo_epi32 (__m128i a, __m128i b)
/// PMULLD xmm, xmm/m128
/// </summary>
public static Vector128<uint> MultiplyLow(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_packus_epi32 (__m128i a, __m128i b)
/// PACKUSDW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> PackUnsignedSaturate(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ps (__m128 a, int rounding)
/// ROUNDPS xmm, xmm/m128, imm8(8)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToNearestInteger(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> RoundToNegativeInfinity(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> RoundToPositiveInfinity(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<float> RoundToZero(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION; ROUNDPS xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<float> RoundCurrentDirection(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_pd (__m128d a, int rounding)
/// ROUNDPD xmm, xmm/m128, imm8(8)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToNearestInteger(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> RoundToNegativeInfinity(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> RoundToPositiveInfinity(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<double> RoundToZero(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION; ROUNDPD xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<double> RoundCurrentDirection(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSD xmm, xmm/m128, imm8(4)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundCurrentDirectionScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(8)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToNearestIntegerScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToNegativeInfinityScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToPositiveInfinityScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(11)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToZeroScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSD xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<double> RoundCurrentDirectionScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(8)
/// </summary>
public static Vector128<double> RoundToNearestIntegerScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> RoundToNegativeInfinityScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> RoundToPositiveInfinityScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<double> RoundToZeroScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSS xmm, xmm/m128, imm8(4)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundCurrentDirectionScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(8)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToNearestIntegerScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToNegativeInfinityScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToPositiveInfinityScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(11)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToZeroScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSS xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<float> RoundCurrentDirectionScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(8)
/// </summary>
public static Vector128<float> RoundToNearestIntegerScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> RoundToNegativeInfinityScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> RoundToPositiveInfinityScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<float> RoundToZeroScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<sbyte> LoadAlignedVector128NonTemporal(sbyte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<byte> LoadAlignedVector128NonTemporal(byte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<short> LoadAlignedVector128NonTemporal(short* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<ushort> LoadAlignedVector128NonTemporal(ushort* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<int> LoadAlignedVector128NonTemporal(int* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<uint> LoadAlignedVector128NonTemporal(uint* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<long> LoadAlignedVector128NonTemporal(long* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<ulong> LoadAlignedVector128NonTemporal(ulong* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_test_all_ones (__m128i a)
/// PCMPEQD xmm, xmm/m128
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestAllOnes(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<short> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<int> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<uint> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<long> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<ulong> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_test_all_zeros (__m128i a, __m128i mask)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestAllZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testc_si128 (__m128i a, __m128i b)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_test_mix_ones_zeros (__m128i a, __m128i mask)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestMixOnesZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testnzc_si128 (__m128i a, __m128i b)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestNotZAndNotC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testz_si128 (__m128i a, __m128i b)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestZ(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
}
}
| |
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
namespace UnityEditor
{
public abstract class BasePropertyDrawer<T> : PropertyDrawer
{
protected const BindingFlags FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
protected static readonly System.Type IListType = typeof(IList);
protected const float ITEM_HEIGHT = 16f;
protected const float EXTENDED_HEIGHT = 18f;
protected const float ITEM_OFFSET = 6f;
protected const float RIGHTMOST_MARGIN = 4.5f;
protected Object target;
protected abstract float PrimaryHeight { get; }
protected abstract float SecondaryHeight { get; }
public sealed override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
this.target = property.serializedObject.targetObject;
var targetMonoBehaviour = true;
var targets = new List<object>();
var infos = new List<IndexOrInfo>();
var values = new List<object>();
var value = default(T);
try
{
value = (T) this.fieldInfo.GetValue(target);
}
catch
{
targetMonoBehaviour = false;
if (!TryParsePropertyPath(property.propertyPath, this.target, ref targets, ref infos, ref values))
return;
try
{
value = (T) values[values.Count - 1];
}
catch
{
return;
}
}
label = EditorGUI.BeginProperty(position, label, property);
var contentPosition = EditorGUI.PrefixLabel(position, label, GUI.skin.label);
contentPosition = AdjustContentPosition(position, contentPosition);
EditorGUI.indentLevel = 0;
DrawProperty(contentPosition, ref value);
if (targetMonoBehaviour)
{
this.fieldInfo.SetValue(this.target, value);
}
else
{
SetValue(ref value, targets, infos, values);
}
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return Screen.width < 333 ? this.SecondaryHeight : this.PrimaryHeight;
}
protected virtual Rect AdjustContentPosition(Rect position, Rect contentPosition)
{
if (position.height > this.PrimaryHeight)
{
position.height = ITEM_HEIGHT;
EditorGUI.indentLevel += 1;
contentPosition = EditorGUI.IndentedRect(position);
contentPosition.y += EXTENDED_HEIGHT;
}
else
{
contentPosition.height = ITEM_HEIGHT;
}
return contentPosition;
}
protected abstract void DrawProperty(Rect contentPosition, ref T value);
protected void SetAndRecord<U>(ref U source, ref U value) where U : System.IEquatable<U>
{
if (!source.Equals(value))
{
Undo.RecordObject(this.target, "SetValue");
source = value;
}
}
protected void SetAndRecord<U>(Rect rect, string label, ref U source, System.Func<Rect, string, U, U> display)
{
if (this.target == null)
return;
EditorGUI.BeginChangeCheck();
var newValue = display(rect, label, source);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(this.target, "SetValue");
source = newValue;
}
}
private bool TryParsePropertyPath(string propertyPath, Object firstTarget, ref List<object> targets, ref List<IndexOrInfo> infos, ref List<object> values)
{
targets.Add(firstTarget);
var path = propertyPath.Replace("Array.data", string.Empty);
var levels = path.Split(new[] { '.' });
var index = -1;
var lastLevelIndex = levels.Length - 1;
for (var i = 0; i < levels.Length; ++i)
{
var level = levels[i];
var target = targets[targets.Count - 1];
try
{
var targetType = target.GetType();
if (level[0] == '[' && level[level.Length - 1] == ']')
{
if (!targetType.GetInterfaces().Contains(IListType))
return false;
if (targetType.IsArray && targetType.GetArrayRank() > 1)
return false;
var indexStr = level.Substring(1, level.Length - 2);
if (!int.TryParse(indexStr, out index))
{
return false;
}
var list = (IList) target;
if (list == null)
return false;
if (index >= list.Count)
return false;
infos.Add(IndexOrInfo.New(index));
values.Add(list[index]);
if (i < lastLevelIndex)
targets.Add(values[values.Count - 1]);
}
else
{
var info = targetType.GetField(level, FLAGS);
if (info == null)
return false;
infos.Add(IndexOrInfo.New(info));
values.Add(info.GetValue(target));
if (i < lastLevelIndex)
targets.Add(values[values.Count - 1]);
}
}
catch (System.Exception ex)
{
Debug.LogErrorFormat("{0}\n{1}", ex.Message, ex.StackTrace);
return false;
}
}
return true;
}
private void SetValue(ref T newValue, List<object> targets, List<IndexOrInfo> infos, List<object> values)
{
var last = targets.Count - 1;
values[last] = newValue;
object val = values[last];
for (var i = last; i >= 0; --i)
{
var target = targets[i];
var info = infos[i];
if (info.IsIndex)
{
var list = (IList) target;
list[info.index] = val;
}
else if (info.info != null)
{
info.info.SetValue(target, val);
}
val = target;
}
}
protected struct IndexOrInfo
{
public int index { get; private set; }
public FieldInfo info { get; private set; }
public bool IsIndex
{
get { return this.index >= 0; }
}
public bool IsEmpty
{
get { return this.index < 0 && this.info == null; }
}
private IndexOrInfo(int index, FieldInfo info)
{
this.index = index;
this.info = info;
}
public static IndexOrInfo New(int index)
{
return new IndexOrInfo(index, null);
}
public static IndexOrInfo New(FieldInfo info)
{
return new IndexOrInfo(-1, info);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Threading.Tasks.Tests
{
public class TaskAwaiterTests
{
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(false, null)]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(true, null)]
public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool? continueOnCapturedContext)
{
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
// Create a context that tracks operations, and set it as current
var validateCtx = new ValidateCorrectContextSynchronizationContext();
Assert.Equal(0, validateCtx.PostCount);
SynchronizationContext.SetSynchronizationContext(validateCtx);
// Create a not-completed task and get an awaiter for it
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
// Hook up a callback
bool postedInContext = false;
Action callback = () =>
{
postedInContext = ValidateCorrectContextSynchronizationContext.t_isPostedInContext;
mres.Set();
};
if (generic)
{
if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else tcs.Task.GetAwaiter().OnCompleted(callback);
}
else
{
if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
}
Assert.False(mres.IsSet, "Callback should not yet have run.");
// Complete the task in another context and wait for the callback to run
Task.Run(() => tcs.SetResult(null));
mres.Wait();
// Validate the callback ran and in the correct context
bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount);
Assert.Equal(shouldHavePosted, postedInContext);
}
finally
{
// Reset back to the original context
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(false, null)]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(true, null)]
public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool? continueOnCapturedContext)
{
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await
var quwi = new QUWITaskScheduler();
RunWithSchedulerAsCurrent(quwi, delegate
{
Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler");
// Create the not completed task and get its awaiter
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
// Hook up the callback
bool ranOnScheduler = false;
Action callback = () =>
{
ranOnScheduler = (TaskScheduler.Current == quwi);
mres.Set();
};
if (generic)
{
if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else tcs.Task.GetAwaiter().OnCompleted(callback);
}
else
{
if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
}
Assert.False(mres.IsSet, "Callback should not yet have run.");
// Complete the task in another scheduler and wait for the callback to run
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
// Validate the callback ran on the right scheduler
bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler);
});
}
finally
{
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Fact]
public async Task Await_TaskCompletesOnNonDefaultSyncCtx_ContinuesOnDefaultSyncCtx()
{
await Task.Run(async delegate // escape xunit's sync context
{
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
var ctx = new ValidateCorrectContextSynchronizationContext();
var tcs = new TaskCompletionSource<bool>();
var ignored = Task.Delay(1).ContinueWith(_ =>
{
SynchronizationContext orig = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(ctx);
try
{
tcs.SetResult(true);
}
finally
{
SynchronizationContext.SetSynchronizationContext(orig);
}
}, TaskScheduler.Default);
await tcs.Task;
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
});
}
[Fact]
public async Task Await_TaskCompletesOnNonDefaultScheduler_ContinuesOnDefaultScheduler()
{
await Task.Run(async delegate // escape xunit's sync context
{
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
var tcs = new TaskCompletionSource<bool>();
var ignored = Task.Delay(1).ContinueWith(_ => tcs.SetResult(true), new QUWITaskScheduler());
await tcs.Task;
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
});
}
public static IEnumerable<object[]> Await_MultipleAwaits_FirstCompletesAccordingToOptions_RestCompleteAsynchronously_MemberData()
{
foreach (int numContinuations in new[] { 1, 2, 5 })
foreach (bool runContinuationsAsynchronously in new[] { false, true })
foreach (bool valueTask in new[] { false, true })
foreach (object scheduler in new object[] { null, new QUWITaskScheduler(), new ValidateCorrectContextSynchronizationContext() })
yield return new object[] { numContinuations, runContinuationsAsynchronously, valueTask, scheduler };
}
[Theory]
[MemberData(nameof(Await_MultipleAwaits_FirstCompletesAccordingToOptions_RestCompleteAsynchronously_MemberData))]
public async Task Await_MultipleAwaits_FirstCompletesAccordingToOptions_RestCompleteAsynchronously(
int numContinuations, bool runContinuationsAsynchronously, bool valueTask, object scheduler)
{
await Task.Factory.StartNew(async delegate
{
if (scheduler is SynchronizationContext sc)
{
SynchronizationContext.SetSynchronizationContext(sc);
}
var tcs = runContinuationsAsynchronously ? new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously) : new TaskCompletionSource<bool>();
var tl = new ThreadLocal<int>();
var tasks = new List<Task>();
for (int i = 1; i <= numContinuations; i++)
{
bool expectedSync = i == 1 && !runContinuationsAsynchronously;
tasks.Add(ThenAsync(tcs.Task, () =>
{
Assert.Equal(expectedSync ? 42 : 0, tl.Value);
switch (scheduler)
{
case null:
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
Assert.Null(SynchronizationContext.Current);
break;
case TaskScheduler ts:
Assert.Same(ts, TaskScheduler.Current);
Assert.Null(SynchronizationContext.Current);
break;
case SynchronizationContext sc:
Assert.Same(sc, SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
break;
}
}));
async Task ThenAsync(Task task, Action action)
{
if (valueTask)
{
await new ValueTask(task);
}
else
{
await task;
}
action();
}
}
Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));
tl.Value = 42;
tcs.SetResult(true);
tl.Value = 0;
SynchronizationContext.SetSynchronizationContext(null);
await Task.WhenAll(tasks);
}, CancellationToken.None, TaskCreationOptions.None, scheduler as TaskScheduler ?? TaskScheduler.Default).Unwrap();
}
[Fact]
public static void GetResult_Completed_Success()
{
Task task = Task.CompletedTask;
task.GetAwaiter().GetResult();
task.ConfigureAwait(false).GetAwaiter().GetResult();
task.ConfigureAwait(true).GetAwaiter().GetResult();
const string expectedResult = "42";
Task<string> taskOfString = Task.FromResult(expectedResult);
Assert.Equal(expectedResult, taskOfString.GetAwaiter().GetResult());
Assert.Equal(expectedResult, taskOfString.ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Equal(expectedResult, taskOfString.ConfigureAwait(true).GetAwaiter().GetResult());
}
[OuterLoop]
[Fact]
public static void GetResult_NotCompleted_BlocksUntilCompletion()
{
var tcs = new TaskCompletionSource<bool>();
// Kick off tasks that should all block
var tasks = new[] {
Task.Run(() => tcs.Task.GetAwaiter().GetResult()),
Task.Run(() => ((Task)tcs.Task).GetAwaiter().GetResult()),
Task.Run(() => tcs.Task.ConfigureAwait(false).GetAwaiter().GetResult()),
Task.Run(() => ((Task)tcs.Task).ConfigureAwait(false).GetAwaiter().GetResult())
};
Assert.Equal(-1, Task.WaitAny(tasks, 100)); // "Tasks should not have completed"
// Now complete the tasks, after which all the tasks should complete successfully.
tcs.SetResult(true);
Task.WaitAll(tasks);
}
[Fact]
public static void GetResult_CanceledTask_ThrowsCancellationException()
{
// Validate cancellation
Task<string> canceled = Task.FromCanceled<string>(new CancellationToken(true));
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.GetAwaiter().GetResult());
// w/ ConfigureAwait false and true
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(true).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(true).GetAwaiter().GetResult());
}
[Fact]
public static void GetResult_FaultedTask_OneException_ThrowsOriginalException()
{
var exception = new ArgumentException("uh oh");
Task<string> task = Task.FromException<string>(exception);
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.GetAwaiter().GetResult()));
// w/ ConfigureAwait false and true
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(true).GetAwaiter().GetResult()));
}
[Fact]
public static void GetResult_FaultedTask_MultipleExceptions_ThrowsFirstException()
{
var exception = new ArgumentException("uh oh");
var tcs = new TaskCompletionSource<string>();
tcs.SetException(new Exception[] { exception, new InvalidOperationException("uh oh") });
Task<string> task = tcs.Task;
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.GetAwaiter().GetResult()));
// w/ ConfigureAwait false and true
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(true).GetAwaiter().GetResult()));
}
[Fact]
public static void AwaiterAndAwaitableEquality()
{
var completed = new TaskCompletionSource<string>();
Task task = completed.Task;
// TaskAwaiter
task.GetAwaiter().Equals(task.GetAwaiter());
// ConfiguredTaskAwaitable
Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false));
Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true));
Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false));
// ConfiguredTaskAwaitable<T>
Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false));
Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true));
Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false));
// ConfiguredTaskAwaitable.ConfiguredTaskAwaiter
Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
// ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter
Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
}
[Fact]
public static void BaseSynchronizationContext_SameAsNoSynchronizationContext()
{
var quwi = new QUWITaskScheduler();
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
RunWithSchedulerAsCurrent(quwi, delegate
{
ManualResetEventSlim mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
var awaiter = ((Task)tcs.Task).GetAwaiter();
bool ranOnScheduler = false;
bool ranWithoutSyncCtx = false;
awaiter.OnCompleted(() =>
{
ranOnScheduler = (TaskScheduler.Current == quwi);
ranWithoutSyncCtx = SynchronizationContext.Current == null;
mres.Set();
});
Assert.False(mres.IsSet, "Callback should not yet have run.");
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
Assert.True(ranOnScheduler, "Should have run on scheduler");
Assert.True(ranWithoutSyncCtx, "Should have run with a null sync ctx");
});
}
finally
{
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Theory]
[MemberData(nameof(CanceledTasksAndExpectedCancellationExceptions))]
public static void OperationCanceledException_PropagatesThroughCanceledTask(int lineNumber, Task task, OperationCanceledException expected)
{
_ = lineNumber;
var caught = Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult());
Assert.Same(expected, caught);
}
public static IEnumerable<object[]> CanceledTasksAndExpectedCancellationExceptions()
{
var cts = new CancellationTokenSource();
var oce = new OperationCanceledException(cts.Token);
// Scheduled Task
Task<int> generic = Task.Run<int>(new Func<int>(() =>
{
cts.Cancel();
throw oce;
}), cts.Token);
yield return new object[] { LineNumber(), generic, oce };
Task nonGeneric = generic;
// WhenAll Task and Task<int>
yield return new object[] { LineNumber(), Task.WhenAll(generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(generic, Task.FromResult(42)), oce };
yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(generic, generic, generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, Task.FromResult(42)), oce };
yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), nonGeneric), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, nonGeneric, nonGeneric), oce };
// Task.Run Task and Task<int> with unwrapping
yield return new object[] { LineNumber(), Task.Run(() => generic), oce };
yield return new object[] { LineNumber(), Task.Run(() => nonGeneric), oce };
// A FromAsync Task and Task<int>
yield return new object[] { LineNumber(), Task.Factory.FromAsync(generic, new Action<IAsyncResult>(ar => { throw oce; })), oce };
yield return new object[] { LineNumber(), Task<int>.Factory.FromAsync(nonGeneric, new Func<IAsyncResult, int>(ar => { throw oce; })), oce };
// AsyncTaskMethodBuilder
var atmb = new AsyncTaskMethodBuilder();
atmb.SetException(oce);
yield return new object[] { LineNumber(), atmb.Task, oce };
}
private static int LineNumber([CallerLineNumber]int lineNumber = 0) => lineNumber;
private class ValidateCorrectContextSynchronizationContext : SynchronizationContext
{
[ThreadStatic]
internal static bool t_isPostedInContext;
internal int PostCount;
internal int SendCount;
public override void Post(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref PostCount);
Task.Run(() =>
{
SetSynchronizationContext(this);
try
{
t_isPostedInContext = true;
d(state);
}
finally
{
t_isPostedInContext = false;
SetSynchronizationContext(null);
}
});
}
public override void Send(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref SendCount);
d(state);
}
}
/// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary>
private class QUWITaskScheduler : TaskScheduler
{
private int _queueTaskCount;
private int _tryExecuteTaskInlineCount;
public int QueueTaskCount { get { return _queueTaskCount; } }
public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } }
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
protected override void QueueTask(Task task)
{
Interlocked.Increment(ref _queueTaskCount);
Task.Run(() => TryExecuteTask(task));
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
Interlocked.Increment(ref _tryExecuteTaskInlineCount);
return TryExecuteTask(task);
}
}
/// <summary>Runs the action with TaskScheduler.Current equal to the specified scheduler.</summary>
private static void RunWithSchedulerAsCurrent(TaskScheduler scheduler, Action action)
{
var t = new Task(action);
t.RunSynchronously(scheduler);
t.GetAwaiter().GetResult();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedisp
{
public class RdpedispServer
{
#region Variables
const int CapsPduSize = 20; // Size of DISPLAYCONTROL_CAPS_PDU is fixed to 20
const String RdpedispChannelName = "Microsoft::Windows::RDS::DisplayControl";
private RdpedycServer rdpedycServer;
private DynamicVirtualChannel RdpedispDVC;
private List<RdpedispPdu> receivedList;
#endregion Variables
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="rdpedycserver"></param>
public RdpedispServer(RdpedycServer rdpedycserver)
{
this.rdpedycServer = rdpedycserver;
receivedList = new List<RdpedispPdu>();
}
#endregion Constructor
/// <summary>
/// Create dynamic virtual channel.
/// </summary>
/// <param name="transportType">selected transport type for created channels</param>
/// <param name="timeout">Timeout</param>
/// <returns>true if client supports this protocol; otherwise, return false.</returns>
public bool CreateRdpedispDvc(TimeSpan timeout, DynamicVC_TransportType transportType = DynamicVC_TransportType.RDP_TCP)
{
const ushort priority = 0;
try
{
RdpedispDVC = rdpedycServer.CreateChannel(timeout, priority, RdpedispChannelName, transportType, OnDataReceived);
}
catch
{
}
if (RdpedispDVC != null)
{
return true;
}
return false;
}
/// <summary>
/// Clear ReceiveList
/// </summary>
public void ClearReceivedList()
{
if (this.receivedList != null)
{
this.receivedList.Clear();
}
}
#region Send/Receive Methods
/// <summary>
/// Send a RDPEDISP Pdu
/// </summary>
/// <param name="pdu"></param>
public void SendRdpedispPdu(RdpedispPdu pdu)
{
byte[] data = PduMarshaler.Marshal(pdu);
if (RdpedispDVC == null)
{
throw new InvalidOperationException("DVC instance of RDPEDISP is null, Dynamic virtual channel must be created before sending data.");
}
RdpedispDVC.Send(data);
}
/// <summary>
/// Method to expect a RdpedispPdu.
/// </summary>
/// <param name="timeout">Timeout</param>
public T ExpectRdpedispPdu<T>(TimeSpan timeout) where T : RdpedispPdu
{
DateTime endTime = DateTime.Now + timeout;
while (endTime > DateTime.Now)
{
if (receivedList.Count > 0)
{
lock (receivedList)
{
foreach (RdpedispPdu pdu in receivedList)
{
T response = pdu as T;
if (response != null)
{
receivedList.Remove(pdu);
return response;
}
}
}
}
System.Threading.Thread.Sleep(100);
}
return null;
}
#endregion Send/Receive Methods
#region Create Methods
/// <summary>
/// Method to create DISPLAYCONTROL_CAPS_PDU PDU
/// </summary>
/// <param name="maxNumMonitors">A 32-bit unsigned integer that specifies the maximum number of monitors supported by the server</param>
/// <param name="maxMonitorAreaFactorA">A 32-bit unsigned integer that is used to specify the maximum monitor area supported by the server. </param>
/// <param name="maxMonitorAreaFactorB">A 32-bit unsigned integer that is used to specify the maximum monitor area supported by the server. </param>
/// <returns></returns>
public DISPLAYCONTROL_CAPS_PDU createDisplayControlCapsPdu(
uint maxNumMonitors,
uint maxMonitorAreaFactorA,
uint maxMonitorAreaFactorB)
{
DISPLAYCONTROL_CAPS_PDU capsPdu = new DISPLAYCONTROL_CAPS_PDU();
capsPdu.Header.Type = PDUTypeValues.DISPLAYCONTROL_PDU_TYPE_CAPS;
capsPdu.Header.Length = CapsPduSize;
capsPdu.MaxNumMonitors = maxNumMonitors;
capsPdu.MaxMonitorAreaFactorA = maxMonitorAreaFactorA;
capsPdu.MaxMonitorAreaFactorB = maxMonitorAreaFactorB;
return capsPdu;
}
#endregion Create Methods
#region Private Methods
/// <summary>
/// The callback method to receive data from transport layer.
/// </summary>
private void OnDataReceived(byte[] data, uint channelID)
{
lock (receivedList)
{
RdpedispPdu basePDU = new RdpedispPdu();
bool fSucceed = false;
bool fResult = PduMarshaler.Unmarshal(data, basePDU);
if (fResult)
{
byte[] pduData = new byte[basePDU.Header.Length];
Array.Copy(data, pduData, basePDU.Header.Length);
if (basePDU.Header.Type == PDUTypeValues.DISPLAYCONTROL_PDU_TYPE_CAPS)
{
DISPLAYCONTROL_CAPS_PDU capsPDU = new DISPLAYCONTROL_CAPS_PDU();
try
{
fSucceed = PduMarshaler.Unmarshal(pduData, capsPDU);
receivedList.Add(capsPDU);
}
catch (PDUDecodeException decodeException)
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(decodeException.DecodingData, unkonw);
receivedList.Add(unkonw);
}
}
else if (basePDU.Header.Type == PDUTypeValues.DISPLAYCONTROL_PDU_TYPE_MONITOR_LAYOUT)
{
DISPLAYCONTROL_MONITOR_LAYOUT_PDU monitorLayoutPDU = new DISPLAYCONTROL_MONITOR_LAYOUT_PDU();
try
{
fSucceed = PduMarshaler.Unmarshal(pduData, monitorLayoutPDU);
receivedList.Add(monitorLayoutPDU);
}
catch (PDUDecodeException decodeException)
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(decodeException.DecodingData, unkonw);
receivedList.Add(unkonw);
}
}
else
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(pduData, unkonw);
receivedList.Add(unkonw);
}
}
if (!fSucceed || !fResult)
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(data, unkonw);
receivedList.Add(unkonw);
}
}
}
#endregion Private Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using csscript;
using CSScripting;
using CSScriptLib;
using Testing;
using Xunit;
public interface IPrinter
{
void Print();
}
// static class extensions { public class UnloadableAssemblyLoadContext : AssemblyLoadContext {
// public UnloadableAssemblyLoadContext(string name = null) : base(name ??
// Guid.NewGuid().ToString(), isCollectible: true) { } } }
namespace EvaluatorTests
{
public class Generic_Roslyn
{
[Fact(Skip = "xUnit runtime is incompatible. But test is valid"
)]
public void call_UnloadAssembly()
{
// There is something strange happening under xUnit runtime. This very test runs fine
// from a console app but under a test runner the assembly stays in the memory. Possibly
// because xUnit uses dynamic types. See "Test_Unloading" method for details (https://github.com/oleg-shilo/cs-script/blob/master/src/CSScriptLib/src/Client.NET-Core/Program.cs)
int? count = null;
for (int i = 0; i < 10; i++)
{
call_SuccessfulUnloadAssembly();
var newCount = AppDomain.CurrentDomain.GetAssemblies().Count();
if (count.HasValue)
Assert.Equal(count, newCount);
GC.Collect();
count = newCount;
}
}
[Fact(Skip = "xUnit runtime is incompatible. But test is valid"
)]
public void call_SuccessfulUnloadAssembly()
{
ICalc script = CSScript.RoslynEvaluator
.With(eval => eval.IsAssemblyUnloadingEnabled = true)
.LoadMethod<ICalc>(@"public int Sum(int a, int b) { return a+b; }");
var result = script.Sum(1, 2);
script.GetType().Assembly.Unload();
}
private void call_FailingUnloadAssembly()
{
// dynamic will trigger an accidental referencing the assembly under the hood of CLR and
// it will not be collected.
dynamic script = CSScript.RoslynEvaluator
.With(eval => eval.IsAssemblyUnloadingEnabled = true)
.LoadMethod(@"public object func()
{
return new[] {0,5};
}");
var result = (int[])script.func();
var asm_type = (Type)script.GetType();
asm_type.Assembly.Unload();
}
[Fact]
public void use_ScriptCaching()
{
var code = "object func() => new[] { 0, 5 }; // " + Guid.NewGuid();
// cache is created and the compilation result is saved
CSScript.RoslynEvaluator
.With(eval => eval.IsCachingEnabled = true)
.LoadMethod(code);
// cache is used instead of recompilation
var sw = Stopwatch.StartNew();
CSScript.RoslynEvaluator
.With(eval => eval.IsCachingEnabled = true)
.LoadMethod(code);
var cachedLoadingTime = sw.ElapsedMilliseconds;
sw.Restart();
// cache is not used and the script is recompiled again
CSScript.RoslynEvaluator
.With(eval => eval.IsCachingEnabled = false)
.LoadMethod(code);
var noncachedLoadingTime = sw.ElapsedMilliseconds;
Assert.True(cachedLoadingTime < noncachedLoadingTime);
return;
}
[Fact]
public void call_LoadMethod()
{
dynamic script = CSScript.RoslynEvaluator
.LoadMethod(@"public object func()
{
return new[] {0,5};
}");
var result = (int[])script.func();
var asm_type = (Type)script.GetType();
Assert.Equal(0, result[0]);
Assert.Equal(5, result[1]);
}
[Fact]
public void issue_251()
{
var calc = CSScript
.Evaluator
.LoadCode<Testing.ICalc>(
@"using System;
public class Script : Testing.ICalc
{
public int Sum(int a, int b)
{
return a+b;
}
}");
var result = calc.Sum(1, 2);
Console.WriteLine(result);
}
[Fact]
public void issue_259()
{
var before = AppDomain.CurrentDomain.GetAssemblies().Count();
// -----
Assembly asm = CSScript.Evaluator
.With(e => e.IsCachingEnabled = true)
.CompileCode(@"using System;
public class Script
{
void Log(string message)
{
Console.WriteLine(message);
}
}");
asm.CreateObject("*");
var after = AppDomain.CurrentDomain.GetAssemblies().Count();
}
[Fact]
public void use_AssembliesFilter()
{
string[] refAssemblies = null;
var eval = CSScript.RoslynEvaluator;
dynamic script = eval.ReferenceDomainAssemblies()
.SetRefAssemblyFilter(asms =>
{
refAssemblies = asms.Select(a => a.Location)
.Distinct()
.ToArray();
return asms.Where(a => a.FullName != Assembly.GetExecutingAssembly().FullName);
})
.LoadMethod(@"public object func()
{
return new[] {0,5};
}");
var filteresAssemblies = eval.GetReferencedAssemblies()
.Select(a => a.Location)
.ToArray();
Assert.Equal(1, refAssemblies.Count() - filteresAssemblies.Count());
}
[Fact]
public void call_CompileMethod()
{
dynamic script = CSScript.RoslynEvaluator
.CompileMethod(@"public object func() => new[] {0,5}; ")
.CreateObject("*.DynamicClass");
var result = (int[])script.func();
Assert.Equal(0, result[0]);
Assert.Equal(5, result[1]);
}
[Fact]
public void referencing_script_types_from_another_script()
{
CSScript.EvaluatorConfig.ReferenceDomainAssemblies = false; // to avoid an accidental referencing
CSScript.EvaluatorConfig.DebugBuild = true;
var info = new CompileInfo { RootClass = "script_a", AssemblyFile = "script_a_asm2" };
try
{
var code2 = @"using System;
using System.Collections.Generic;
using System.Linq;
public class Utils
{
static void Main(string[] args)
{
var x = new List<int> {1, 2, 3, 4, 5};
var y = Enumerable.Range(0, 5);
x.ForEach(Console.WriteLine);
var z = y.First();
Console.WriteLine(z);
}
}";
CSScript.RoslynEvaluator
.With(e => e.IsCachingEnabled = false) // required to not interfere with xUnit
.CompileCode(code2, info);
dynamic script = CSScript.RoslynEvaluator
.With(e => e.IsCachingEnabled = false)
// .With(e => e.ReferenceDomainAssemblies = false)
.ReferenceAssembly(info.AssemblyFile)
.CompileMethod(@"using static script_a;
Utils Test()
{
return new Utils();
}")
.CreateObject("*");
object utils = script.Test();
Assert.Equal("script_a+Utils", utils.GetType().ToString());
}
finally
{
info.AssemblyFile.FileDelete(rethrow: false);
}
}
[Fact]
public void use_interfaces_between_scripts()
{
IPrinter printer = CSScript.RoslynEvaluator
.ReferenceAssemblyOf<IPrinter>()
.LoadCode<IPrinter>(@"using System;
public class Printer : IPrinter
{
public void Print()
=> Console.Write(""Printing..."");
}");
dynamic script = CSScript.RoslynEvaluator
.ReferenceAssemblyOf<IPrinter>()
.LoadMethod(@"void Test(IPrinter printer)
{
printer.Print();
}");
script.Test(printer);
}
// [Fact(Skip = "VB is not supported yet")] // hiding it from xUnit public void
// VB_Generic_Test() { Assembly asm = CSScript.RoslynEvaluator .CompileCode(@"' //css_ref
// System Imports System Class Script
// Function Sum(a As Integer, b As Integer) Sum = a + b End Function
// End Class");
// dynamic script = asm.CreateObject("*"); var result = script.Sum(7, 3); }
[Fact]
public void Issue_185_Referencing()
{
CSScript.EvaluatorConfig.DebugBuild = true;
var root_class_name = $"script_{System.Guid.NewGuid()}".Replace("-", "");
var info = new CompileInfo { RootClass = root_class_name, PreferLoadingFromFile = true };
try
{
var printer_asm = CSScript.RoslynEvaluator
.CompileCode(@"using System;
public class Printer
{
public void Print() => Console.Write(""Printing..."");
}", info);
dynamic script = CSScript.RoslynEvaluator
.ReferenceAssembly(printer_asm)
.LoadMethod($"using static {root_class_name};" + @"
void Test()
{
new Printer().Print();
}");
script.Test();
}
finally
{
info.AssemblyFile.FileDelete(rethrow: false);
}
}
}
}
namespace Testing
{
public interface ICalc
{
int Sum(int a, int b);
}
}
| |
using AjaxControlToolkit.Design;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxControlToolkit {
/// <summary>
/// The Accordion control represents a series of panes that can be viewed
/// one at a time. The control is used to create "strongly typed" access
/// to the AccordionBehavior. Its major purpose is to structure the content
/// in a way that the AccordionBehavior can understand it.
/// </summary>
[Designer(typeof(AccordionDesigner))]
[ToolboxData("<{0}:Accordion runat=server></{0}:Accordion>")]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.AccordionName + Constants.IconPostfix)]
public class Accordion : WebControl {
// ViewState key for tracking the number of panes in the Accordion
internal const string ItemCountViewStateKey = "_!ItemCount";
/// <summary>
/// An event to raise when an item (i.e. Pane's Header or Content) is created during data binding
/// </summary>
public event EventHandler<AccordionItemEventArgs> ItemCreated;
/// <summary>
/// An event to raise when an item (i.e. Pane's Header or Content) is data bound
/// </summary>
public event EventHandler<AccordionItemEventArgs> ItemDataBound;
/// <summary>
/// An event to raise when a command is fired
/// </summary>
public event CommandEventHandler ItemCommand;
// AccordionExtender to attach
AccordionExtender _extender;
// The Accordion's child panes
AccordionPaneCollection _panes;
#region DataBinding Fields
// DataSource to bind the Accordion to
object _dataSource;
// DataBinding template for the header
ITemplate _headerTemplate;
// DataBinding template for the content
ITemplate _contentTemplate;
// Whether or not the control has been initialized
bool _initialized;
// Whether the page's PreLoad event has already fired
bool _pagePreLoadFired;
// Whether or not the Accordion needs to be databound but hasn't been yet
bool _requiresDataBinding;
// Flag to determine if we should throw an exception when a data property
// (i.e. DataSource, DataSourceID, DataMember) is changed
bool _throwOnDataPropertyChange;
// View of the the data provided by the data property
DataSourceView _currentView;
// Whether the current DataSourceView was loaded from a DataSourceID
bool _currentViewIsFromDataSourceID;
// Whether the current DataSourceView contains valid data
bool _currentViewValid;
// Arguments used to sort, filter, etc., the data when creating
// the DataSourceView (although we will use the default whenever possible)
DataSourceSelectArguments _arguments;
// Enumerable list of data items obtained from the DataSource
IEnumerable _selectResult;
// Thread synchronization event used for obtaining data from the DataSource
EventWaitHandle _selectWait;
#endregion
// Default constructor that tells ASP.NET to render it as a DIV
public Accordion()
: base(HtmlTextWriterTag.Div) {
}
// Reference to the AccordionExtender wrapped by the Accordion control.
// This will be referenced in CreateChildControls so that the extender
// will always be created by any calls to EnsureChildControls.
AccordionExtender AccordionExtender {
get {
if(_extender == null) {
// Create the extender
_extender = new AccordionExtender();
_extender.ID = ID + "_AccordionExtender";
_extender.TargetControlID = ID;
Controls.AddAt(0, _extender);
}
return _extender;
}
}
/// <summary>
/// Length of the transition animation in milliseconds. The default is 500
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Length of the transition animation in milliseconds")]
[DefaultValue(500)]
public int TransitionDuration {
get { return AccordionExtender.TransitionDuration; }
set { AccordionExtender.TransitionDuration = value; }
}
/// <summary>
/// The number of frames per second used in animation effects' transition.
/// This is used to tune performance when using FadeTransition,
/// a large number of Accordion Panes, etc.
/// The default is 30.
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Number of frames per second used in the transition animation")]
[DefaultValue(30)]
public int FramesPerSecond {
get { return AccordionExtender.FramesPerSecond; }
set { AccordionExtender.FramesPerSecond = value; }
}
/// <summary>
/// Whether or not to use a fade effect when transitioning between selected
/// Accordion Panes. The default is false
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Whether or not to use a fade effect in the transition animations")]
[DefaultValue(false)]
public bool FadeTransitions {
get { return AccordionExtender.FadeTransitions; }
set { AccordionExtender.FadeTransitions = value; }
}
/// <summary>
/// The default Header CSS class
/// </summary>
[Browsable(true)]
[Category("Appearance")]
[Description("Default CSS class for Accordion Pane Headers")]
public string HeaderCssClass {
get { return AccordionExtender.HeaderCssClass; }
set { AccordionExtender.HeaderCssClass = value; }
}
/// <summary>
/// The default selected Header CSS Class
/// </summary>
[Browsable(true)]
[Category("Appearance")]
[Description("Default CSS class for the selected Accordion Pane Headers")]
public string HeaderSelectedCssClass {
get { return AccordionExtender.HeaderSelectedCssClass; }
set { AccordionExtender.HeaderSelectedCssClass = value; }
}
/// <summary>
/// The default Content CSS class
/// </summary>
[Browsable(true)]
[Category("Appearance")]
[Description("Default CSS class for Accordion Pane Content")]
public string ContentCssClass {
get { return AccordionExtender.ContentCssClass; }
set { AccordionExtender.ContentCssClass = value; }
}
/// <summary>
/// Determines how to controll resizing of the Accordion.
/// If it is set to None, then the Accordion can grow as large or as small as necessary.
/// If it is set to Limit, then the Accordion will always be less than or equal to its Height.
/// If it is set to Fill then it will always be equal to its height.
/// The default is None.
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Determine how the growth of the Accordion will be controlled")]
[DefaultValue(AutoSize.None)]
public AutoSize AutoSize {
get { return AccordionExtender.AutoSize; }
set { AccordionExtender.AutoSize = value; }
}
/// <summary>
/// Index of the AccordionPane to be displayed
/// (this property must be set before OnPreRender). The default is 0
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Index of the AccordionPane to be displayed")]
[DefaultValue(0)]
public int SelectedIndex {
get { return AccordionExtender.SelectedIndex; }
set { AccordionExtender.SelectedIndex = value; }
}
/// <summary>
/// Whether or not clicking the header will close the currently opened pane (leaving
/// all the Accordion's panes closed). The default is true
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Whether or not clicking the header will close the currently opened pane (leaving all the Accordion's panes closed)")]
[DefaultValue(true)]
public bool RequireOpenedPane {
get { return AccordionExtender.RequireOpenedPane; }
set { AccordionExtender.RequireOpenedPane = value; }
}
/// <summary>
/// Whether or not we suppress the client-side click handlers of any elements (including server
/// controls like Button or HTML elements like anchor) in the header sections of the Accordion.
/// The default is false
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Whether or not we suppress the client-side click handlers of any elements in the header sections")]
[DefaultValue(false)]
public bool SuppressHeaderPostbacks {
get { return AccordionExtender.SuppressHeaderPostbacks; }
set { AccordionExtender.SuppressHeaderPostbacks = value; }
}
/// <summary>
/// A collection of child panes in the Accordion
/// </summary>
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public AccordionPaneCollection Panes {
get {
if(_panes == null)
_panes = new AccordionPaneCollection(this);
return _panes;
}
}
/// <summary>
/// Prevent the Controls property from appearing in the editor (so
/// that people will use the Panes collection instead)
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override ControlCollection Controls {
get { return base.Controls; }
}
#region DataBinding Properties
/// <summary>
/// A template for the Header of databound panes
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(AccordionContentPanel))]
public virtual ITemplate HeaderTemplate {
get { return _headerTemplate; }
set { _headerTemplate = value; }
}
/// <summary>
/// A template for the content of databound panes
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(AccordionContentPanel))]
public virtual ITemplate ContentTemplate {
get { return _contentTemplate; }
set { _contentTemplate = value; }
}
/// <summary>
/// The data source that provides data for populating
/// the list of AccordionPanes
/// </summary>
[Bindable(true)]
[Category("Data")]
[DefaultValue(null)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual object DataSource {
get { return _dataSource; }
set {
if((value == null) || (value is IListSource) || (value is IEnumerable)) {
_dataSource = value;
OnDataPropertyChanged();
} else {
throw new ArgumentException("Can't bind to value that is not an IListSource or an IEnumerable.");
}
}
}
/// <summary>
/// The ID of the DataControl that this control should use to retrieve its data source.
/// When the control is bound to a DataControl, it can retrieve a data source instance on demand,
/// and thereby attempt to work in auto-DataBind mode.
/// </summary>
[DefaultValue("")]
[IDReferenceProperty(typeof(DataSourceControl))]
[Category("Data")]
public virtual string DataSourceID {
get { return ViewState["DataSourceID"] as string ?? String.Empty; }
set {
ViewState["DataSourceID"] = value;
OnDataPropertyChanged();
}
}
/// <summary>
/// A member in the DataSource to bind to
/// </summary>
[DefaultValue("")]
[Category("Data")]
public virtual string DataMember {
get { return ViewState["DataMember"] as string ?? String.Empty; }
set {
ViewState["DataMember"] = value;
OnDataPropertyChanged();
}
}
// Whether or not the Accordion was databound using the DataSourceID
// property rather than setting the DataSource directly
protected bool IsBoundUsingDataSourceID {
get { return !String.IsNullOrEmpty(DataSourceID); }
}
// Whether or not the control has already been databound, or still needs
// to be databound
protected bool RequiresDataBinding {
get { return _requiresDataBinding; }
set { _requiresDataBinding = value; }
}
// Arguments used to request data-related operations from
// data source controls when data is retrieved
protected DataSourceSelectArguments SelectArguments {
get {
if(_arguments == null)
_arguments = CreateDataSourceSelectArguments();
return _arguments;
}
}
#endregion
//OnInit handler to wireup the Page's PreLoad event
protected override void OnInit(EventArgs e) {
base.OnInit(e);
if(Page != null) {
Page.PreLoad += new EventHandler(this.OnPagePreLoad);
if(!IsViewStateEnabled && Page.IsPostBack)
RequiresDataBinding = true;
}
}
// OnPreLoad is used to determine whether or not we still need to databind the Accordion
void OnPagePreLoad(object sender, EventArgs e) {
_initialized = true;
if(Page != null) {
Page.PreLoad -= new EventHandler(this.OnPagePreLoad);
// Setting RequiresDataBinding to true in OnLoad is too late because the OnLoad page event
// happens before the control.OnLoad method gets called. So a page_load handler on the page
// that calls DataBind won't prevent DataBind from getting called again in PreRender.
if(!Page.IsPostBack)
RequiresDataBinding = true;
// If this is a postback and viewstate is enabled, but we have never bound the control
// before, it is probably because its visibility was changed in the postback. In this
// case, we need to bind the control or it will never appear. This is a common scenario
// for Wizard and MultiView.
if(Page.IsPostBack && IsViewStateEnabled && ViewState[ItemCountViewStateKey] == null)
RequiresDataBinding = true;
_pagePreLoadFired = true;
}
EnsureChildControls();
}
// Connect to the DataSourceView and determine if we still need to
// do databinding
protected override void OnLoad(EventArgs e) {
_initialized = true; // just in case we were added to the page after PreLoad
ConnectToDataSourceView();
if(Page != null && !_pagePreLoadFired && ViewState[ItemCountViewStateKey] == null) {
// If the control was added after PagePreLoad, we still need to databind it because it missed its
// first change in PagePreLoad. If this control was created by a call to a parent control's DataBind
// in Page_Load (with is relatively common), this control will already have been databound even
// though pagePreLoad never fired and the page isn't a postback.
if(!Page.IsPostBack) {
RequiresDataBinding = true;
}
// If the control was added to the page after page.PreLoad, we'll never get the event and we'll
// never databind the control. So if we're catching up and Load happens but PreLoad never happened,
// call DataBind. This may make the control get databound twice if the user called DataBind on the control
// directly in Page.OnLoad, but better to bind twice than never to bind at all.
else if(IsViewStateEnabled) {
RequiresDataBinding = true;
}
}
base.OnLoad(e);
}
// Create the AccordionExtender and attach it to the div
// that will be generated for this control
protected override void CreateChildControls() {
base.CreateChildControls();
// If we already have items in the ViewState, create the control
// hierarchy using the view state (and not the datasource)
if(AccordionExtender != null && ViewState[ItemCountViewStateKey] != null)
CreateControlHierarchy(false);
ClearChildViewState();
// Ensure creation of child controls
foreach(var pane in Panes) {
ControlCollection controls = pane.Controls;
}
}
// Mark the selected AccordionPane so it does not appear collapsed
protected override void OnPreRender(EventArgs e) {
EnsureDataBound();
base.OnPreRender(e);
// Set the overflow to hidden to prevent any growth from
// showing initially before it is hidden by the script if
// we are controlling the height
if(AutoSize != AutoSize.None) {
Style[HtmlTextWriterStyle.Overflow] = "hidden";
Style[HtmlTextWriterStyle.OverflowX] = "auto";
}
// Apply the standard header/content styles, but allow the
// pane's styles to take precedent
foreach(var pane in Panes) {
if(pane.HeaderCssClass == HeaderSelectedCssClass)
pane.HeaderCssClass = String.Empty;
if(!String.IsNullOrEmpty(HeaderCssClass) && String.IsNullOrEmpty(pane.HeaderCssClass))
pane.HeaderCssClass = HeaderCssClass;
if(!String.IsNullOrEmpty(ContentCssClass) && String.IsNullOrEmpty(pane.ContentCssClass))
pane.ContentCssClass = ContentCssClass;
}
// Get the index of the selected pane, or use the first pane if we don't
// have a valid index and require one. (Note: We don't reset the SelectedIndex
// property because it may refer to a pane that will be added dynamically on the
// client. If we need to start with a pane visible, then we'll open the first
// pane because that's the default value used on the client as the SelectedIndex
// in this scenario.)
var index = AccordionExtender.SelectedIndex;
index = ((index < 0 || index >= Panes.Count) && AccordionExtender.RequireOpenedPane) ? 0 : index;
// Make sure the selected pane is displayed
if(index >= 0 && index < Panes.Count) {
var content = Panes[index].ContentContainer;
if(content != null)
content.Collapsed = false;
}
}
/// <summary>
/// Override FindControl to look first at this control, then check each
/// of its child AccordionPanes for the control
/// </summary>
/// <param name="id" type="String">ID of the control to find</param>
/// <returns></returns>
public override Control FindControl(string id) {
var ctrl = base.FindControl(id);
if(ctrl == null)
foreach(var pane in Panes) {
ctrl = pane.FindControl(id);
if(ctrl != null)
break;
}
return ctrl;
}
//Empty out the child Pane's collection
internal void ClearPanes() {
for(var i = Controls.Count - 1; i >= 0; i--)
if(Controls[i] is AccordionPane)
Controls.RemoveAt(i);
}
#region DataBinding
// Connects this data bound control to the appropriate DataSourceView
// and hooks up the appropriate event listener for the
// DataSourceViewChanged event. The return value is the new view (if
// any) that was connected to. An exception is thrown if there is
// a problem finding the requested view or data source.
DataSourceView ConnectToDataSourceView() {
// If the current view is correct, there is no need to reconnect
if(_currentViewValid && !DesignMode)
return _currentView;
// Disconnect from old view, if necessary
if((_currentView != null) && (_currentViewIsFromDataSourceID)) {
// We only care about this event if we are bound through the DataSourceID property
_currentView.DataSourceViewChanged -= new EventHandler(OnDataSourceViewChanged);
}
// Connect to new view
IDataSource ds = null;
var dataSourceID = DataSourceID;
if(!String.IsNullOrEmpty(dataSourceID)) {
// Try to find a DataSource control with the ID specified in DataSourceID
var control = NamingContainer.FindControl(dataSourceID);
if(control == null)
throw new HttpException(String.Format(CultureInfo.CurrentCulture, "DataSource '{1}' for control '{0}' doesn't exist", ID, dataSourceID));
ds = control as IDataSource;
if(ds == null)
throw new HttpException(String.Format(CultureInfo.CurrentCulture, "'{1}' is not a data source for control '{0}'.", ID, dataSourceID));
}
if(ds == null)
// DataSource control was not found, construct a temporary data source to wrap the data
return null;
else
// Ensure that both DataSourceID as well as DataSource are not set at the same time
if(DataSource != null)
throw new InvalidOperationException("DataSourceID and DataSource can't be set at the same time.");
// IDataSource was found, extract the appropriate view and return it
var newView = ds.GetView(DataMember);
if(newView == null)
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "DataSourceView not found for control '{0}'", ID));
_currentViewIsFromDataSourceID = IsBoundUsingDataSourceID;
_currentView = newView;
// If we're bound through the DataSourceID proeprty, then we care about this event
if((_currentView != null) && (_currentViewIsFromDataSourceID))
_currentView.DataSourceViewChanged += new EventHandler(OnDataSourceViewChanged);
_currentViewValid = true;
return _currentView;
}
/// <summary>
/// Bind the Accordion to its DataSource
/// </summary>
public override void DataBind() {
// Don't databind to a data source control when the control is in the designer but not top-level
if(IsBoundUsingDataSourceID && DesignMode && (Site == null))
return;
// do our own databinding
RequiresDataBinding = false;
OnDataBinding(EventArgs.Empty);
}
// DataBind the Accordion to its panes
protected override void OnDataBinding(EventArgs e) {
base.OnDataBinding(e);
//Only bind if the control has the DataSource or DataSourceID set
if(this.DataSource != null || IsBoundUsingDataSourceID) {
// reset the control state
ClearPanes();
ClearChildViewState();
// and then create the control hierarchy using the datasource
CreateControlHierarchy(true);
ChildControlsCreated = true;
}
}
// Create the new control hierarchy of AccordionPanes
// (using the DataSource if specificed)
protected virtual void CreateControlHierarchy(bool useDataSource) {
var count = -1;
IEnumerable dataSource = null;
var itemsArray = new List<AccordionPane>();
if(!useDataSource) {
var viewCount = ViewState[ItemCountViewStateKey];
// ViewState must have a non-null value for ItemCount because we check for
// this in CreateChildControls
if(viewCount != null) {
count = (int)viewCount;
if(count != -1) {
var dummyList = new List<object>(count);
for(var i = 0; i < count; i++)
dummyList.Add(null);
dataSource = dummyList;
itemsArray.Capacity = count;
}
}
} else {
dataSource = GetData();
count = 0;
var collection = dataSource as ICollection;
if(collection != null)
itemsArray.Capacity = collection.Count;
}
if(dataSource != null) {
var index = 0;
foreach(var dataItem in dataSource) {
var ap = new AccordionPane();
ap.ID = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_Pane_{1}", ID, index.ToString(CultureInfo.InvariantCulture));
Controls.Add(ap);
CreateItem(dataItem, index, AccordionItemType.Header, ap.HeaderContainer, HeaderTemplate, useDataSource);
CreateItem(dataItem, index, AccordionItemType.Content, ap.ContentContainer, ContentTemplate, useDataSource);
itemsArray.Add(ap);
count++;
index++;
}
}
// If we're binding, save the number of items contained in the repeater for use in round-trips
if(useDataSource)
ViewState[ItemCountViewStateKey] = ((dataSource != null) ? count : -1);
}
// Create an AccordionPane's item (either Header or Content) and raise the ItemCreated event
void CreateItem(object dataItem, int index, AccordionItemType itemType, AccordionContentPanel container, ITemplate template, bool dataBind) {
if(template == null)
return;
var itemArgs = new AccordionItemEventArgs(container, itemType);
OnItemCreated(itemArgs);
container.ID = (itemType == AccordionItemType.Header ? "h" : "c") + index;
container.SetDataItemProperties(dataItem, index, itemType);
template.InstantiateIn(container);
if(dataBind) {
container.DataBind();
OnItemDataBound(itemArgs);
}
}
// Ensure that the Accordion has been databound if it needed to be
protected void EnsureDataBound() {
try {
_throwOnDataPropertyChange = true;
if(RequiresDataBinding && !String.IsNullOrEmpty(DataSourceID))
DataBind();
} finally {
_throwOnDataPropertyChange = false;
}
}
// Returns an IEnumerable that is the DataSource, which either came
// from the DataSource property or from the control bound via the
// DataSourceID property.
protected virtual IEnumerable GetData() {
_selectResult = null;
var view = ConnectToDataSourceView();
if(view != null) {
Debug.Assert(_currentViewValid);
// create a handle here to make sure this is a synchronous operation.
_selectWait = new EventWaitHandle(false, EventResetMode.AutoReset);
view.Select(SelectArguments, new DataSourceViewSelectCallback(DoSelect));
_selectWait.WaitOne();
} else if(DataSource != null)
_selectResult = DataSource as IEnumerable;
return _selectResult;
}
// Create the DataSourceSelectArguments (which just defaults to the Empty value
// because we don't want to sort, filter, etc.)
protected virtual DataSourceSelectArguments CreateDataSourceSelectArguments() {
return DataSourceSelectArguments.Empty;
}
// Select the data
void DoSelect(IEnumerable data) {
_selectResult = data;
_selectWait.Set();
}
// Wrap the CommandArgs of an ItemCommand event with AccordionCommandEventArgs
// returns whether the event was handled
protected override bool OnBubbleEvent(object source, EventArgs args) {
var handled = false;
var accordionArgs = args as AccordionCommandEventArgs;
if(accordionArgs != null) {
OnItemCommand(accordionArgs);
handled = true;
}
return handled;
}
// This method is called when DataMember, DataSource, or DataSourceID is changed.
protected virtual void OnDataPropertyChanged() {
if(_throwOnDataPropertyChange)
throw new HttpException("Invalid data property change");
if(_initialized)
RequiresDataBinding = true;
_currentViewValid = false;
}
// Indicate that we need to be databound whenever the DataSourceView changes
protected virtual void OnDataSourceViewChanged(object sender, EventArgs args) {
RequiresDataBinding = true;
}
protected virtual void OnItemCommand(AccordionCommandEventArgs args) {
if(ItemCommand != null)
ItemCommand(this, args);
}
protected virtual void OnItemCreated(AccordionItemEventArgs args) {
if(ItemCreated != null)
ItemCreated(this, args);
}
protected virtual void OnItemDataBound(AccordionItemEventArgs args) {
if(ItemDataBound != null)
ItemDataBound(this, args);
}
#endregion
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Algo
File: Connector_Raise.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo
{
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.BusinessEntities;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Localization;
partial class Connector
{
/// <summary>
/// Own trade received.
/// </summary>
public event Action<MyTrade> NewMyTrade;
/// <summary>
/// Own trades received.
/// </summary>
public event Action<IEnumerable<MyTrade>> NewMyTrades;
/// <summary>
/// Tick trade received.
/// </summary>
public event Action<Trade> NewTrade;
/// <summary>
/// Tick trades received.
/// </summary>
public event Action<IEnumerable<Trade>> NewTrades;
/// <summary>
/// Order received.
/// </summary>
public event Action<Order> NewOrder;
/// <summary>
/// Orders received.
/// </summary>
public event Action<IEnumerable<Order>> NewOrders;
/// <summary>
/// Order changed (cancelled, matched).
/// </summary>
public event Action<Order> OrderChanged;
/// <summary>
/// Stop-orders received.
/// </summary>
public event Action<IEnumerable<Order>> NewStopOrders;
/// <summary>
/// Orders changed (cancelled, matched).
/// </summary>
public event Action<IEnumerable<Order>> OrdersChanged;
/// <summary>
/// Order registration error event.
/// </summary>
public event Action<OrderFail> OrderRegisterFailed;
/// <summary>
/// Order cancellation error event.
/// </summary>
public event Action<OrderFail> OrderCancelFailed;
/// <summary>
/// Stop-orders changed.
/// </summary>
public event Action<IEnumerable<Order>> StopOrdersChanged;
/// <summary>
/// Stop-order registration error event.
/// </summary>
public event Action<OrderFail> StopOrderRegisterFailed;
/// <summary>
/// Stop-order cancellation error event.
/// </summary>
public event Action<OrderFail> StopOrderCancelFailed;
/// <summary>
/// Stop-order received.
/// </summary>
public event Action<Order> NewStopOrder;
/// <summary>
/// Stop order state change event.
/// </summary>
public event Action<Order> StopOrderChanged;
/// <summary>
/// Security received.
/// </summary>
public event Action<Security> NewSecurity;
/// <summary>
/// Order registration errors event.
/// </summary>
public event Action<IEnumerable<OrderFail>> OrdersRegisterFailed;
/// <summary>
/// Order cancellation errors event.
/// </summary>
public event Action<IEnumerable<OrderFail>> OrdersCancelFailed;
/// <summary>
/// Mass order cancellation event.
/// </summary>
public event Action<long> MassOrderCanceled;
/// <summary>
/// Mass order cancellation errors event.
/// </summary>
public event Action<long, Exception> MassOrderCancelFailed;
/// <summary>
/// Stop-order registration errors event.
/// </summary>
public event Action<IEnumerable<OrderFail>> StopOrdersRegisterFailed;
/// <summary>
/// Stop-order cancellation errors event.
/// </summary>
public event Action<IEnumerable<OrderFail>> StopOrdersCancelFailed;
/// <summary>
/// Securities received.
/// </summary>
public event Action<IEnumerable<Security>> NewSecurities;
/// <summary>
/// Security changed.
/// </summary>
public event Action<Security> SecurityChanged;
/// <summary>
/// Securities changed.
/// </summary>
public event Action<IEnumerable<Security>> SecuritiesChanged;
/// <summary>
/// New portfolio received.
/// </summary>
public event Action<Portfolio> NewPortfolio;
/// <summary>
/// Portfolios received.
/// </summary>
public event Action<IEnumerable<Portfolio>> NewPortfolios;
/// <summary>
/// Portfolio changed.
/// </summary>
public event Action<Portfolio> PortfolioChanged;
/// <summary>
/// Portfolios changed.
/// </summary>
public event Action<IEnumerable<Portfolio>> PortfoliosChanged;
/// <summary>
/// Position received.
/// </summary>
public event Action<Position> NewPosition;
/// <summary>
/// Positions received.
/// </summary>
public event Action<IEnumerable<Position>> NewPositions;
/// <summary>
/// Position changed.
/// </summary>
public event Action<Position> PositionChanged;
/// <summary>
/// Positions changed.
/// </summary>
public event Action<IEnumerable<Position>> PositionsChanged;
/// <summary>
/// Order book received.
/// </summary>
public event Action<MarketDepth> NewMarketDepth;
/// <summary>
/// Order book changed.
/// </summary>
public event Action<MarketDepth> MarketDepthChanged;
/// <summary>
/// Order books received.
/// </summary>
public event Action<IEnumerable<MarketDepth>> NewMarketDepths;
/// <summary>
/// Order books changed.
/// </summary>
public event Action<IEnumerable<MarketDepth>> MarketDepthsChanged;
/// <summary>
/// Order log received.
/// </summary>
public event Action<OrderLogItem> NewOrderLogItem;
/// <summary>
/// Order log received.
/// </summary>
public event Action<IEnumerable<OrderLogItem>> NewOrderLogItems;
/// <summary>
/// Server time changed <see cref="IConnector.ExchangeBoards"/>. It passed the time difference since the last call of the event. The first time the event passes the value <see cref="TimeSpan.Zero"/>.
/// </summary>
public event Action<TimeSpan> MarketTimeChanged;
/// <summary>
/// News received.
/// </summary>
public event Action<News> NewNews;
/// <summary>
/// News updated (news body received <see cref="StockSharp.BusinessEntities.News.Story"/>).
/// </summary>
public event Action<News> NewsChanged;
/// <summary>
/// Message processed <see cref="Message"/>.
/// </summary>
public event Action<Message> NewMessage;
/// <summary>
/// Connected.
/// </summary>
public event Action Connected;
/// <summary>
/// Disconnected.
/// </summary>
public event Action Disconnected;
/// <summary>
/// Connection error (for example, the connection was aborted by server).
/// </summary>
public event Action<Exception> ConnectionError;
/// <summary>
/// Connected.
/// </summary>
public event Action<IMessageAdapter> ConnectedEx;
/// <summary>
/// Disconnected.
/// </summary>
public event Action<IMessageAdapter> DisconnectedEx;
/// <summary>
/// Connection error (for example, the connection was aborted by server).
/// </summary>
public event Action<IMessageAdapter, Exception> ConnectionErrorEx;
/// <summary>
/// Dats process error.
/// </summary>
public event Action<Exception> Error;
/// <summary>
/// Lookup result <see cref="IConnector.LookupSecurities(Security)"/> received.
/// </summary>
public event Action<Exception, IEnumerable<Security>> LookupSecuritiesResult;
/// <summary>
/// Lookup result <see cref="IConnector.LookupPortfolios"/> received.
/// </summary>
public event Action<Exception, IEnumerable<Portfolio>> LookupPortfoliosResult;
/// <summary>
/// Successful subscription market-data.
/// </summary>
public event Action<Security, MarketDataMessage> MarketDataSubscriptionSucceeded;
/// <summary>
/// Error subscription market-data.
/// </summary>
public event Action<Security, MarketDataMessage, Exception> MarketDataSubscriptionFailed;
/// <summary>
/// Successful unsubscription market-data.
/// </summary>
public event Action<Security, MarketDataMessage> MarketDataUnSubscriptionSucceeded;
/// <summary>
/// Error unsubscription market-data.
/// </summary>
public event Action<Security, MarketDataMessage, Exception> MarketDataUnSubscriptionFailed;
/// <summary>
/// Session changed.
/// </summary>
public event Action<ExchangeBoard, SessionStates> SessionStateChanged;
/// <summary>
/// Security changed.
/// </summary>
public event Action<Security, IEnumerable<KeyValuePair<Level1Fields, object>>, DateTimeOffset, DateTimeOffset> ValuesChanged;
/// <summary>
/// Connection restored.
/// </summary>
public event Action Restored;
/// <summary>
/// Connection timed-out.
/// </summary>
public event Action TimeOut;
private void RaiseNewMyTrade(MyTrade trade)
{
NewMyTrade?.Invoke(trade);
NewMyTrades?.Invoke(new[] { trade });
}
private void RaiseNewTrade(Trade trade)
{
NewTrade?.Invoke(trade);
NewTrades?.Invoke(new[] { trade });
}
private void RaiseNewOrder(Order order)
{
NewOrder?.Invoke(order);
NewOrders?.Invoke(new[] { order });
}
private void RaiseOrderChanged(Order order)
{
OrderChanged?.Invoke(order);
OrdersChanged?.Invoke(new[] { order });
}
/// <summary>
/// To call the event <see cref="NewStopOrders"/>.
/// </summary>
/// <param name="stopOrder">Stop order that should be passed to the event.</param>
private void RaiseNewStopOrder(Order stopOrder)
{
NewStopOrder?.Invoke(stopOrder);
NewStopOrders?.Invoke(new[] { stopOrder });
}
/// <summary>
/// To call the event <see cref="StopOrdersChanged"/>.
/// </summary>
/// <param name="stopOrder">Stop orders that should be passed to the event.</param>
private void RaiseStopOrderChanged(Order stopOrder)
{
StopOrderChanged?.Invoke(stopOrder);
StopOrdersChanged?.Invoke(new[] { stopOrder });
}
private void RaiseStopOrdersChanged(IEnumerable<Order> stopOrders)
{
foreach (var stopOrder in stopOrders)
{
StopOrderChanged?.Invoke(stopOrder);
}
StopOrdersChanged?.Invoke(stopOrders);
}
private void RaiseOrderRegisterFailed(OrderFail fail)
{
OrderRegisterFailed?.Invoke(fail);
OrdersRegisterFailed?.Invoke(new[] { fail });
}
private void RaiseOrderCancelFailed(OrderFail fail)
{
OrderCancelFailed?.Invoke(fail);
OrdersCancelFailed?.Invoke(new[] { fail });
}
/// <summary>
/// To call the event <see cref="StopOrdersRegisterFailed"/>.
/// </summary>
/// <param name="fail">Error information that should be passed to the event.</param>
private void RaiseStopOrdersRegisterFailed(OrderFail fail)
{
StopOrderRegisterFailed?.Invoke(fail);
StopOrdersRegisterFailed?.Invoke(new[] { fail });
}
/// <summary>
/// To call the event <see cref="StopOrdersCancelFailed"/>.
/// </summary>
/// <param name="fail">Error information that should be passed to the event.</param>
private void RaiseStopOrdersCancelFailed(OrderFail fail)
{
StopOrderCancelFailed?.Invoke(fail);
StopOrdersCancelFailed?.Invoke(new[] { fail });
}
private void RaiseMassOrderCanceled(long transactionId)
{
MassOrderCanceled?.Invoke(transactionId);
}
private void RaiseMassOrderCancelFailed(long transactionId, Exception error)
{
MassOrderCancelFailed?.Invoke(transactionId, error);
}
private void RaiseNewSecurity(Security security)
{
var arr = new[] { security };
_added?.Invoke(arr);
NewSecurity?.Invoke(security);
NewSecurities?.Invoke(arr);
}
private void RaiseSecuritiesChanged(Security[] securities)
{
SecuritiesChanged?.Invoke(securities);
var evt = SecurityChanged;
if (evt == null)
return;
foreach (var security in securities)
evt(security);
}
private void RaiseSecurityChanged(Security security)
{
SecurityChanged?.Invoke(security);
SecuritiesChanged?.Invoke(new[] { security });
}
private void RaiseNewPortfolio(Portfolio portfolio)
{
NewPortfolio?.Invoke(portfolio);
NewPortfolios?.Invoke(new[] { portfolio });
}
private void RaisePortfolioChanged(Portfolio portfolio)
{
PortfolioChanged?.Invoke(portfolio);
PortfoliosChanged?.Invoke(new[] { portfolio });
}
private void RaiseNewPosition(Position position)
{
NewPosition?.Invoke(position);
NewPositions?.Invoke(new[] { position });
}
private void RaisePositionChanged(Position position)
{
PositionChanged?.Invoke(position);
PositionsChanged?.Invoke(new[] { position });
}
private void RaiseNewMarketDepth(MarketDepth marketDepth)
{
NewMarketDepth?.Invoke(marketDepth);
NewMarketDepths?.Invoke(new[] { marketDepth });
}
private void RaiseMarketDepthChanged(MarketDepth marketDepth)
{
MarketDepthChanged?.Invoke(marketDepth);
MarketDepthsChanged?.Invoke(new[] { marketDepth });
}
/// <summary>
/// To call the event <see cref="NewNews"/>.
/// </summary>
/// <param name="news">News.</param>
private void RaiseNewNews(News news)
{
NewNews?.Invoke(news);
}
/// <summary>
/// To call the event <see cref="NewsChanged"/>.
/// </summary>
/// <param name="news">News.</param>
private void RaiseNewsChanged(News news)
{
NewsChanged?.Invoke(news);
}
private void RaiseNewOrderLogItem(OrderLogItem item)
{
NewOrderLogItem?.Invoke(item);
NewOrderLogItems?.Invoke(new[] { item });
}
/// <summary>
/// To call the event <see cref="Connected"/>.
/// </summary>
private void RaiseConnected()
{
ConnectionState = ConnectionStates.Connected;
Connected?.Invoke();
}
/// <summary>
/// To call the event <see cref="ConnectedEx"/>.
/// </summary>
/// <param name="adapter">Adapter, initiated event.</param>
private void RaiseConnectedEx(IMessageAdapter adapter)
{
ConnectedEx?.Invoke(adapter);
}
/// <summary>
/// To call the event <see cref="Disconnected"/>.
/// </summary>
private void RaiseDisconnected()
{
ConnectionState = ConnectionStates.Disconnected;
Disconnected?.Invoke();
}
/// <summary>
/// To call the event <see cref="DisconnectedEx"/>.
/// </summary>
/// <param name="adapter">Adapter, initiated event.</param>
private void RaiseDisconnectedEx(IMessageAdapter adapter)
{
DisconnectedEx?.Invoke(adapter);
}
/// <summary>
/// To call the event <see cref="ConnectionError"/>.
/// </summary>
/// <param name="exception">Error connection.</param>
private void RaiseConnectionError(Exception exception)
{
if (exception == null)
throw new ArgumentNullException(nameof(exception));
ConnectionState = ConnectionStates.Failed;
ConnectionError?.Invoke(exception);
this.AddErrorLog(exception);
}
/// <summary>
/// To call the event <see cref="ConnectionErrorEx"/>.
/// </summary>
/// <param name="adapter">Adapter, initiated event.</param>
/// <param name="exception">Error connection.</param>
private void RaiseConnectionErrorEx(IMessageAdapter adapter, Exception exception)
{
if (exception == null)
throw new ArgumentNullException(nameof(exception));
ConnectionErrorEx?.Invoke(adapter, exception);
}
/// <summary>
/// To call the event <see cref="Connector.Error"/>.
/// </summary>
/// <param name="exception">Data processing error.</param>
protected void RaiseError(Exception exception)
{
if (exception == null)
throw new ArgumentNullException(nameof(exception));
ErrorCount++;
this.AddErrorLog(exception);
Error?.Invoke(exception);
}
/// <summary>
/// To call the event <see cref="MarketTimeChanged"/>.
/// </summary>
/// <param name="diff">The difference in the time since the last call of the event. The first time the event passes the <see cref="TimeSpan.Zero"/> value.</param>
private void RaiseMarketTimeChanged(TimeSpan diff)
{
MarketTimeChanged?.Invoke(diff);
}
/// <summary>
/// To call the event <see cref="LookupSecuritiesResult"/>.
/// </summary>
/// <param name="error">An error of security lookup operation. The value will be <see langword="null"/> if operation complete successfully.</param>
/// <param name="securities">Found instruments.</param>
private void RaiseLookupSecuritiesResult(Exception error, IEnumerable<Security> securities)
{
LookupSecuritiesResult?.Invoke(error, securities);
}
/// <summary>
/// To call the event <see cref="LookupPortfoliosResult"/>.
/// </summary>
/// <param name="error">An error of portfolio lookup operation. The value will be <see langword="null"/> if operation complete successfully.</param>
/// <param name="portfolios">Found portfolios.</param>
private void RaiseLookupPortfoliosResult(Exception error, IEnumerable<Portfolio> portfolios)
{
LookupPortfoliosResult?.Invoke(error, portfolios);
}
private void RaiseMarketDataSubscriptionSucceeded(Security security, MarketDataMessage message)
{
var msg = LocalizedStrings.Str690Params.Put(security.Id, message.DataType);
if (message.From != null && message.To != null)
msg += LocalizedStrings.Str691Params.Put(message.From.Value, message.To.Value);
this.AddInfoLog(msg + ".");
MarketDataSubscriptionSucceeded?.Invoke(security, message);
}
private void RaiseMarketDataSubscriptionFailed(Security security, MarketDataMessage message, Exception error)
{
this.AddErrorLog(LocalizedStrings.Str634Params, security.Id, message.DataType, message.Error);
MarketDataSubscriptionFailed?.Invoke(security, message, error);
}
private void RaiseMarketDataUnSubscriptionSucceeded(Security security, MarketDataMessage message)
{
MarketDataUnSubscriptionSucceeded?.Invoke(security, message);
}
private void RaiseMarketDataUnSubscriptionFailed(Security security, MarketDataMessage message, Exception error)
{
MarketDataUnSubscriptionFailed?.Invoke(security, message, error);
}
/// <summary>
/// To call the event <see cref="Connector.NewMessage"/>.
/// </summary>
/// <param name="message">A new message.</param>
private void RaiseNewMessage(Message message)
{
NewMessage?.Invoke(message);
}
private void RaiseValuesChanged(Security security, IEnumerable<KeyValuePair<Level1Fields, object>> changes, DateTimeOffset serverTime, DateTimeOffset localTime)
{
ValuesChanged?.Invoke(security, changes, serverTime, localTime);
}
private void RaiseRestored()
{
Restored?.Invoke();
}
private void RaiseTimeOut()
{
TimeOut?.Invoke();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// UsagesOperations operations.
/// </summary>
internal partial class UsagesOperations : IServiceOperations<NetworkManagementClient>, IUsagesOperations
{
/// <summary>
/// Initializes a new instance of the UsagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UsagesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Lists compute usages for a subscription.
/// </summary>
/// <param name='location'>
/// The location upon which resource usage is queried.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IPage<Usage>>> ListWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (location != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(location, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "location", "^[-\\w\\._]+$");
}
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "List", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages").ToString();
url = url.Replace("{location}", Uri.EscapeDataString(location));
url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = new HttpRequestMessageWrapper(httpRequest, null);
ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<IPage<Usage>>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)statusCode == 200)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Page<Usage>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Lists compute usages for a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IPage<Usage>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string url = "{nextLink}";
url = url.Replace("{nextLink}", nextPageLink);
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = new HttpRequestMessageWrapper(httpRequest, null);
ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<IPage<Usage>>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)statusCode == 200)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Page<Usage>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using JetBrains.Annotations;
namespace NLog.UnitTests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xunit;
using NLog.Common;
using NLog.Config;
using NLog.Targets;
using System.Threading.Tasks;
public class LogManagerTests : NLogTestBase
{
[Fact]
public void GetLoggerTest()
{
ILogger loggerA = LogManager.GetLogger("A");
ILogger loggerA2 = LogManager.GetLogger("A");
ILogger loggerB = LogManager.GetLogger("B");
Assert.Same(loggerA, loggerA2);
Assert.NotSame(loggerA, loggerB);
Assert.Equal("A", loggerA.Name);
Assert.Equal("B", loggerB.Name);
}
[Fact]
public void GarbageCollectionTest()
{
string uniqueLoggerName = Guid.NewGuid().ToString();
ILogger loggerA1 = LogManager.GetLogger(uniqueLoggerName);
GC.Collect();
ILogger loggerA2 = LogManager.GetLogger(uniqueLoggerName);
Assert.Same(loggerA1, loggerA2);
}
static WeakReference GetWeakReferenceToTemporaryLogger()
{
string uniqueLoggerName = Guid.NewGuid().ToString();
return new WeakReference(LogManager.GetLogger(uniqueLoggerName));
}
[Fact]
public void GarbageCollection2Test()
{
WeakReference wr = GetWeakReferenceToTemporaryLogger();
// nobody's holding a reference to this Logger anymore, so GC.Collect(2) should free it
GC.Collect(2, GCCollectionMode.Forced, true);
Assert.False(wr.IsAlive);
}
[Fact]
public void NullLoggerTest()
{
ILogger l = LogManager.CreateNullLogger();
Assert.Equal(String.Empty, l.Name);
}
[Fact]
public void ThrowExceptionsTest()
{
FileTarget ft = new FileTarget();
ft.FileName = ""; // invalid file name
SimpleConfigurator.ConfigureForTargetLogging(ft);
using (new NoThrowNLogExceptions())
{
LogManager.GetLogger("A").Info("a");
LogManager.ThrowExceptions = true;
try
{
LogManager.GetLogger("A").Info("a");
Assert.True(false, "Should not be reached.");
}
catch
{
Assert.True(true);
}
}
}
[Fact(Skip="Side effects to other unit tests.")]
public void GlobalThresholdTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog globalThreshold='Info'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Assert.Equal(LogLevel.Info, LogManager.GlobalThreshold);
// nothing gets logged because of globalThreshold
LogManager.GetLogger("A").Debug("xxx");
AssertDebugLastMessage("debug", "");
// lower the threshold
LogManager.GlobalThreshold = LogLevel.Trace;
LogManager.GetLogger("A").Debug("yyy");
AssertDebugLastMessage("debug", "yyy");
// raise the threshold
LogManager.GlobalThreshold = LogLevel.Info;
// this should be yyy, meaning that the target is in place
// only rules have been modified.
LogManager.GetLogger("A").Debug("zzz");
AssertDebugLastMessage("debug", "yyy");
LogManager.Shutdown();
LogManager.Configuration = null;
}
[Fact]
public void DisableLoggingTest_UsingStatement()
{
const string LoggerConfig = @"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='DisableLoggingTest_UsingStatement_A' levels='Trace' writeTo='debug' />
<logger name='DisableLoggingTest_UsingStatement_B' levels='Error' writeTo='debug' />
</rules>
</nlog>";
// Disable/Enable logging should affect ALL the loggers.
ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_UsingStatement_A");
ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_UsingStatement_B");
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(LoggerConfig);
// The starting state for logging is enable.
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
loggerA.Trace("---");
AssertDebugLastMessage("debug", "---");
using (LogManager.DisableLogging())
{
Assert.False(LogManager.IsLoggingEnabled());
// The last of LastMessage outside using statement should be returned.
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "---");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "---");
}
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
LogManager.Shutdown();
LogManager.Configuration = null;
}
[Fact]
public void DisableLoggingTest_WithoutUsingStatement()
{
const string LoggerConfig = @"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='DisableLoggingTest_WithoutUsingStatement_A' levels='Trace' writeTo='debug' />
<logger name='DisableLoggingTest_WithoutUsingStatement_B' levels='Error' writeTo='debug' />
</rules>
</nlog>";
// Disable/Enable logging should affect ALL the loggers.
ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_A");
ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_B");
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(LoggerConfig);
// The starting state for logging is enable.
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
loggerA.Trace("---");
AssertDebugLastMessage("debug", "---");
LogManager.DisableLogging();
Assert.False(LogManager.IsLoggingEnabled());
// The last value of LastMessage before DisableLogging() should be returned.
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "---");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "---");
LogManager.EnableLogging();
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
LogManager.Shutdown();
LogManager.Configuration = null;
}
private int _reloadCounter;
private void WaitForConfigReload(int counter)
{
while (_reloadCounter < counter)
{
System.Threading.Thread.Sleep(100);
}
}
private void OnConfigReloaded(object sender, LoggingConfigurationReloadedEventArgs e)
{
Console.WriteLine("OnConfigReloaded success={0}", e.Succeeded);
_reloadCounter++;
}
[Fact]
public void AutoReloadTest()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] LogManagerTests.AutoReloadTest because we are running in Travis");
return;
}
#endif
using (new InternalLoggerScope())
{
string fileName = Path.GetTempFileName();
try
{
_reloadCounter = 0;
LogManager.ConfigurationReloaded += OnConfigReloaded;
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
LogManager.Configuration = new XmlLoggingConfiguration(fileName);
AssertDebugCounter("debug", 0);
ILogger logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
InternalLogger.Info("Rewriting test file...");
// now write the file again
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
InternalLogger.Info("Rewritten.");
WaitForConfigReload(1);
logger.Debug("aaa");
AssertDebugLastMessage("debug", "xxx aaa");
// write the file again, this time make an error
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
WaitForConfigReload(2);
logger.Debug("bbb");
AssertDebugLastMessage("debug", "xxx bbb");
// write the corrected file again
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='zzz ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
WaitForConfigReload(3);
logger.Debug("ccc");
AssertDebugLastMessage("debug", "zzz ccc");
}
finally
{
LogManager.ConfigurationReloaded -= OnConfigReloaded;
if (File.Exists(fileName))
File.Delete(fileName);
}
}
}
[Fact]
public void GivenCurrentClass_WhenGetCurrentClassLogger_ThenLoggerShouldBeCurrentClass()
{
var logger = LogManager.GetCurrentClassLogger();
Assert.Equal(GetType().FullName, logger.Name);
}
private static class ImAStaticClass
{
[UsedImplicitly]
public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
static ImAStaticClass() { }
public static void DummyToInvokeInitializers() { }
}
[Fact]
public void GetCurrentClassLogger_static_class()
{
ImAStaticClass.DummyToInvokeInitializers();
Assert.Equal(typeof(ImAStaticClass).FullName, ImAStaticClass.Logger.Name);
}
private abstract class ImAAbstractClass
{
public Logger Logger { get; private set; }
public Logger LoggerType { get; private set; }
public string BaseName => typeof(ImAAbstractClass).FullName;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Object"/> class.
/// </summary>
protected ImAAbstractClass()
{
Logger = LogManager.GetCurrentClassLogger();
LoggerType = LogManager.GetCurrentClassLogger(typeof(Logger));
}
protected ImAAbstractClass(string param1, Func<string> param2)
{
Logger = LogManager.GetCurrentClassLogger();
LoggerType = LogManager.GetCurrentClassLogger(typeof(Logger));
}
}
private class InheritedFromAbstractClass : ImAAbstractClass
{
public Logger LoggerInherited = LogManager.GetCurrentClassLogger();
public Logger LoggerTypeInherited = LogManager.GetCurrentClassLogger(typeof(Logger));
public string InheritedName => GetType().FullName;
public InheritedFromAbstractClass()
: base()
{
}
public InheritedFromAbstractClass(string param1, Func<string> param2)
: base(param1, param2)
{
}
}
/// <summary>
/// Creating instance in a abstract ctor should not be a problem
/// </summary>
[Fact]
public void GetCurrentClassLogger_abstract_class()
{
var instance = new InheritedFromAbstractClass();
Assert.Equal(instance.BaseName, instance.Logger.Name);
Assert.Equal(instance.BaseName, instance.LoggerType.Name);
Assert.Equal(instance.InheritedName, instance.LoggerInherited.Name);
Assert.Equal(instance.InheritedName, instance.LoggerTypeInherited.Name);
}
/// <summary>
/// Creating instance in a abstract ctor should not be a problem
/// </summary>
[Fact]
public void GetCurrentClassLogger_abstract_class_with_parameter()
{
var instance = new InheritedFromAbstractClass("Hello", null);
Assert.Equal(instance.BaseName, instance.Logger.Name);
Assert.Equal(instance.BaseName, instance.LoggerType.Name);
}
/// <summary>
/// I'm a class which isn't inhereting from Logger
/// </summary>
private class ImNotALogger
{
}
/// <summary>
/// ImNotALogger inherits not from Logger , but should not throw an exception
/// </summary>
[Fact]
public void GetLogger_wrong_loggertype_should_continue()
{
using (new NoThrowNLogExceptions())
{
var instance = LogManager.GetLogger("a", typeof(ImNotALogger));
Assert.NotNull(instance);
}
}
/// <summary>
/// ImNotALogger inherits not from Logger , but should not throw an exception
/// </summary>
[Fact]
public void GetLogger_wrong_loggertype_should_continue_even_if_class_is_static()
{
using (new NoThrowNLogExceptions())
{
var instance = LogManager.GetLogger("a", typeof(ImAStaticClass));
Assert.NotNull(instance);
}
}
[Fact]
public void GivenLazyClass_WhenGetCurrentClassLogger_ThenLoggerNameShouldBeCurrentClass()
{
var logger = new Lazy<ILogger>(LogManager.GetCurrentClassLogger);
Assert.Equal(GetType().FullName, logger.Value.Name);
}
[Fact]
public void ThreadSafe_Shutdown()
{
LogManager.Configuration = new LoggingConfiguration();
LogManager.ThrowExceptions = true;
LogManager.Configuration.AddTarget("memory", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryTarget() { MaxLogsCount = 500 }, 5, 1));
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory")));
LogManager.Configuration.AddTarget("memory2", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryTarget() { MaxLogsCount = 500 }, 5, 1));
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory2")));
var stopFlag = false;
var exceptionThrown = false;
Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } });
Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } });
System.Threading.Thread.Sleep(20);
LogManager.Shutdown(); // Shutdown active LoggingConfiguration
System.Threading.Thread.Sleep(20);
stopFlag = true;
System.Threading.Thread.Sleep(20);
Assert.False(exceptionThrown);
}
/// <summary>
/// Note: THe problem can be reproduced when: debugging the unittest + "break when exception is thrown" checked in visual studio.
///
/// https://github.com/NLog/NLog/issues/500
/// </summary>
[Fact]
public void ThreadSafe_getCurrentClassLogger_test()
{
MemoryTarget mTarget = new MemoryTarget() { Name = "memory", MaxLogsCount = 1000 };
MemoryTarget mTarget2 = new MemoryTarget() { Name = "memory2", MaxLogsCount = 1000 };
var task1 = Task.Run(() =>
{
//need for init
LogManager.Configuration = new LoggingConfiguration();
LogManager.Configuration.AddTarget(mTarget.Name, mTarget);
LogManager.Configuration.AddRuleForAllLevels(mTarget.Name);
System.Threading.Thread.Sleep(1);
LogManager.ReconfigExistingLoggers();
System.Threading.Thread.Sleep(1);
mTarget.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}";
});
var task2 = task1.ContinueWith((t) =>
{
LogManager.Configuration.AddTarget(mTarget2.Name, mTarget2);
LogManager.Configuration.AddRuleForAllLevels(mTarget2.Name);
System.Threading.Thread.Sleep(1);
LogManager.ReconfigExistingLoggers();
System.Threading.Thread.Sleep(1);
mTarget2.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}";
});
System.Threading.Thread.Sleep(1);
Parallel.For(0, 8, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, (e) =>
{
bool task1Complete = false, task2Complete = false;
for (int i = 0; i < 100; ++i)
{
if (i > 25 && !task1Complete)
{
task1.Wait(5000);
task1Complete = true;
}
if (i > 75 && !task2Complete)
{
task2.Wait(5000);
task2Complete = true;
}
// Multiple threads initializing new loggers while configuration is changing
var loggerA = LogManager.GetLogger(e + "A" + i);
loggerA.Info("Hi there {0}", e);
var loggerB = LogManager.GetLogger(e + "B" + i);
loggerB.Info("Hi there {0}", e);
var loggerC = LogManager.GetLogger(e + "C" + i);
loggerC.Info("Hi there {0}", e);
var loggerD = LogManager.GetLogger(e + "D" + i);
loggerD.Info("Hi there {0}", e);
};
});
Assert.NotEqual(0, mTarget.Logs.Count + mTarget2.Logs.Count);
}
[Fact]
public void RemovedTargetShouldNotLog()
{
var config = new LoggingConfiguration();
var targetA = new MemoryTarget("TargetA") { Layout = "A | ${message}", MaxLogsCount = 1 };
var targetB = new MemoryTarget("TargetB") { Layout = "B | ${message}", MaxLogsCount = 1 };
config.AddRule(LogLevel.Debug, LogLevel.Fatal, targetA);
config.AddRule(LogLevel.Debug, LogLevel.Fatal, targetB);
LogManager.Configuration = config;
Assert.Equal(new[] { "TargetA", "TargetB" }, LogManager.Configuration.ConfiguredNamedTargets.Select(target => target.Name));
Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetA"));
Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetB"));
var logger = LogManager.GetCurrentClassLogger();
logger.Info("Hello World");
Assert.Equal("A | Hello World", targetA.Logs.LastOrDefault());
Assert.Equal("B | Hello World", targetB.Logs.LastOrDefault());
// Remove the first target from the configuration
LogManager.Configuration.RemoveTarget("TargetA");
Assert.Equal(new[] { "TargetB" }, LogManager.Configuration.ConfiguredNamedTargets.Select(target => target.Name));
Assert.Null(LogManager.Configuration.FindTargetByName("TargetA"));
Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetB"));
logger.Info("Goodbye World");
Assert.Equal("A | Hello World", targetA.Logs.LastOrDefault()); // Flushed and closed
Assert.Equal("B | Goodbye World", targetB.Logs.LastOrDefault());
}
}
}
| |
namespace System.Windows.Forms
{
using System;
using System.ComponentModel;
using System.Reactive;
using System.Reactive.Linq;
/// <summary>
/// Extension methods providing IObservable wrappers for the events on TreeView.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ObservableTreeViewEvents
{
/// <summary>
/// Returns an observable sequence wrapping the BackgroundImageChanged event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the BackgroundImageChanged event on the TreeView instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackgroundImageChangedObservable(this TreeView instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackgroundImageChanged += handler,
handler => instance.BackgroundImageChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BackgroundImageLayoutChanged event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the BackgroundImageLayoutChanged event on the TreeView instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackgroundImageLayoutChangedObservable(this TreeView instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackgroundImageLayoutChanged += handler,
handler => instance.BackgroundImageLayoutChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the PaddingChanged event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the PaddingChanged event on the TreeView instance.</returns>
public static IObservable<EventPattern<EventArgs>> PaddingChangedObservable(this TreeView instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.PaddingChanged += handler,
handler => instance.PaddingChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the TextChanged event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the TextChanged event on the TreeView instance.</returns>
public static IObservable<EventPattern<EventArgs>> TextChangedObservable(this TreeView instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.TextChanged += handler,
handler => instance.TextChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BeforeLabelEdit event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the BeforeLabelEdit event on the TreeView instance.</returns>
public static IObservable<EventPattern<NodeLabelEditEventArgs>> BeforeLabelEditObservable(this TreeView instance)
{
return Observable.FromEventPattern<NodeLabelEditEventHandler, NodeLabelEditEventArgs>(
handler => instance.BeforeLabelEdit += handler,
handler => instance.BeforeLabelEdit -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the AfterLabelEdit event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the AfterLabelEdit event on the TreeView instance.</returns>
public static IObservable<EventPattern<NodeLabelEditEventArgs>> AfterLabelEditObservable(this TreeView instance)
{
return Observable.FromEventPattern<NodeLabelEditEventHandler, NodeLabelEditEventArgs>(
handler => instance.AfterLabelEdit += handler,
handler => instance.AfterLabelEdit -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BeforeCheck event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the BeforeCheck event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewCancelEventArgs>> BeforeCheckObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewCancelEventHandler, TreeViewCancelEventArgs>(
handler => instance.BeforeCheck += handler,
handler => instance.BeforeCheck -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the AfterCheck event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the AfterCheck event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewEventArgs>> AfterCheckObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewEventHandler, TreeViewEventArgs>(
handler => instance.AfterCheck += handler,
handler => instance.AfterCheck -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BeforeCollapse event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the BeforeCollapse event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewCancelEventArgs>> BeforeCollapseObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewCancelEventHandler, TreeViewCancelEventArgs>(
handler => instance.BeforeCollapse += handler,
handler => instance.BeforeCollapse -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the AfterCollapse event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the AfterCollapse event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewEventArgs>> AfterCollapseObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewEventHandler, TreeViewEventArgs>(
handler => instance.AfterCollapse += handler,
handler => instance.AfterCollapse -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BeforeExpand event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the BeforeExpand event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewCancelEventArgs>> BeforeExpandObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewCancelEventHandler, TreeViewCancelEventArgs>(
handler => instance.BeforeExpand += handler,
handler => instance.BeforeExpand -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the AfterExpand event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the AfterExpand event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewEventArgs>> AfterExpandObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewEventHandler, TreeViewEventArgs>(
handler => instance.AfterExpand += handler,
handler => instance.AfterExpand -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the DrawNode event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the DrawNode event on the TreeView instance.</returns>
public static IObservable<EventPattern<DrawTreeNodeEventArgs>> DrawNodeObservable(this TreeView instance)
{
return Observable.FromEventPattern<DrawTreeNodeEventHandler, DrawTreeNodeEventArgs>(
handler => instance.DrawNode += handler,
handler => instance.DrawNode -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ItemDrag event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the ItemDrag event on the TreeView instance.</returns>
public static IObservable<EventPattern<ItemDragEventArgs>> ItemDragObservable(this TreeView instance)
{
return Observable.FromEventPattern<ItemDragEventHandler, ItemDragEventArgs>(
handler => instance.ItemDrag += handler,
handler => instance.ItemDrag -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the NodeMouseHover event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the NodeMouseHover event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeNodeMouseHoverEventArgs>> NodeMouseHoverObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeNodeMouseHoverEventHandler, TreeNodeMouseHoverEventArgs>(
handler => instance.NodeMouseHover += handler,
handler => instance.NodeMouseHover -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BeforeSelect event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the BeforeSelect event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewCancelEventArgs>> BeforeSelectObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewCancelEventHandler, TreeViewCancelEventArgs>(
handler => instance.BeforeSelect += handler,
handler => instance.BeforeSelect -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the AfterSelect event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the AfterSelect event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeViewEventArgs>> AfterSelectObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeViewEventHandler, TreeViewEventArgs>(
handler => instance.AfterSelect += handler,
handler => instance.AfterSelect -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Paint event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the Paint event on the TreeView instance.</returns>
public static IObservable<EventPattern<PaintEventArgs>> PaintObservable(this TreeView instance)
{
return Observable.FromEventPattern<PaintEventHandler, PaintEventArgs>(
handler => instance.Paint += handler,
handler => instance.Paint -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the NodeMouseClick event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the NodeMouseClick event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeNodeMouseClickEventArgs>> NodeMouseClickObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeNodeMouseClickEventHandler, TreeNodeMouseClickEventArgs>(
handler => instance.NodeMouseClick += handler,
handler => instance.NodeMouseClick -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the NodeMouseDoubleClick event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the NodeMouseDoubleClick event on the TreeView instance.</returns>
public static IObservable<EventPattern<TreeNodeMouseClickEventArgs>> NodeMouseDoubleClickObservable(this TreeView instance)
{
return Observable.FromEventPattern<TreeNodeMouseClickEventHandler, TreeNodeMouseClickEventArgs>(
handler => instance.NodeMouseDoubleClick += handler,
handler => instance.NodeMouseDoubleClick -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the RightToLeftLayoutChanged event on the TreeView instance.
/// </summary>
/// <param name="instance">The TreeView instance to observe.</param>
/// <returns>An observable sequence wrapping the RightToLeftLayoutChanged event on the TreeView instance.</returns>
public static IObservable<EventPattern<EventArgs>> RightToLeftLayoutChangedObservable(this TreeView instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.RightToLeftLayoutChanged += handler,
handler => instance.RightToLeftLayoutChanged -= handler);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
#if !JSONNET_XMLDISABLE
using System.Xml;
#endif
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public class JsonTextReader : JsonReader, IJsonLineInfo
{
private enum ReadType
{
Read,
ReadAsBytes,
ReadAsDecimal,
ReadAsDateTimeOffset
}
private readonly TextReader _reader;
private readonly StringBuffer _buffer;
private char? _lastChar;
private int _currentLinePosition;
private int _currentLineNumber;
private bool _end;
private ReadType _readType;
private CultureInfo _culture;
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.CurrentCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.CurrentCulture; }
set { _culture = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
/// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param>
public JsonTextReader(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = reader;
_buffer = new StringBuffer(4096);
_currentLineNumber = 1;
}
private void ParseString(char quote)
{
ReadStringIntoBuffer(quote);
if (_readType == ReadType.ReadAsBytes)
{
byte[] data;
if (_buffer.Position == 0)
{
data = new byte[0];
}
else
{
data = Convert.FromBase64CharArray(_buffer.GetInternalBuffer(), 0, _buffer.Position);
_buffer.Position = 0;
}
SetToken(JsonToken.Bytes, data);
}
else
{
string text = _buffer.ToString();
_buffer.Position = 0;
if (text.StartsWith("/Date(", StringComparison.Ordinal) && text.EndsWith(")/", StringComparison.Ordinal))
{
ParseDate(text);
}
else
{
SetToken(JsonToken.String, text);
QuoteChar = quote;
}
}
}
private void ReadStringIntoBuffer(char quote)
{
while (true)
{
char currentChar = MoveNext();
switch (currentChar)
{
case '\0':
if (_end)
throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition);
_buffer.Append('\0');
break;
case '\\':
if ((currentChar = MoveNext()) != '\0' || !_end)
{
switch (currentChar)
{
case 'b':
_buffer.Append('\b');
break;
case 't':
_buffer.Append('\t');
break;
case 'n':
_buffer.Append('\n');
break;
case 'f':
_buffer.Append('\f');
break;
case 'r':
_buffer.Append('\r');
break;
case '\\':
_buffer.Append('\\');
break;
case '"':
case '\'':
case '/':
_buffer.Append(currentChar);
break;
case 'u':
char[] hexValues = new char[4];
for (int i = 0; i < hexValues.Length; i++)
{
if ((currentChar = MoveNext()) != '\0' || !_end)
hexValues[i] = currentChar;
else
throw CreateJsonReaderException("Unexpected end while parsing unicode character. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
char hexChar = Convert.ToChar(int.Parse(new string(hexValues), NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
_buffer.Append(hexChar);
break;
default:
throw CreateJsonReaderException("Bad JSON escape sequence: {0}. Line {1}, position {2}.", @"\" + currentChar, _currentLineNumber, _currentLinePosition);
}
}
else
{
throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition);
}
break;
case '"':
case '\'':
if (currentChar == quote)
{
return;
}
else
{
_buffer.Append(currentChar);
}
break;
default:
_buffer.Append(currentChar);
break;
}
}
}
private JsonReaderException CreateJsonReaderException(string format, params object[] args)
{
string message = format.FormatWith(CultureInfo.InvariantCulture, args);
return new JsonReaderException(message, null, _currentLineNumber, _currentLinePosition);
}
private TimeSpan ReadOffset(string offsetText)
{
bool negative = (offsetText[0] == '-');
int hours = int.Parse(offsetText.Substring(1, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
int minutes = 0;
if (offsetText.Length >= 5)
minutes = int.Parse(offsetText.Substring(3, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
TimeSpan offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
if (negative)
offset = offset.Negate();
return offset;
}
private void ParseDate(string text)
{
string value = text.Substring(6, text.Length - 8);
DateTimeKind kind = DateTimeKind.Utc;
int index = value.IndexOf('+', 1);
if (index == -1)
index = value.IndexOf('-', 1);
TimeSpan offset = TimeSpan.Zero;
if (index != -1)
{
kind = DateTimeKind.Local;
offset = ReadOffset(value.Substring(index));
value = value.Substring(0, index);
}
long javaScriptTicks = long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture);
DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
if (_readType == ReadType.ReadAsDateTimeOffset)
{
SetToken(JsonToken.Date, new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset));
}
else
{
DateTime dateTime;
switch (kind)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
SetToken(JsonToken.Date, dateTime);
}
}
private const int LineFeedValue = StringUtils.LineFeed;
private const int CarriageReturnValue = StringUtils.CarriageReturn;
private char MoveNext()
{
int value = _reader.Read();
switch (value)
{
case -1:
_end = true;
return '\0';
case CarriageReturnValue:
if (_reader.Peek() == LineFeedValue)
_reader.Read();
_currentLineNumber++;
_currentLinePosition = 0;
break;
case LineFeedValue:
_currentLineNumber++;
_currentLinePosition = 0;
break;
default:
_currentLinePosition++;
break;
}
return (char)value;
}
private bool HasNext()
{
return (_reader.Peek() != -1);
}
private int PeekNext()
{
return _reader.Peek();
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
_readType = ReadType.Read;
return ReadInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null.
/// </returns>
public override byte[] ReadAsBytes()
{
_readType = ReadType.ReadAsBytes;
do
{
if (!ReadInternal())
throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Bytes)
return (byte[]) Value;
if (TokenType == JsonToken.StartArray)
{
List<byte> data = new List<byte>();
while (ReadInternal())
{
switch (TokenType)
{
case JsonToken.Integer:
data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
byte[] d = data.ToArray();
SetToken(JsonToken.Bytes, d);
return d;
case JsonToken.Comment:
// skip
break;
default:
throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition);
}
}
throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition);
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>.</returns>
public override decimal? ReadAsDecimal()
{
_readType = ReadType.ReadAsDecimal;
do
{
if (!ReadInternal())
throw CreateJsonReaderException("Unexpected end when reading decimal: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Float)
return (decimal?)Value;
decimal d;
if (TokenType == JsonToken.String && decimal.TryParse((string)Value, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d);
return d;
}
throw CreateJsonReaderException("Unexpected token when reading decimal: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition);
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="DateTimeOffset"/>.</returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
_readType = ReadType.ReadAsDateTimeOffset;
do
{
if (!ReadInternal())
throw CreateJsonReaderException("Unexpected end when reading date: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Date)
return (DateTimeOffset)Value;
DateTimeOffset dt;
if (TokenType == JsonToken.String && DateTimeOffset.TryParse((string)Value, Culture, DateTimeStyles.None, out dt))
{
SetToken(JsonToken.Date, dt);
return dt;
}
throw CreateJsonReaderException("Unexpected token when reading date: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition);
}
private bool ReadInternal()
{
while (true)
{
char currentChar;
if (_lastChar != null)
{
currentChar = _lastChar.Value;
_lastChar = null;
}
else
{
currentChar = MoveNext();
}
if (currentChar == '\0' && _end)
return false;
switch (CurrentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValue(currentChar);
case State.Complete:
break;
case State.Object:
case State.ObjectStart:
return ParseObject(currentChar);
case State.PostValue:
// returns true if it hits
// end of object or array
if (ParsePostValue(currentChar))
return true;
break;
case State.Closed:
break;
case State.Error:
break;
default:
throw CreateJsonReaderException("Unexpected state: {0}. Line {1}, position {2}.", CurrentState, _currentLineNumber, _currentLinePosition);
}
}
}
private bool ParsePostValue(char currentChar)
{
do
{
switch (currentChar)
{
case '}':
SetToken(JsonToken.EndObject);
return true;
case ']':
SetToken(JsonToken.EndArray);
return true;
case ')':
SetToken(JsonToken.EndConstructor);
return true;
case '/':
ParseComment();
return true;
case ',':
// finished parsing
SetStateBasedOnCurrent();
return false;
case ' ':
case StringUtils.Tab:
case StringUtils.LineFeed:
case StringUtils.CarriageReturn:
// eat
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
}
else
{
throw CreateJsonReaderException("After parsing a value an unexpected character was encountered: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition);
}
break;
}
} while ((currentChar = MoveNext()) != '\0' || !_end);
return false;
}
private bool ParseObject(char currentChar)
{
do
{
switch (currentChar)
{
case '}':
SetToken(JsonToken.EndObject);
return true;
case '/':
ParseComment();
return true;
case ' ':
case StringUtils.Tab:
case StringUtils.LineFeed:
case StringUtils.CarriageReturn:
// eat
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
}
else
{
return ParseProperty(currentChar);
}
break;
}
} while ((currentChar = MoveNext()) != '\0' || !_end);
return false;
}
private bool ParseProperty(char firstChar)
{
char currentChar = firstChar;
char quoteChar;
if (ValidIdentifierChar(currentChar))
{
quoteChar = '\0';
currentChar = ParseUnquotedProperty(currentChar);
}
else if (currentChar == '"' || currentChar == '\'')
{
quoteChar = currentChar;
ReadStringIntoBuffer(quoteChar);
currentChar = MoveNext();
}
else
{
throw CreateJsonReaderException("Invalid property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition);
}
if (currentChar != ':')
{
currentChar = MoveNext();
// finished property. skip any whitespace and move to colon
EatWhitespace(currentChar, false, out currentChar);
if (currentChar != ':')
throw CreateJsonReaderException("Invalid character after parsing property name. Expected ':' but got: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition);
}
SetToken(JsonToken.PropertyName, _buffer.ToString());
QuoteChar = quoteChar;
_buffer.Position = 0;
return true;
}
private bool ValidIdentifierChar(char value)
{
return (char.IsLetterOrDigit(value) || value == '_' || value == '$');
}
private char ParseUnquotedProperty(char firstChar)
{
// parse unquoted property name until whitespace or colon
_buffer.Append(firstChar);
char currentChar;
while ((currentChar = MoveNext()) != '\0' || !_end)
{
if (char.IsWhiteSpace(currentChar) || currentChar == ':')
{
return currentChar;
}
else if (ValidIdentifierChar(currentChar))
{
_buffer.Append(currentChar);
}
else
{
throw CreateJsonReaderException("Invalid JavaScript property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition);
}
}
throw CreateJsonReaderException("Unexpected end when parsing unquoted property name. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
private bool ParseValue(char currentChar)
{
do
{
switch (currentChar)
{
case '"':
case '\'':
ParseString(currentChar);
return true;
case 't':
ParseTrue();
return true;
case 'f':
ParseFalse();
return true;
case 'n':
if (HasNext())
{
char next = (char)PeekNext();
if (next == 'u')
ParseNull();
else if (next == 'e')
ParseConstructor();
else
throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition);
}
else
{
throw CreateJsonReaderException("Unexpected end. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
return true;
case 'N':
ParseNumberNaN();
return true;
case 'I':
ParseNumberPositiveInfinity();
return true;
case '-':
if (PeekNext() == 'I')
ParseNumberNegativeInfinity();
else
ParseNumber(currentChar);
return true;
case '/':
ParseComment();
return true;
case 'u':
ParseUndefined();
return true;
case '{':
SetToken(JsonToken.StartObject);
return true;
case '[':
SetToken(JsonToken.StartArray);
return true;
case '}':
SetToken(JsonToken.EndObject);
return true;
case ']':
SetToken(JsonToken.EndArray);
return true;
case ',':
SetToken(JsonToken.Undefined);
return true;
case ')':
SetToken(JsonToken.EndConstructor);
return true;
case ' ':
case StringUtils.Tab:
case StringUtils.LineFeed:
case StringUtils.CarriageReturn:
// eat
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
}
else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber(currentChar);
return true;
}
else
{
throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition);
}
break;
}
} while ((currentChar = MoveNext()) != '\0' || !_end);
return false;
}
private bool EatWhitespace(char initialChar, bool oneOrMore, out char finalChar)
{
bool whitespace = false;
char currentChar = initialChar;
while (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
whitespace = true;
currentChar = MoveNext();
}
finalChar = currentChar;
return (!oneOrMore || whitespace);
}
private void ParseConstructor()
{
if (MatchValue('n', "new", true))
{
char currentChar = MoveNext();
if (EatWhitespace(currentChar, true, out currentChar))
{
while (char.IsLetter(currentChar))
{
_buffer.Append(currentChar);
currentChar = MoveNext();
}
EatWhitespace(currentChar, false, out currentChar);
if (currentChar != '(')
throw CreateJsonReaderException("Unexpected character while parsing constructor: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition);
string constructorName = _buffer.ToString();
_buffer.Position = 0;
SetToken(JsonToken.StartConstructor, constructorName);
}
}
}
private void ParseNumber(char firstChar)
{
char currentChar = firstChar;
// parse until seperator character or end
bool end = false;
do
{
if (IsSeperator(currentChar))
{
end = true;
_lastChar = currentChar;
}
else
{
_buffer.Append(currentChar);
}
} while (!end && ((currentChar = MoveNext()) != '\0' || !_end));
string number = _buffer.ToString();
object numberValue;
JsonToken numberType;
bool nonBase10 = (firstChar == '0' && !number.StartsWith("0.", StringComparison.OrdinalIgnoreCase));
if (_readType == ReadType.ReadAsDecimal)
{
if (nonBase10)
{
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberValue = Convert.ToDecimal(integer);
}
else
{
numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
}
numberType = JsonToken.Float;
}
else
{
if (nonBase10)
{
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberType = JsonToken.Integer;
}
else if (number.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || number.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
{
numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture);
numberType = JsonToken.Float;
}
else
{
try
{
numberValue = Convert.ToInt64(number, CultureInfo.InvariantCulture);
}
catch (OverflowException ex)
{
throw new JsonReaderException("JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
numberType = JsonToken.Integer;
}
}
_buffer.Position = 0;
SetToken(numberType, numberValue);
}
private void ParseComment()
{
// should have already parsed / character before reaching this method
char currentChar = MoveNext();
if (currentChar == '*')
{
while ((currentChar = MoveNext()) != '\0' || !_end)
{
if (currentChar == '*')
{
if ((currentChar = MoveNext()) != '\0' || !_end)
{
if (currentChar == '/')
{
break;
}
else
{
_buffer.Append('*');
_buffer.Append(currentChar);
}
}
}
else
{
_buffer.Append(currentChar);
}
}
}
else
{
throw CreateJsonReaderException("Error parsing comment. Expected: *. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
SetToken(JsonToken.Comment, _buffer.ToString());
_buffer.Position = 0;
}
private bool MatchValue(char firstChar, string value)
{
char currentChar = firstChar;
int i = 0;
do
{
if (currentChar != value[i])
{
break;
}
i++;
}
while (i < value.Length && ((currentChar = MoveNext()) != '\0' || !_end));
return (i == value.Length);
}
private bool MatchValue(char firstChar, string value, bool noTrailingNonSeperatorCharacters)
{
// will match value and then move to the next character, checking that it is a seperator character
bool match = MatchValue(firstChar, value);
if (!noTrailingNonSeperatorCharacters)
{
return match;
}
else
{
int c = PeekNext();
char next = (c != -1) ? (char) c : '\0';
bool matchAndNoTrainingNonSeperatorCharacters = (match && (next == '\0' || IsSeperator(next)));
return matchAndNoTrainingNonSeperatorCharacters;
}
}
private bool IsSeperator(char c)
{
switch (c)
{
case '}':
case ']':
case ',':
return true;
case '/':
// check next character to see if start of a comment
return (HasNext() && PeekNext() == '*');
case ')':
if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart)
return true;
break;
case ' ':
case StringUtils.Tab:
case StringUtils.LineFeed:
case StringUtils.CarriageReturn:
return true;
default:
if (char.IsWhiteSpace(c))
return true;
break;
}
return false;
}
private void ParseTrue()
{
// check characters equal 'true'
// and that it is followed by either a seperator character
// or the text ends
if (MatchValue('t', JsonConvert.True, true))
{
SetToken(JsonToken.Boolean, true);
}
else
{
throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
}
private void ParseNull()
{
if (MatchValue('n', JsonConvert.Null, true))
{
SetToken(JsonToken.Null);
}
else
{
throw CreateJsonReaderException("Error parsing null value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
}
private void ParseUndefined()
{
if (MatchValue('u', JsonConvert.Undefined, true))
{
SetToken(JsonToken.Undefined);
}
else
{
throw CreateJsonReaderException("Error parsing undefined value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
}
private void ParseFalse()
{
if (MatchValue('f', JsonConvert.False, true))
{
SetToken(JsonToken.Boolean, false);
}
else
{
throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
}
private void ParseNumberNegativeInfinity()
{
if (MatchValue('-', JsonConvert.NegativeInfinity, true))
{
SetToken(JsonToken.Float, double.NegativeInfinity);
}
else
{
throw CreateJsonReaderException("Error parsing negative infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
}
private void ParseNumberPositiveInfinity()
{
if (MatchValue('I', JsonConvert.PositiveInfinity, true))
{
SetToken(JsonToken.Float, double.PositiveInfinity);
}
else
{
throw CreateJsonReaderException("Error parsing positive infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
}
private void ParseNumberNaN()
{
if (MatchValue('N', JsonConvert.NaN, true))
{
SetToken(JsonToken.Float, double.NaN);
}
else
{
throw CreateJsonReaderException("Error parsing NaN value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
}
/// <summary>
/// Changes the state to closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput && _reader != null)
_reader.Close();
if (_buffer != null)
_buffer.Clear();
}
/// <summary>
/// Gets a value indicating whether the class can return line information.
/// </summary>
/// <returns>
/// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>.
/// </returns>
public bool HasLineInfo()
{
return true;
}
/// <summary>
/// Gets the current line number.
/// </summary>
/// <value>
/// The current line number or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LineNumber
{
get
{
if (CurrentState == State.Start)
return 0;
return _currentLineNumber;
}
}
/// <summary>
/// Gets the current line position.
/// </summary>
/// <value>
/// The current line position or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LinePosition
{
get { return _currentLinePosition; }
}
}
}
#endif
| |
using System;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Json;
using Serilog.Settings.KeyValuePairs;
using Serilog.Tests.Support;
using Xunit;
namespace Serilog.Tests.Settings
{
public class SettingValueConversionsTests
{
[Fact]
public void ConvertibleValuesConvertToTIfTargetIsNullable()
{
var result = (int?)SettingValueConversions.ConvertToType("3", typeof(int?));
Assert.True(result == 3);
}
[Fact]
public void NullValuesConvertToNullIfTargetIsNullable()
{
var result = (int?)SettingValueConversions.ConvertToType(null, typeof(int?));
Assert.True(result == null);
}
[Fact]
public void EmptyStringValuesConvertToNullIfTargetIsNullable()
{
var result = (int?)SettingValueConversions.ConvertToType("", typeof(int?));
Assert.True(result == null);
}
[Fact]
public void ValuesConvertToNullableTimeSpan()
{
var result = (TimeSpan?)SettingValueConversions.ConvertToType("00:01:00", typeof(TimeSpan?));
Assert.Equal(TimeSpan.FromMinutes(1), result);
}
[Fact]
public void ValuesConvertToEnumMembers()
{
var result = (LogEventLevel)SettingValueConversions.ConvertToType("Information", typeof(LogEventLevel));
Assert.Equal(LogEventLevel.Information, result);
}
[Fact]
public void ValuesConvertToStringArray()
{
var result = (string[])SettingValueConversions.ConvertToType("key1=value1,key2=value2", typeof(string[]));
Assert.Equal(2, result.Length);
Assert.Equal("key1=value1", result[0]);
Assert.Equal("key2=value2", result[1]);
}
[Fact]
public void ValuesConvertToStringArrayEmpty()
{
var result = (string[])SettingValueConversions.ConvertToType("", typeof(string[]));
Assert.Empty(result);
}
[Fact]
public void ValuesConvertToIntArray()
{
var result = (int[])SettingValueConversions.ConvertToType("1,2", typeof(int[]));
Assert.Equal(2, result.Length);
Assert.Equal(1, result[0]);
Assert.Equal(2, result[1]);
}
[Fact]
public void ValuesConvertToIntArrayEmpty()
{
var result = (int[])SettingValueConversions.ConvertToType("", typeof(int[]));
Assert.Empty(result);
}
[Fact]
public void ValuesConvertToTypeFromQualifiedName()
{
var result = (Type)SettingValueConversions.ConvertToType("System.Version", typeof(Type));
Assert.Equal(typeof(Version), result);
}
[Fact]
public void ValuesConvertToTypeFromAssemblyQualifiedName()
{
var assemblyQualifiedName = typeof(Version).AssemblyQualifiedName;
var result = (Type)SettingValueConversions.ConvertToType(assemblyQualifiedName, typeof(Type));
Assert.Equal(typeof(Version), result);
}
[Fact]
public void StringValuesConvertToDefaultInstancesIfTargetIsInterface()
{
var result = SettingValueConversions.ConvertToType("Serilog.Formatting.Json.JsonFormatter", typeof(ITextFormatter));
Assert.IsType<JsonFormatter>(result);
}
[Fact]
public void StringValuesConvertToDefaultInstancesIfTargetIsAbstractClass()
{
var result = SettingValueConversions.ConvertToType("Serilog.Tests.Support.DummyConcreteClassWithDefaultConstructor, Serilog.Tests", typeof(DummyAbstractClass));
Assert.IsType<DummyConcreteClassWithDefaultConstructor>(result);
}
[Fact]
public void StringValuesThrowsWhenMissingDefaultConstructorIfTargetIsAbstractClass()
{
var value = "Serilog.Tests.Support.DummyConcreteClassWithoutDefaultConstructor, Serilog.Tests";
Assert.Throws<InvalidOperationException>(() =>
SettingValueConversions.ConvertToType(value, typeof(DummyAbstractClass)));
}
[Theory]
[InlineData("3.14:21:18.986", 3 /*days*/, 14 /*hours*/, 21 /*min*/, 18 /*sec*/, 986 /*ms*/)]
[InlineData("4", 4, 0, 0, 0, 0)] // minimal : days
[InlineData("2:0", 0, 2, 0, 0, 0)] // minimal hours
[InlineData("0:5", 0, 0, 5, 0, 0)] // minimal minutes
[InlineData("0:0:7", 0, 0, 0, 7, 0)] // minimal seconds
[InlineData("0:0:0.2", 0, 0, 0, 0, 200)] // minimal milliseconds
public void TimeSpanValuesCanBeParsed(string input, int expDays, int expHours, int expMin, int expSec, int expMs)
{
var expectedTimeSpan = new TimeSpan(expDays, expHours, expMin, expSec, expMs);
var actual = SettingValueConversions.ConvertToType(input, typeof(TimeSpan));
Assert.IsType<TimeSpan>(actual);
Assert.Equal(expectedTimeSpan, actual);
}
[Theory]
[InlineData("My.NameSpace.Class+InnerClass::Member",
"My.NameSpace.Class+InnerClass", "Member")]
[InlineData(" TrimMe.NameSpace.Class::NeedsTrimming ",
"TrimMe.NameSpace.Class", "NeedsTrimming")]
[InlineData("My.NameSpace.Class::Member",
"My.NameSpace.Class", "Member")]
[InlineData("My.NameSpace.Class::Member, MyAssembly",
"My.NameSpace.Class, MyAssembly", "Member")]
[InlineData("My.NameSpace.Class::Member, MyAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"My.NameSpace.Class, MyAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Member")]
[InlineData("Just a random string with :: in it",
null, null)]
[InlineData("Its::a::trapWithColonsAppearingTwice",
null, null)]
[InlineData("ThereIsNoMemberHere::",
null, null)]
[InlineData(null,
null, null)]
[InlineData(" ",
null, null)]
// a full-qualified type name should not be considered a static member accessor
[InlineData("My.NameSpace.Class, MyAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
null, null)]
public void TryParseStaticMemberAccessorReturnsExpectedResults(string input, string expectedAccessorType, string expectedPropertyName)
{
var actual = SettingValueConversions.TryParseStaticMemberAccessor(input,
out var actualAccessorType,
out var actualMemberName);
if (expectedAccessorType == null)
{
Assert.False(actual, $"Should not parse {input}");
}
else
{
Assert.True(actual, $"should successfully parse {input}");
Assert.Equal(expectedAccessorType, actualAccessorType);
Assert.Equal(expectedPropertyName, actualMemberName);
}
}
[Theory]
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::InterfaceProperty, Serilog.Tests", typeof(IAmAnInterface))]
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::AbstractProperty, Serilog.Tests", typeof(AnAbstractClass))]
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::InterfaceField, Serilog.Tests", typeof(IAmAnInterface))]
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::AbstractField, Serilog.Tests", typeof(AnAbstractClass))]
public void StaticMembersAccessorsCanBeUsedForReferenceTypes(string input, Type targetType)
{
var actual = SettingValueConversions.ConvertToType(input, targetType);
Assert.IsAssignableFrom(targetType, actual);
Assert.Equal(ConcreteImpl.Instance, actual);
}
[Theory]
// unknown type
[InlineData("Namespace.ThisIsNotAKnownType::InterfaceProperty, Serilog.Tests", typeof(IAmAnInterface))]
// good type name, but wrong namespace
[InlineData("Random.Namespace.ClassWithStaticAccessors::InterfaceProperty, Serilog.Tests", typeof(IAmAnInterface))]
// good full type name, but missing or wrong assembly
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::InterfaceProperty", typeof(IAmAnInterface))]
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::InterfaceProperty, TestDummies", typeof(IAmAnInterface))]
public void StaticAccessorOnUnknownTypeThrowsTypeLoadException(string input, Type targetType)
{
Assert.Throws<TypeLoadException>(() =>
SettingValueConversions.ConvertToType(input, targetType)
);
}
[Theory]
// unknown member
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::UnknownMember, Serilog.Tests", typeof(IAmAnInterface))]
// static property exists but it's private
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::PrivateInterfaceProperty, Serilog.Tests", typeof(IAmAnInterface))]
// static field exists but it's private
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::PrivateInterfaceField, Serilog.Tests", typeof(IAmAnInterface))]
// public property exists but it's not static
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::InstanceInterfaceProperty, Serilog.Tests", typeof(IAmAnInterface))]
// public field exists but it's not static
[InlineData("Serilog.Tests.Support.ClassWithStaticAccessors::InstanceInterfaceField, Serilog.Tests", typeof(IAmAnInterface))]
public void StaticAccessorWithInvalidMemberThrowsInvalidOperationException(string input, Type targetType)
{
var exception = Assert.Throws<InvalidOperationException>(() =>
SettingValueConversions.ConvertToType(input, targetType)
);
Assert.Contains("Could not find a public static property or field ", exception.Message);
Assert.Contains("on type `Serilog.Tests.Support.ClassWithStaticAccessors, Serilog.Tests`", exception.Message);
}
}
}
| |
// ------------------------------------------------------------------------
// Orthello 2D Framework Example Source Code
// (C)opyright 2011 - WyrmTale Games - http://www.wyrmtale.com
// ------------------------------------------------------------------------
// More info http://www.wyrmtale.com/orthello
// ------------------------------------------------------------------------
// Example 5
// Creation of objects by code
// ------------------------------------------------------------------------
// Main Example 5 Demo class
// ------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CExample5 : MonoBehaviour {
public Texture greenStarsAnimation; // texture with rotating star frames
public Texture walkingManAnimation; // texture with walking man frames
public Texture whiteTile; // Just a white wyrmtale tile
public GameObject stage1; // stage1 menu itmem
public GameObject stage2; // stage2 menu itmem
bool initialized = false; // initialization indicator
int appMode = 1; // application mode ( 1 = stars, 2 = walking man )
OTAnimatingSprite star; // center star animating sprite, used as prototype
List<OTAnimatingSprite> stars = // moving stars
new List<OTAnimatingSprite>();
OTAnimatingSprite man; // walking man animating sprite
OTFilledSprite back; // background
float starSpeed = 0.25f; // star creation frequency
float starTime = 0; // star creation wait time
TextMesh stagemesh1; // textmesh for stage 1 menu item
TextMesh stagemesh2; // textmesh for stage 1 menu item
// Create all objects fo r the star stage by code
void AnimatingGreenStarStage()
{
// To create a scrolling background, first create a filled sprite object
back = OT.CreateObject(OTObjectType.FilledSprite).GetComponent<OTFilledSprite>();
// Set the image to the tile texture
back.image = whiteTile;
// Set material reference to 'custom' blue material
back.materialReference = "blue";
// Set size to match the screen resolution so it will fill the entire screen
back.size = new Vector2(Screen.width,Screen.height);
// Set the display depth all the way back so everything else will come on top
back.depth = 1000;
// Set fill image size to 50 x 50 pixels
back.fillSize = new Vector2(50, 50);
// Set scroll speed so we will scroll horizontally 20 px / second
back.scrollSpeed = new Vector2(20, 0);
// To create the animating star we first have to create the sprite sheet object that will
// hold our texture/animation frames
OTSpriteSheet sheet = OT.CreateObject(OTObjectType.SpriteSheet).GetComponent<OTSpriteSheet>();
// Give our sheet a name
sheet.name = "mySheet";
// Assign texture
sheet.texture = greenStarsAnimation;
// Specify how many columns and rows we have (frames)
sheet.framesXY = new Vector2(25, 3);
// Because we have some overhead space to the right and bottom of our texture we have to
// specify the original texture size and the original frame size so that the right texture
// scale and offsetting can be calculated.
sheet.sheetSize = new Vector2(2048, 256);
sheet.frameSize = new Vector2(80, 80);
// Next thing is to create the animation that our animating sprite will use
OTAnimation animation = OT.CreateObject(OTObjectType.Animation).GetComponent<OTAnimation>();
// This animation will use only one frameset with all animating star frames.
OTAnimationFrameset frameset = new OTAnimationFrameset();
// Link up the sprite sheet to this animation's frameset
frameset.container = sheet;
// Frameset animation will start at frame index 0
frameset.startFrame = 0;
// Frameset animation will end at frame index 69
frameset.endFrame = 69;
// Assign this frameset to the animation.
// HINT : by asigning more than one frameset it is possible to create an animation that will span
// across mutiple framesets
// HINT : Because it is possible (and very easy) to play a specific frameset of an animation
// One could pack a lot of animations into one animation object.
animation.framesets = new OTAnimationFrameset[] { frameset };
// Set the duration of this animation
// HINT : By using the OTAnimationSprite.speed setting one can speed up or slow down a
// running animation without changing the OTAnimation.fps or .duration setting.
animation.duration = .95f;
// Lets give our animation a name
animation.name = "star-animation";
// To finally get the animatiing star on screen we will create our animation sprite object
star = OT.CreateObject(OTObjectType.AnimatingSprite).GetComponent<OTAnimatingSprite>();
// Link up the animation
star.animation = animation;
// Lets start at a random frame
star.startAtRandomFrame = true;
// Lets auto-start this animation
star.playOnStart = true;
// start invisible and make visible when containers are ready.
star.visible = false;
star.name = "star";
star.spriteContainer = sheet;
// INFO : This animation 'star' will be center (0,0) positioned and act as a prototype
// to create more moveing and animating (additive) 'stars'.
}
// Create an walking man animation frameset with 15 images
// INFO : Because our walking man sprite sheet contains 8 direction
// animations of 15 frames. We will put these into seperate animation
// framesets, so they can be played quickly when needed.
OTAnimationFrameset WalkingFrameset(string name, int row, OTContainer sheet)
{
// Create a new frameset
OTAnimationFrameset frameset = new OTAnimationFrameset();
// Give this frameset a name for later reference
frameset.name = name;
// Link our provided sprite sheet
frameset.container = sheet;
// Set the correct start frame
frameset.startFrame = (row - 1) * 15;
// Set the correct end frame
frameset.endFrame = ((row - 1) * 15) + 14;
// Set this frameset's animation duration that will only
// be used when the frameset is played as a single animation
frameset.singleDuration = 0.95f;
// Return this new frameset
return frameset;
}
// Create all objects for the 'walking man' stage
void WalkingBlueManStage()
{
// To create the background lets create a filled sprite object
back = OT.CreateObject(OTObjectType.FilledSprite).GetComponent<OTFilledSprite>();
// Set the image to our wyrmtale tile
back.image = whiteTile;
// But this all the way back so all other objects will be located in front.
back.depth = 1000;
// Set material reference to 'custom' green material - check OT material references
back.materialReference = "green";
// Set the size to match the screen resolution.
back.size = new Vector2(Screen.width, Screen.height);
// Set the fill image size to 50 x 50 pixels
back.fillSize = new Vector2(50, 50);
// To create the walking man animation we first will have to create a sprite sheet
OTSpriteSheet sheet = OT.CreateObject(OTObjectType.SpriteSheet).GetComponent<OTSpriteSheet>();
// Link our walking man frames
sheet.texture = walkingManAnimation;
// specify the number or column and rows (frames) of this container
sheet.framesXY = new Vector2(15, 8);
// The next step is to create our animation object that will hold all
// animation framesets (8 directions of walking) for our walking man
OTAnimation animation = OT.CreateObject(OTObjectType.Animation).GetComponent<OTAnimation>();
// Initialize our animation framesets so it can hold 8 framesets
animation.framesets = new OTAnimationFrameset[8];
// Add the 8 direction framesets
animation.framesets[0] = WalkingFrameset("down",1, sheet);
animation.framesets[1] = WalkingFrameset("downLeft", 2, sheet);
animation.framesets[2] = WalkingFrameset("left", 3, sheet);
animation.framesets[3] = WalkingFrameset("upLeft", 4, sheet);
animation.framesets[4] = WalkingFrameset("up", 5, sheet);
animation.framesets[5] = WalkingFrameset("upRight", 6, sheet);
animation.framesets[6] = WalkingFrameset("right", 7, sheet);
animation.framesets[7] = WalkingFrameset("downRight", 8, sheet);
// Give our animation a name
animation.name = "walking-animation";
// To put our walking man on screen we create an animting sprite object
man = OT.CreateObject(OTObjectType.AnimatingSprite).GetComponent<OTAnimatingSprite>();
// Set the size of our walking man
man.size = new Vector2(40, 65);
// Link our animation
man.animation = animation;
// Lets play a single frameset .. we start with 'down'
man.animationFrameset = "down";
// Auto-start to play this animation frameset
man.playOnStart = true;
// Give our sprite a name
man.name = "man";
// start invisible and make visible when containers are ready.
man.visible = false;
man.spriteContainer = sheet;
// INFO : In this class Update() method, we will check the location of
// the mouse pointer and play the corresponding direction animation
// as we will set the right scroll speed for our background.
}
// (Re)Create our objects
void CreateObjects()
{
OT.objectPooling = false;
// Destroy all objects, containers and animations
OT.DestroyAll();
// Clear our active stars list
stars.Clear();
// check what appMode we are in and create all objects for the
// corresponding stage
switch (appMode)
{
case 1:
AnimatingGreenStarStage();
break;
case 2:
WalkingBlueManStage();
break;
}
}
// Application initialization
void Initialize()
{
// Create all application objects
CreateObjects();
// Get TextMesh objects to color menu's on hover later
stagemesh1 = stage1.GetComponent<TextMesh>();
stagemesh2 = stage2.GetComponent<TextMesh>();
// indicate that we have initialized
initialized = true;
}
// Update is called once per frame
void Update () {
// only go on if Orthello is ready
if (!OT.isValid) return;
// Initialize application once
if (!initialized)
Initialize();
// if containers that were created are not ready yet, lets hold.
if (!OT.ContainersReady())
return;
switch (appMode)
{
case 1:
star.visible = true;
// we are in the star stage so increase star creation wait time
starTime += Time.deltaTime;
// check if we may create a new star
if (starTime > starSpeed)
{
// Lets create one, reset the wait time
starTime = 0;
// Create a copy of out animating star
OTAnimatingSprite newStar = OT.CreateSprite(star) as OTAnimatingSprite;
// Put this star in our active stars list
stars.Add(newStar);
// Give it a random size
newStar.size *= (0.3f + Random.value * 2.5f);
// Give it a random position on the right border of the screen
newStar.position = new Vector2((Screen.width / 2) + newStar.size.x / 2,
((Screen.height / 2) * -1) + newStar.size.y/2 + Random.value * (Screen.height - newStar.size.y));
// Calculate the depth (smaller stars to the back, bigger to the front)
newStar.depth = (int)((1 / newStar.size.x)*100);
// Set material to additive
newStar.additive = true;
newStar.frameIndex = 0;
}
// Lets loop all active stars
// HINT : Because we will be adjusting (removing) items as they get out of view,
// we better not use a for() loop. While() is the better way for this.
int s=0;
while (s<stars.Count)
{
// get next active star
OTAnimatingSprite dStar = stars[s];
// increase its position
dStar.position += new Vector2(stars[s].size.x * 3 * Time.deltaTime * -1, 0);
// If the star gets out of view we will remove and destroy it
if (dStar.outOfView)
{
// remove from active stars list
stars.Remove(dStar);
// destroy this object
OT.DestroyObject(dStar);
// no need to increment iterator as we just removed the current element
}
else
s++; // increment iterator
}
break;
case 2:
man.visible = true;
// we are in the walking man stage so calculate a normalized vector from
// our man to the mouse pointer
Vector2 mouseVector = (OT.view.mouseWorldPosition - man.position).normalized;
// The Atan2 will give you a -3.141 to 3.141 range depending of your vector x/y values
float angle = Mathf.Atan2(mouseVector.x, mouseVector.y);
// Play the right frameset dependent on the angle
float part = 6.2f / 8;
string anim = "";
if (angle > -1 * (part / 2) && angle <= (part / 2)) anim = "up";
else
if (angle > -3 * (part / 2) && angle <= -1 * (part / 2)) anim = "upLeft";
else
if (angle > -5 * (part / 2) && angle <= -3 * (part / 2)) anim = "left";
else
if (angle > -7 * (part / 2) && angle <= -5 * (part / 2)) anim = "downLeft";
else
if (angle > (part / 2) && angle <= 3 * (part / 2)) anim = "upRight";
else
if (angle > 3 * (part / 2) && angle <= 5 * (part / 2)) anim = "right";
else
if (angle > 5 * (part / 2) && angle <= 7 * (part / 2)) anim = "downRight";
else
anim = "down";
man.PlayLoop(anim);
// adjust background scroll speed related to our mouse vector
back.scrollSpeed = mouseVector * 10;
break;
}
// color menu red when we are hovering over an item
if (OT.Over(stage1))
stagemesh1.renderer.material.color = new Color(1, .3f, .3f);
else
stagemesh1.renderer.material.color = new Color(1, 1, 1);
if (OT.Over(stage2))
stagemesh2.renderer.material.color = new Color(1, .3f, .3f);
else
stagemesh2.renderer.material.color = new Color(1, 1, 1);
//check if we want to change stage
if (OT.Clicked(stage1))
{
appMode = 1;
CreateObjects();
}
else
if (OT.Clicked(stage2))
{
appMode = 2;
CreateObjects();
}
}
}
| |
//
// PlayerEngineService.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2006-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using Mono.Unix;
using Mono.Addins;
using Hyena;
using Banshee.Base;
using Banshee.Streaming;
using Banshee.ServiceStack;
using Banshee.Metadata;
using Banshee.Configuration;
using Banshee.Collection;
using Banshee.Equalizer;
using Banshee.Collection.Database;
namespace Banshee.MediaEngine
{
public delegate bool TrackInterceptHandler (TrackInfo track);
public class PlayerEngineService : IInitializeService, IDelayedInitializeService,
IRequiredService, IPlayerEngineService, IDisposable
{
private List<PlayerEngine> engines = new List<PlayerEngine> ();
private PlayerEngine active_engine;
private PlayerEngine default_engine;
private PlayerEngine pending_engine;
private object pending_playback_for_not_ready;
private bool pending_playback_for_not_ready_play;
private TrackInfo synthesized_contacting_track;
private string preferred_engine_id = null;
public event EventHandler PlayWhenIdleRequest;
public event TrackInterceptHandler TrackIntercept;
public event Action<PlayerEngine> EngineBeforeInitialize;
public event Action<PlayerEngine> EngineAfterInitialize;
private event DBusPlayerEventHandler dbus_event_changed;
event DBusPlayerEventHandler IPlayerEngineService.EventChanged {
add { dbus_event_changed += value; }
remove { dbus_event_changed -= value; }
}
private event DBusPlayerStateHandler dbus_state_changed;
event DBusPlayerStateHandler IPlayerEngineService.StateChanged {
add { dbus_state_changed += value; }
remove { dbus_state_changed -= value; }
}
public PlayerEngineService ()
{
}
void IInitializeService.Initialize ()
{
preferred_engine_id = EngineSchema.Get();
if (default_engine == null && engines.Count > 0) {
default_engine = engines[0];
}
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/MediaEngine/PlayerEngine")) {
LoadEngine (node);
}
if (default_engine != null) {
active_engine = default_engine;
Log.Debug (Catalog.GetString ("Default player engine"), active_engine.Name);
} else {
default_engine = active_engine;
}
if (default_engine == null || active_engine == null || engines == null || engines.Count == 0) {
Log.Warning (Catalog.GetString (
"No player engines were found. Please ensure Banshee has been cleanly installed."),
"Using the featureless NullPlayerEngine.");
PlayerEngine null_engine = new NullPlayerEngine ();
LoadEngine (null_engine);
active_engine = null_engine;
default_engine = null_engine;
}
MetadataService.Instance.HaveResult += OnMetadataServiceHaveResult;
TrackInfo.IsPlayingMethod = track => IsPlaying (track) &&
track.CacheModelId == CurrentTrack.CacheModelId &&
(track.CacheEntryId == null || track.CacheEntryId.Equals (CurrentTrack.CacheEntryId));
}
private void InitializeEngine (PlayerEngine engine)
{
var handler = EngineBeforeInitialize;
if (handler != null) {
handler (engine);
}
engine.Initialize ();
engine.IsInitialized = true;
handler = EngineAfterInitialize;
if (handler != null) {
handler (engine);
}
}
void IDelayedInitializeService.DelayedInitialize ()
{
foreach (var engine in Engines) {
if (engine.DelayedInitialize) {
InitializeEngine (engine);
}
}
}
private void LoadEngine (TypeExtensionNode node)
{
LoadEngine ((PlayerEngine) node.CreateInstance (typeof (PlayerEngine)));
}
private void LoadEngine (PlayerEngine engine)
{
if (!engine.DelayedInitialize) {
InitializeEngine (engine);
}
engine.EventChanged += OnEngineEventChanged;
if (engine.Id == preferred_engine_id) {
DefaultEngine = engine;
} else {
if (active_engine == null) {
active_engine = engine;
}
engines.Add (engine);
}
}
public void Dispose ()
{
MetadataService.Instance.HaveResult -= OnMetadataServiceHaveResult;
foreach (PlayerEngine engine in engines) {
engine.Dispose ();
}
active_engine = null;
default_engine = null;
pending_engine = null;
preferred_engine_id = null;
engines.Clear ();
}
private void OnMetadataServiceHaveResult (object o, MetadataLookupResultArgs args)
{
if (CurrentTrack != null && CurrentTrack.TrackEqual (args.Track as TrackInfo)) {
foreach (StreamTag tag in args.ResultTags) {
StreamTagger.TrackInfoMerge (CurrentTrack, tag);
}
OnEngineEventChanged (new PlayerEventArgs (PlayerEvent.TrackInfoUpdated));
}
}
private void HandleStateChange (PlayerEventStateChangeArgs args)
{
if (args.Current == PlayerState.Loaded && CurrentTrack != null) {
MetadataService.Instance.Lookup (CurrentTrack);
} else if (args.Current == PlayerState.Ready) {
// Enable our preferred equalizer if it exists and was enabled last time.
if (SupportsEqualizer) {
EqualizerManager.Instance.Select ();
}
if (pending_playback_for_not_ready != null) {
OpenCheck (pending_playback_for_not_ready, pending_playback_for_not_ready_play);
pending_playback_for_not_ready = null;
pending_playback_for_not_ready_play = false;
}
}
DBusPlayerStateHandler dbus_handler = dbus_state_changed;
if (dbus_handler != null) {
dbus_handler (args.Current.ToString ().ToLower ());
}
}
private void OnEngineEventChanged (PlayerEventArgs args)
{
if (CurrentTrack != null) {
if (args.Event == PlayerEvent.Error
&& CurrentTrack.PlaybackError == StreamPlaybackError.None) {
CurrentTrack.SavePlaybackError (StreamPlaybackError.Unknown);
} else if (args.Event == PlayerEvent.Iterate
&& CurrentTrack.PlaybackError != StreamPlaybackError.None) {
CurrentTrack.SavePlaybackError (StreamPlaybackError.None);
}
}
if (args.Event == PlayerEvent.StartOfStream) {
incremented_last_played = false;
} else if (args.Event == PlayerEvent.EndOfStream) {
IncrementLastPlayed ();
}
RaiseEvent (args);
// Do not raise iterate across DBus to avoid so many calls;
// DBus clients should do their own iterating and
// event/state checking locally
if (args.Event == PlayerEvent.Iterate) {
return;
}
DBusPlayerEventHandler dbus_handler = dbus_event_changed;
if (dbus_handler != null) {
dbus_handler (args.Event.ToString ().ToLower (),
args is PlayerEventErrorArgs ? ((PlayerEventErrorArgs)args).Message : String.Empty,
args is PlayerEventBufferingArgs ? ((PlayerEventBufferingArgs)args).Progress : 0
);
}
}
private void OnPlayWhenIdleRequest ()
{
EventHandler handler = PlayWhenIdleRequest;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private bool OnTrackIntercept (TrackInfo track)
{
TrackInterceptHandler handler = TrackIntercept;
if (handler == null) {
return false;
}
bool handled = false;
foreach (TrackInterceptHandler single_handler in handler.GetInvocationList ()) {
handled |= single_handler (track);
}
return handled;
}
public void Open (TrackInfo track)
{
OpenPlay (track, false);
}
public void Open (SafeUri uri)
{
// Check if the uri exists
if (uri == null || !File.Exists (uri.AbsolutePath)) {
return;
}
// Try to find uri in the library
int track_id = DatabaseTrackInfo.GetTrackIdForUri (uri);
if (track_id > 0) {
DatabaseTrackInfo track_db = DatabaseTrackInfo.Provider.FetchSingle (track_id);
Open (track_db);
} else {
// Not in the library, get info from the file
TrackInfo track = new TrackInfo ();
using (var file = StreamTagger.ProcessUri (uri)) {
StreamTagger.TrackInfoMerge (track, file, false);
}
Open (track);
}
}
void IPlayerEngineService.Open (string uri)
{
Open (new SafeUri (uri));
}
public void SetNextTrack (TrackInfo track)
{
if (track != null && EnsureActiveEngineCanPlay (track.Uri)) {
active_engine.SetNextTrack (track);
} else {
active_engine.SetNextTrack ((TrackInfo) null);
}
}
public void SetNextTrack (SafeUri uri)
{
if (EnsureActiveEngineCanPlay (uri)) {
active_engine.SetNextTrack (uri);
} else {
active_engine.SetNextTrack ((SafeUri) null);
}
}
private bool EnsureActiveEngineCanPlay (SafeUri uri)
{
if (uri == null) {
// No engine can play the null URI.
return false;
}
if (active_engine != FindSupportingEngine (uri)) {
if (active_engine.CurrentState == PlayerState.Playing) {
// If we're currently playing then we can't switch engines now.
// We can't ensure the active engine can play this URI.
return false;
} else {
// If we're not playing, we can switch the active engine to
// something that will play this URI.
SwitchToEngine (FindSupportingEngine (uri));
CheckPending ();
return true;
}
}
return true;
}
public void OpenPlay (TrackInfo track)
{
OpenPlay (track, true);
}
private void OpenPlay (TrackInfo track, bool play)
{
if (track == null || !track.CanPlay || OnTrackIntercept (track)) {
return;
}
try {
OpenCheck (track, play);
} catch (Exception e) {
Log.Exception (e);
Log.Error (Catalog.GetString ("Problem with Player Engine"), e.Message, true);
Close ();
ActiveEngine = default_engine;
}
}
private void OpenCheck (object o, bool play)
{
if (CurrentState == PlayerState.NotReady) {
pending_playback_for_not_ready = o;
pending_playback_for_not_ready_play = play;
return;
}
SafeUri uri = null;
TrackInfo track = null;
if (o is SafeUri) {
uri = (SafeUri)o;
} else if (o is TrackInfo) {
track = (TrackInfo)o;
uri = track.Uri;
} else {
return;
}
if (track != null && (track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) {
RaiseEvent (new PlayerEventArgs (PlayerEvent.EndOfStream));
return;
}
PlayerEngine supportingEngine = FindSupportingEngine (uri);
SwitchToEngine (supportingEngine);
CheckPending ();
if (track != null) {
active_engine.Open (track);
} else if (uri != null) {
active_engine.Open (uri);
}
if (play) {
active_engine.Play ();
}
}
public void IncrementLastPlayed ()
{
// If Length <= 0 assume 100% completion.
IncrementLastPlayed (active_engine.Length <= 0
? 1.0
: (double)active_engine.Position / active_engine.Length);
}
private bool incremented_last_played = true;
public void IncrementLastPlayed (double completed)
{
if (!incremented_last_played && CurrentTrack != null && CurrentTrack.PlaybackError == StreamPlaybackError.None) {
CurrentTrack.OnPlaybackFinished (completed);
incremented_last_played = true;
}
}
private PlayerEngine FindSupportingEngine (SafeUri uri)
{
foreach (PlayerEngine engine in engines) {
foreach (string extension in engine.ExplicitDecoderCapabilities) {
if (!uri.AbsoluteUri.EndsWith (extension)) {
continue;
}
return engine;
}
}
foreach (PlayerEngine engine in engines) {
foreach (string scheme in engine.SourceCapabilities) {
bool supported = scheme == uri.Scheme;
if (supported) {
return engine;
}
}
}
// If none of our engines support this URI, return the currently active one.
// There doesn't seem to be anything better to do.
return active_engine;
}
private bool SwitchToEngine (PlayerEngine switchTo)
{
if (active_engine != switchTo) {
Close ();
pending_engine = switchTo;
Log.DebugFormat ("Switching engine to: {0}", switchTo.GetType ());
return true;
}
return false;
}
public void Close ()
{
Close (false);
}
public void Close (bool fullShutdown)
{
IncrementLastPlayed ();
active_engine.Close (fullShutdown);
}
public void Play ()
{
if (CurrentState == PlayerState.Idle) {
OnPlayWhenIdleRequest ();
} else {
active_engine.Play ();
}
}
public void Pause ()
{
if (!CanPause) {
Close ();
} else {
active_engine.Pause ();
}
}
// For use by RadioTrackInfo
// TODO remove this method once RadioTrackInfo playlist downloading/parsing logic moved here?
internal void StartSynthesizeContacting (TrackInfo track)
{
//OnStateChanged (PlayerState.Contacting);
RaiseEvent (new PlayerEventStateChangeArgs (CurrentState, PlayerState.Contacting));
synthesized_contacting_track = track;
}
internal void EndSynthesizeContacting (TrackInfo track, bool idle)
{
if (track == synthesized_contacting_track) {
synthesized_contacting_track = null;
if (idle) {
RaiseEvent (new PlayerEventStateChangeArgs (PlayerState.Contacting, PlayerState.Idle));
}
}
}
public void TogglePlaying ()
{
if (IsPlaying () && CurrentState != PlayerState.Paused) {
Pause ();
} else if (CurrentState != PlayerState.NotReady) {
Play ();
}
}
public void VideoExpose (IntPtr displayContext, bool direct)
{
active_engine.VideoExpose (displayContext, direct);
}
public void VideoWindowRealize (IntPtr displayContext)
{
active_engine.VideoWindowRealize (displayContext);
}
public IntPtr VideoDisplayContext {
set { active_engine.VideoDisplayContext = value; }
get { return active_engine.VideoDisplayContext; }
}
public void TrackInfoUpdated ()
{
active_engine.TrackInfoUpdated ();
}
public bool IsPlaying (TrackInfo track)
{
return IsPlaying () && track != null && track.TrackEqual (CurrentTrack);
}
public bool IsPlaying ()
{
return CurrentState == PlayerState.Playing ||
CurrentState == PlayerState.Paused ||
CurrentState == PlayerState.Loaded ||
CurrentState == PlayerState.Loading ||
CurrentState == PlayerState.Contacting;
}
public string GetSubtitleDescription (int index)
{
return active_engine.GetSubtitleDescription (index);
}
private void CheckPending ()
{
if (pending_engine != null && pending_engine != active_engine) {
if (active_engine.CurrentState == PlayerState.Idle) {
Close ();
}
active_engine = pending_engine;
pending_engine = null;
}
}
public TrackInfo CurrentTrack {
get {
return active_engine == null ? null : active_engine.CurrentTrack ?? synthesized_contacting_track;
}
}
private Dictionary<string, object> dbus_sucks;
IDictionary<string, object> IPlayerEngineService.CurrentTrack {
get {
// FIXME: Managed DBus sucks - it explodes if you transport null
// or even an empty dictionary (a{sv} in our case). Piece of shit.
if (dbus_sucks == null) {
dbus_sucks = new Dictionary<string, object> ();
dbus_sucks.Add (String.Empty, String.Empty);
}
return CurrentTrack == null ? dbus_sucks : CurrentTrack.GenerateExportable ();
}
}
public SafeUri CurrentSafeUri {
get { return active_engine.CurrentUri; }
}
string IPlayerEngineService.CurrentUri {
get { return CurrentSafeUri == null ? String.Empty : CurrentSafeUri.AbsoluteUri; }
}
public PlayerState CurrentState {
get { return synthesized_contacting_track != null ? PlayerState.Contacting : active_engine.CurrentState; }
}
string IPlayerEngineService.CurrentState {
get { return CurrentState.ToString ().ToLower (); }
}
public PlayerState LastState {
get { return active_engine.LastState; }
}
string IPlayerEngineService.LastState {
get { return LastState.ToString ().ToLower (); }
}
public ushort Volume {
get { return active_engine.Volume; }
set {
foreach (PlayerEngine engine in engines) {
engine.Volume = value;
}
}
}
public uint Position {
get { return active_engine.Position; }
set { active_engine.Position = value; }
}
public byte Rating {
get { return (byte)(CurrentTrack == null ? 0 : CurrentTrack.Rating); }
set {
if (CurrentTrack != null) {
CurrentTrack.Rating = (int)Math.Min (5u, value);
CurrentTrack.Save ();
}
}
}
public bool CanSeek {
get { return active_engine.CanSeek; }
}
public bool CanPause {
get { return CurrentTrack != null && !CurrentTrack.IsLive; }
}
public bool SupportsEqualizer {
get { return ((active_engine is IEqualizer) && active_engine.SupportsEqualizer); }
}
public int SubtitleCount {
get { return active_engine.SubtitleCount; }
}
public int SubtitleIndex {
set { active_engine.SubtitleIndex = value; }
}
public SafeUri SubtitleUri {
set { active_engine.SubtitleUri = value; }
get { return active_engine.SubtitleUri; }
}
public VideoDisplayContextType VideoDisplayContextType {
get { return active_engine.VideoDisplayContextType; }
}
public uint Length {
get {
uint length = active_engine.Length;
if (length > 0) {
return length;
} else if (CurrentTrack == null) {
return 0;
}
return (uint) CurrentTrack.Duration.TotalSeconds;
}
}
public PlayerEngine ActiveEngine {
get { return active_engine; }
set { pending_engine = value; }
}
public PlayerEngine DefaultEngine {
get { return default_engine; }
set {
if (engines.Contains (value)) {
engines.Remove (value);
}
engines.Insert (0, value);
default_engine = value;
EngineSchema.Set (value.Id);
}
}
public IEnumerable<PlayerEngine> Engines {
get { return engines; }
}
#region Player Event System
private LinkedList<PlayerEventHandlerSlot> event_handlers = new LinkedList<PlayerEventHandlerSlot> ();
private struct PlayerEventHandlerSlot
{
public PlayerEvent EventMask;
public PlayerEventHandler Handler;
public PlayerEventHandlerSlot (PlayerEvent mask, PlayerEventHandler handler)
{
EventMask = mask;
Handler = handler;
}
}
private const PlayerEvent event_all_mask = PlayerEvent.Iterate
| PlayerEvent.StateChange
| PlayerEvent.StartOfStream
| PlayerEvent.EndOfStream
| PlayerEvent.Buffering
| PlayerEvent.Seek
| PlayerEvent.Error
| PlayerEvent.Volume
| PlayerEvent.Metadata
| PlayerEvent.TrackInfoUpdated
| PlayerEvent.RequestNextTrack
| PlayerEvent.PrepareVideoWindow;
private const PlayerEvent event_default_mask = event_all_mask & ~PlayerEvent.Iterate;
private static void VerifyEventMask (PlayerEvent eventMask)
{
if (eventMask <= PlayerEvent.None || eventMask > event_all_mask) {
throw new ArgumentOutOfRangeException ("eventMask", "A valid event mask must be provided");
}
}
public void ConnectEvent (PlayerEventHandler handler)
{
ConnectEvent (handler, event_default_mask, false);
}
public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask)
{
ConnectEvent (handler, eventMask, false);
}
public void ConnectEvent (PlayerEventHandler handler, bool connectAfter)
{
ConnectEvent (handler, event_default_mask, connectAfter);
}
public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask, bool connectAfter)
{
lock (event_handlers) {
VerifyEventMask (eventMask);
PlayerEventHandlerSlot slot = new PlayerEventHandlerSlot (eventMask, handler);
if (connectAfter) {
event_handlers.AddLast (slot);
} else {
event_handlers.AddFirst (slot);
}
}
}
private LinkedListNode<PlayerEventHandlerSlot> FindEventNode (PlayerEventHandler handler)
{
LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First;
while (node != null) {
if (node.Value.Handler == handler) {
return node;
}
node = node.Next;
}
return null;
}
public void DisconnectEvent (PlayerEventHandler handler)
{
lock (event_handlers) {
LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler);
if (node != null) {
event_handlers.Remove (node);
}
}
}
public void ModifyEvent (PlayerEvent eventMask, PlayerEventHandler handler)
{
lock (event_handlers) {
VerifyEventMask (eventMask);
LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler);
if (node != null) {
PlayerEventHandlerSlot slot = node.Value;
slot.EventMask = eventMask;
node.Value = slot;
}
}
}
private void RaiseEvent (PlayerEventArgs args)
{
lock (event_handlers) {
if (args.Event == PlayerEvent.StateChange && args is PlayerEventStateChangeArgs) {
HandleStateChange ((PlayerEventStateChangeArgs)args);
}
LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First;
while (node != null) {
if ((node.Value.EventMask & args.Event) == args.Event) {
try {
node.Value.Handler (args);
} catch (Exception e) {
Log.Exception (String.Format ("Error running PlayerEngine handler for {0}", args.Event), e);
}
}
node = node.Next;
}
}
}
#endregion
string IService.ServiceName {
get { return "PlayerEngine"; }
}
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
public static readonly SchemaEntry<int> VolumeSchema = new SchemaEntry<int> (
"player_engine", "volume",
80,
"Volume",
"Volume of playback relative to mixer output"
);
public static readonly SchemaEntry<string> EngineSchema = new SchemaEntry<string> (
"player_engine", "backend",
"helix-remote",
"Backend",
"Name of media playback engine backend"
);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
namespace System.Data.Common
{
[TypeConverter(typeof(DataColumnMappingConverter))]
public sealed class DataColumnMapping : MarshalByRefObject, IColumnMapping, ICloneable
{
private DataColumnMappingCollection _parent;
private string _dataSetColumnName;
private string _sourceColumnName;
public DataColumnMapping()
{
}
public DataColumnMapping(string sourceColumn, string dataSetColumn)
{
SourceColumn = sourceColumn;
DataSetColumn = dataSetColumn;
}
[DefaultValue("")]
public string DataSetColumn
{
get { return _dataSetColumnName ?? string.Empty; }
set { _dataSetColumnName = value; }
}
internal DataColumnMappingCollection Parent
{
get
{
return _parent;
}
set
{
_parent = value;
}
}
[DefaultValue("")]
public string SourceColumn
{
get { return _sourceColumnName ?? string.Empty; }
set
{
if ((null != Parent) && (0 != ADP.SrcCompare(_sourceColumnName, value)))
{
Parent.ValidateSourceColumn(-1, value);
}
_sourceColumnName = value;
}
}
object ICloneable.Clone()
{
DataColumnMapping clone = new DataColumnMapping();
clone._sourceColumnName = _sourceColumnName;
clone._dataSetColumnName = _dataSetColumnName;
return clone;
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public DataColumn GetDataColumnBySchemaAction(DataTable dataTable, Type dataType, MissingSchemaAction schemaAction)
{
return GetDataColumnBySchemaAction(SourceColumn, DataSetColumn, dataTable, dataType, schemaAction);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static DataColumn GetDataColumnBySchemaAction(string sourceColumn, string dataSetColumn, DataTable dataTable, Type dataType, MissingSchemaAction schemaAction)
{
if (null == dataTable)
{
throw ADP.ArgumentNull(nameof(dataTable));
}
if (string.IsNullOrEmpty(dataSetColumn))
{
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning)
{
Debug.WriteLine("explicit filtering of SourceColumn \"" + sourceColumn + "\"");
}
#endif
return null;
}
DataColumnCollection columns = dataTable.Columns;
Debug.Assert(null != columns, "GetDataColumnBySchemaAction: unexpected null DataColumnCollection");
int index = columns.IndexOf(dataSetColumn);
if ((0 <= index) && (index < columns.Count))
{
DataColumn dataColumn = columns[index];
Debug.Assert(null != dataColumn, "GetDataColumnBySchemaAction: unexpected null dataColumn");
if (!string.IsNullOrEmpty(dataColumn.Expression))
{
#if DEBUG
if (AdapterSwitches.DataSchema.TraceError)
{
Debug.WriteLine("schema mismatch on DataColumn \"" + dataSetColumn + "\" which is a computed column");
}
#endif
throw ADP.ColumnSchemaExpression(sourceColumn, dataSetColumn);
}
if ((null == dataType) || (dataType.IsArray == dataColumn.DataType.IsArray))
{
#if DEBUG
if (AdapterSwitches.DataSchema.TraceInfo)
{
Debug.WriteLine("schema match on DataColumn \"" + dataSetColumn + "\"");
}
#endif
return dataColumn;
}
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning)
{
Debug.WriteLine("schema mismatch on DataColumn \"" + dataSetColumn + "\" " + dataType.Name + " != " + dataColumn.DataType.Name);
}
#endif
throw ADP.ColumnSchemaMismatch(sourceColumn, dataType, dataColumn);
}
return CreateDataColumnBySchemaAction(sourceColumn, dataSetColumn, dataTable, dataType, schemaAction);
}
internal static DataColumn CreateDataColumnBySchemaAction(string sourceColumn, string dataSetColumn, DataTable dataTable, Type dataType, MissingSchemaAction schemaAction)
{
Debug.Assert(dataTable != null, "Should not call with a null DataTable");
if (string.IsNullOrEmpty(dataSetColumn))
{
return null;
}
switch (schemaAction)
{
case MissingSchemaAction.Add:
case MissingSchemaAction.AddWithKey:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceInfo)
{
Debug.WriteLine("schema add of DataColumn \"" + dataSetColumn + "\" <" + Convert.ToString(dataType, CultureInfo.InvariantCulture) + ">");
}
#endif
return new DataColumn(dataSetColumn, dataType);
case MissingSchemaAction.Ignore:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning)
{
Debug.WriteLine("schema filter of DataColumn \"" + dataSetColumn + "\" <" + Convert.ToString(dataType, CultureInfo.InvariantCulture) + ">");
}
#endif
return null;
case MissingSchemaAction.Error:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceError)
{
Debug.WriteLine("schema error on DataColumn \"" + dataSetColumn + "\" <" + Convert.ToString(dataType, CultureInfo.InvariantCulture) + ">");
}
#endif
throw ADP.ColumnSchemaMissing(dataSetColumn, dataTable.TableName, sourceColumn);
}
throw ADP.InvalidMissingSchemaAction(schemaAction);
}
public override string ToString()
{
return SourceColumn;
}
internal sealed class DataColumnMappingConverter : System.ComponentModel.ExpandableObjectConverter
{
// converter classes should have public ctor
public DataColumnMappingConverter()
{
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (typeof(InstanceDescriptor) == destinationType)
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (null == destinationType)
{
throw ADP.ArgumentNull(nameof(destinationType));
}
if ((typeof(InstanceDescriptor) == destinationType) && (value is DataColumnMapping))
{
DataColumnMapping mapping = (DataColumnMapping)value;
object[] values = new object[] { mapping.SourceColumn, mapping.DataSetColumn };
Type[] types = new Type[] { typeof(string), typeof(string) };
ConstructorInfo ctor = typeof(DataColumnMapping).GetConstructor(types);
return new InstanceDescriptor(ctor, values);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
struct Range {
public uint Start;
public uint Length;
public Range (uint index, uint length)
{
this.Start = index;
this.Length = length;
}
}
sealed class MetadataSystem {
internal AssemblyNameReference [] AssemblyReferences;
internal ModuleReference [] ModuleReferences;
internal TypeDefinition [] Types;
internal TypeReference [] TypeReferences;
internal FieldDefinition [] Fields;
internal MethodDefinition [] Methods;
internal MemberReference [] MemberReferences;
internal Dictionary<uint, uint []> NestedTypes;
internal Dictionary<uint, uint> ReverseNestedTypes;
internal Dictionary<uint, MetadataToken []> Interfaces;
internal Dictionary<uint, Row<ushort, uint>> ClassLayouts;
internal Dictionary<uint, uint> FieldLayouts;
internal Dictionary<uint, uint> FieldRVAs;
internal Dictionary<MetadataToken, uint> FieldMarshals;
internal Dictionary<MetadataToken, Row<ElementType, uint>> Constants;
internal Dictionary<uint, MetadataToken []> Overrides;
internal Dictionary<MetadataToken, Range []> CustomAttributes;
internal Dictionary<MetadataToken, Range []> SecurityDeclarations;
internal Dictionary<uint, Range> Events;
internal Dictionary<uint, Range> Properties;
internal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics;
internal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes;
internal Dictionary<MetadataToken, Range []> GenericParameters;
internal Dictionary<uint, MetadataToken []> GenericConstraints;
static Dictionary<string, Row<ElementType, bool>> primitive_value_types;
static void InitializePrimitives ()
{
primitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18, StringComparer.Ordinal) {
{ "Void", new Row<ElementType, bool> (ElementType.Void, false) },
{ "Boolean", new Row<ElementType, bool> (ElementType.Boolean, true) },
{ "Char", new Row<ElementType, bool> (ElementType.Char, true) },
{ "SByte", new Row<ElementType, bool> (ElementType.I1, true) },
{ "Byte", new Row<ElementType, bool> (ElementType.U1, true) },
{ "Int16", new Row<ElementType, bool> (ElementType.I2, true) },
{ "UInt16", new Row<ElementType, bool> (ElementType.U2, true) },
{ "Int32", new Row<ElementType, bool> (ElementType.I4, true) },
{ "UInt32", new Row<ElementType, bool> (ElementType.U4, true) },
{ "Int64", new Row<ElementType, bool> (ElementType.I8, true) },
{ "UInt64", new Row<ElementType, bool> (ElementType.U8, true) },
{ "Single", new Row<ElementType, bool> (ElementType.R4, true) },
{ "Double", new Row<ElementType, bool> (ElementType.R8, true) },
{ "String", new Row<ElementType, bool> (ElementType.String, false) },
{ "TypedReference", new Row<ElementType, bool> (ElementType.TypedByRef, false) },
{ "IntPtr", new Row<ElementType, bool> (ElementType.I, true) },
{ "UIntPtr", new Row<ElementType, bool> (ElementType.U, true) },
{ "Object", new Row<ElementType, bool> (ElementType.Object, false) },
};
}
public static void TryProcessPrimitiveTypeReference (TypeReference type)
{
if (type.Namespace != "System")
return;
var scope = type.scope;
if (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference)
return;
Row<ElementType, bool> primitive_data;
if (!TryGetPrimitiveData (type, out primitive_data))
return;
type.etype = primitive_data.Col1;
type.IsValueType = primitive_data.Col2;
}
public static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype)
{
etype = ElementType.None;
if (type.Namespace != "System")
return false;
Row<ElementType, bool> primitive_data;
if (TryGetPrimitiveData (type, out primitive_data) && primitive_data.Col1.IsPrimitive ()) {
etype = primitive_data.Col1;
return true;
}
return false;
}
static bool TryGetPrimitiveData (TypeReference type, out Row<ElementType, bool> primitive_data)
{
if (primitive_value_types == null)
InitializePrimitives ();
return primitive_value_types.TryGetValue (type.Name, out primitive_data);
}
public void Clear ()
{
if (NestedTypes != null) NestedTypes.Clear ();
if (ReverseNestedTypes != null) ReverseNestedTypes.Clear ();
if (Interfaces != null) Interfaces.Clear ();
if (ClassLayouts != null) ClassLayouts.Clear ();
if (FieldLayouts != null) FieldLayouts.Clear ();
if (FieldRVAs != null) FieldRVAs.Clear ();
if (FieldMarshals != null) FieldMarshals.Clear ();
if (Constants != null) Constants.Clear ();
if (Overrides != null) Overrides.Clear ();
if (CustomAttributes != null) CustomAttributes.Clear ();
if (SecurityDeclarations != null) SecurityDeclarations.Clear ();
if (Events != null) Events.Clear ();
if (Properties != null) Properties.Clear ();
if (Semantics != null) Semantics.Clear ();
if (PInvokes != null) PInvokes.Clear ();
if (GenericParameters != null) GenericParameters.Clear ();
if (GenericConstraints != null) GenericConstraints.Clear ();
}
public TypeDefinition GetTypeDefinition (uint rid)
{
if (rid < 1 || rid > Types.Length)
return null;
return Types [rid - 1];
}
public void AddTypeDefinition (TypeDefinition type)
{
Types [type.token.RID - 1] = type;
}
public TypeReference GetTypeReference (uint rid)
{
if (rid < 1 || rid > TypeReferences.Length)
return null;
return TypeReferences [rid - 1];
}
public void AddTypeReference (TypeReference type)
{
TypeReferences [type.token.RID - 1] = type;
}
public FieldDefinition GetFieldDefinition (uint rid)
{
if (rid < 1 || rid > Fields.Length)
return null;
return Fields [rid - 1];
}
public void AddFieldDefinition (FieldDefinition field)
{
Fields [field.token.RID - 1] = field;
}
public MethodDefinition GetMethodDefinition (uint rid)
{
if (rid < 1 || rid > Methods.Length)
return null;
return Methods [rid - 1];
}
public void AddMethodDefinition (MethodDefinition method)
{
Methods [method.token.RID - 1] = method;
}
public MemberReference GetMemberReference (uint rid)
{
if (rid < 1 || rid > MemberReferences.Length)
return null;
return MemberReferences [rid - 1];
}
public void AddMemberReference (MemberReference member)
{
MemberReferences [member.token.RID - 1] = member;
}
public bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping)
{
return NestedTypes.TryGetValue (type.token.RID, out mapping);
}
public void SetNestedTypeMapping (uint type_rid, uint [] mapping)
{
NestedTypes [type_rid] = mapping;
}
public void RemoveNestedTypeMapping (TypeDefinition type)
{
NestedTypes.Remove (type.token.RID);
}
public bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring)
{
return ReverseNestedTypes.TryGetValue (type.token.RID, out declaring);
}
public void SetReverseNestedTypeMapping (uint nested, uint declaring)
{
ReverseNestedTypes [nested] = declaring;
}
public void RemoveReverseNestedTypeMapping (TypeDefinition type)
{
ReverseNestedTypes.Remove (type.token.RID);
}
public bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping)
{
return Interfaces.TryGetValue (type.token.RID, out mapping);
}
public void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping)
{
Interfaces [type_rid] = mapping;
}
public void RemoveInterfaceMapping (TypeDefinition type)
{
Interfaces.Remove (type.token.RID);
}
public void AddPropertiesRange (uint type_rid, Range range)
{
Properties.Add (type_rid, range);
}
public bool TryGetPropertiesRange (TypeDefinition type, out Range range)
{
return Properties.TryGetValue (type.token.RID, out range);
}
public void RemovePropertiesRange (TypeDefinition type)
{
Properties.Remove (type.token.RID);
}
public void AddEventsRange (uint type_rid, Range range)
{
Events.Add (type_rid, range);
}
public bool TryGetEventsRange (TypeDefinition type, out Range range)
{
return Events.TryGetValue (type.token.RID, out range);
}
public void RemoveEventsRange (TypeDefinition type)
{
Events.Remove (type.token.RID);
}
public bool TryGetGenericParameterRanges (IGenericParameterProvider owner, out Range [] ranges)
{
return GenericParameters.TryGetValue (owner.MetadataToken, out ranges);
}
public void RemoveGenericParameterRange (IGenericParameterProvider owner)
{
GenericParameters.Remove (owner.MetadataToken);
}
public bool TryGetCustomAttributeRanges (ICustomAttributeProvider owner, out Range [] ranges)
{
return CustomAttributes.TryGetValue (owner.MetadataToken, out ranges);
}
public void RemoveCustomAttributeRange (ICustomAttributeProvider owner)
{
CustomAttributes.Remove (owner.MetadataToken);
}
public bool TryGetSecurityDeclarationRanges (ISecurityDeclarationProvider owner, out Range [] ranges)
{
return SecurityDeclarations.TryGetValue (owner.MetadataToken, out ranges);
}
public void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner)
{
SecurityDeclarations.Remove (owner.MetadataToken);
}
public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping)
{
return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping);
}
public void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping)
{
GenericConstraints [gp_rid] = mapping;
}
public void RemoveGenericConstraintMapping (GenericParameter generic_parameter)
{
GenericConstraints.Remove (generic_parameter.token.RID);
}
public bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping)
{
return Overrides.TryGetValue (method.token.RID, out mapping);
}
public void SetOverrideMapping (uint rid, MetadataToken [] mapping)
{
Overrides [rid] = mapping;
}
public void RemoveOverrideMapping (MethodDefinition method)
{
Overrides.Remove (method.token.RID);
}
public TypeDefinition GetFieldDeclaringType (uint field_rid)
{
return BinaryRangeSearch (Types, field_rid, true);
}
public TypeDefinition GetMethodDeclaringType (uint method_rid)
{
return BinaryRangeSearch (Types, method_rid, false);
}
static TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field)
{
int min = 0;
int max = types.Length - 1;
while (min <= max) {
int mid = min + ((max - min) / 2);
var type = types [mid];
var range = field ? type.fields_range : type.methods_range;
if (rid < range.Start)
max = mid - 1;
else if (rid >= range.Start + range.Length)
min = mid + 1;
else
return type;
}
return null;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Model
{
using System;
using NPOI.HSSF.Record;
using NPOI.HSSF.UserModel;
using NUnit.Framework;
using TestCases.HSSF;
using NPOI.SS.UserModel;
using NPOI.Util;
using System.Collections.Generic;
using System.Collections;
using NPOI.HSSF.Model;
using NPOI.SS.Formula.PTG;
/**
* Tests for {@link LinkTable}
*
* @author Josh Micich
*/
[TestFixture]
public class TestLinkTable
{
/**
* The example file attached to bugzilla 45046 is a clear example of Name records being present
* without an External Book (SupBook) record. Excel has no trouble Reading this file.<br/>
* TODO get OOO documentation updated to reflect this (that EXTERNALBOOK is optional).
*
* It's not clear what exact steps need to be taken in Excel to create such a workbook
*/
[Test]
public void TestLinkTableWithoutExternalBookRecord_bug45046()
{
HSSFWorkbook wb;
try
{
wb = HSSFTestDataSamples.OpenSampleWorkbook("ex45046-21984.xls");
}
catch (Exception e)
{
if ("DEFINEDNAME is part of LinkTable".Equals(e.Message))
{
throw new AssertionException("Identified bug 45046 b");
}
throw e;
}
// some other sanity Checks
Assert.AreEqual(3, wb.NumberOfSheets);
String formula = wb.GetSheetAt(0).GetRow(4).GetCell(13).CellFormula;
if ("ipcSummenproduktIntern($P5,N$6,$A$9,N$5)".Equals(formula))
{
// The reported symptom of this bugzilla is an earlier bug (already fixed)
throw new AssertionException("Identified bug 41726");
// This is observable in version 3.0
}
Assert.AreEqual("ipcSummenproduktIntern($C5,N$2,$A$9,N$1)", formula);
}
[Test]
public void TestMultipleExternSheetRecords_bug45698()
{
HSSFWorkbook wb;
try
{
wb = HSSFTestDataSamples.OpenSampleWorkbook("ex45698-22488.xls");
}
catch (Exception e)
{
if ("Extern sheet is part of LinkTable".Equals(e.Message))
{
throw new AssertionException("Identified bug 45698");
}
throw e;
}
// some other sanity Checks
Assert.AreEqual(7, wb.NumberOfSheets);
}
[Test]
public void TestExtraSheetRefs_bug45978()
{
HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("ex45978-extraLinkTableSheets.xls");
/*
ex45978-extraLinkTableSheets.xls is a cut-down version of attachment 22561.
The original file produces the same error.
This bug was caused by a combination of invalid sheet indexes in the EXTERNSHEET
record, and eager Initialisation of the extern sheet references. Note - the workbook
has 2 sheets, but the EXTERNSHEET record refers to sheet indexes 0, 1 and 2.
Offset 0x3954 (14676)
recordid = 0x17, size = 32
[EXTERNSHEET]
numOfRefs = 5
refrec #0: extBook=0 firstSheet=0 lastSheet=0
refrec #1: extBook=1 firstSheet=2 lastSheet=2
refrec #2: extBook=2 firstSheet=1 lastSheet=1
refrec #3: extBook=0 firstSheet=-1 lastSheet=-1
refrec #4: extBook=0 firstSheet=1 lastSheet=1
[/EXTERNSHEET]
As it turns out, the formula in question doesn't even use externSheetIndex #1 - it
uses #4, which Resolves to sheetIndex 1 -> 'Data'.
It is not clear exactly what externSheetIndex #4 would refer to. Excel seems to
display such a formula as "''!$A2", but then complains of broken link errors.
*/
ICell cell = wb.GetSheetAt(0).GetRow(1).GetCell(1);
String cellFormula;
try
{
cellFormula = cell.CellFormula;
}
catch (IndexOutOfRangeException e)
{
if (e.Message.Equals("Index: 2, Size: 2"))
{
throw new AssertionException("Identified bug 45798");
}
throw e;
}
Assert.AreEqual("Data!$A2", cellFormula);
}
/**
* This problem was visible in POI svn r763332
* when Reading the workbook of attachment 23468 from bugzilla 47001
*/
[Test]
public void TestMissingExternSheetRecord_bug47001b()
{
Record[] recs = {
SupBookRecord.CreateAddInFunctions(),
new SSTRecord(),
};
List<Record> recList = new List<Record>(recs);
WorkbookRecordList wrl = new WorkbookRecordList();
LinkTable lt;
try
{
lt = new LinkTable(recList, 0, wrl, new Dictionary<String, NameCommentRecord>());
}
catch (Exception e)
{
if (e.Message.Equals("Expected an EXTERNSHEET record but got (NPOI.HSSF.record.SSTRecord)"))
{
throw new AssertionException("Identified bug 47001b");
}
throw e;
}
Assert.IsNotNull(lt);
}
[Test]
public void TestNameCommentRecordBetweenNameRecords()
{
Record[] recs = {
new NameRecord(),
new NameCommentRecord("name1", "comment1"),
new NameRecord(),
new NameCommentRecord("name2", "comment2"),
};
List<Record> recList = new List<Record>(recs);
WorkbookRecordList wrl = new WorkbookRecordList();
Dictionary<String, NameCommentRecord> commentRecords = new Dictionary<String, NameCommentRecord>();
LinkTable lt = new LinkTable(recList, 0, wrl, commentRecords);
Assert.IsNotNull(lt);
Assert.AreEqual(2, commentRecords.Count);
Assert.IsTrue(recs[1] == commentRecords["name1"]); //== is intentionally not .Equals()!
Assert.IsTrue(recs[3] == commentRecords["name2"]); //== is intentionally not .Equals()!
Assert.AreEqual(2, lt.NumNames);
}
[Test]
public void TestAddNameX()
{
WorkbookRecordList wrl = new WorkbookRecordList();
wrl.Add(0, new BOFRecord());
wrl.Add(1, new CountryRecord());
wrl.Add(2, EOFRecord.instance);
int numberOfSheets = 3;
LinkTable tbl = new LinkTable(numberOfSheets, wrl);
// creation of a new LinkTable insert two new records: SupBookRecord followed by ExternSheetRecord
// assure they are in place:
// [BOFRecord]
// [CountryRecord]
// [SUPBOOK Internal References nSheets= 3]
// [EXTERNSHEET]
// [EOFRecord]
Assert.AreEqual(5, wrl.Records.Count);
Assert.IsTrue(wrl[(2)] is SupBookRecord);
SupBookRecord sup1 = (SupBookRecord)wrl[(2)];
Assert.AreEqual(numberOfSheets, sup1.NumberOfSheets);
Assert.IsTrue(wrl[(3)] is ExternSheetRecord);
ExternSheetRecord extSheet = (ExternSheetRecord)wrl[(3)];
Assert.AreEqual(0, extSheet.NumOfRefs);
Assert.IsNull(tbl.GetNameXPtg("ISODD", -1));
Assert.AreEqual(5, wrl.Records.Count); //still have five records
NameXPtg namex1 = tbl.AddNameXPtg("ISODD"); // Adds two new rercords
Assert.AreEqual(0, namex1.SheetRefIndex);
Assert.AreEqual(0, namex1.NameIndex);
Assert.AreEqual(namex1.ToString(), tbl.GetNameXPtg("ISODD", -1).ToString());
// Can only find on the right sheet ref, if restricting
Assert.AreEqual(namex1.ToString(), tbl.GetNameXPtg("ISODD", 0).ToString());
Assert.IsNull(tbl.GetNameXPtg("ISODD", 1));
Assert.IsNull(tbl.GetNameXPtg("ISODD", 2));
// assure they are in place:
// [BOFRecord]
// [CountryRecord]
// [SUPBOOK Internal References nSheets= 3]
// [SUPBOOK Add-In Functions nSheets= 1]
// [EXTERNALNAME .name = ISODD]
// [EXTERNSHEET]
// [EOFRecord]
Assert.AreEqual(7, wrl.Records.Count);
Assert.IsTrue(wrl[(3)] is SupBookRecord);
SupBookRecord sup2 = (SupBookRecord)wrl[(3)];
Assert.IsTrue(sup2.IsAddInFunctions);
Assert.IsTrue(wrl[(4)] is ExternalNameRecord);
ExternalNameRecord ext1 = (ExternalNameRecord)wrl[(4)];
Assert.AreEqual("ISODD", ext1.Text);
Assert.IsTrue(wrl[(5)] is ExternSheetRecord);
Assert.AreEqual(1, extSheet.NumOfRefs);
//check that
Assert.AreEqual(0, tbl.ResolveNameXIx(namex1.SheetRefIndex, namex1.NameIndex));
Assert.AreEqual("ISODD", tbl.ResolveNameXText(namex1.SheetRefIndex, namex1.NameIndex, null));
Assert.IsNull(tbl.GetNameXPtg("ISEVEN", -1));
NameXPtg namex2 = tbl.AddNameXPtg("ISEVEN"); // Adds two new rercords
Assert.AreEqual(0, namex2.SheetRefIndex);
Assert.AreEqual(1, namex2.NameIndex); // name index increased by one
Assert.AreEqual(namex2.ToString(), tbl.GetNameXPtg("ISEVEN", -1).ToString());
Assert.AreEqual(8, wrl.Records.Count);
// assure they are in place:
// [BOFRecord]
// [CountryRecord]
// [SUPBOOK Internal References nSheets= 3]
// [SUPBOOK Add-In Functions nSheets= 1]
// [EXTERNALNAME .name = ISODD]
// [EXTERNALNAME .name = ISEVEN]
// [EXTERNSHEET]
// [EOFRecord]
Assert.IsTrue(wrl[(3)] is SupBookRecord);
Assert.IsTrue(wrl[(4)] is ExternalNameRecord);
Assert.IsTrue(wrl[(5)] is ExternalNameRecord);
Assert.AreEqual("ISODD", ((ExternalNameRecord)wrl[(4)]).Text);
Assert.AreEqual("ISEVEN", ((ExternalNameRecord)wrl[(5)]).Text);
Assert.IsTrue(wrl[(6)] is ExternSheetRecord);
Assert.IsTrue(wrl[(7)] is EOFRecord);
Assert.AreEqual(0, tbl.ResolveNameXIx(namex2.SheetRefIndex, namex2.NameIndex));
Assert.AreEqual("ISEVEN", tbl.ResolveNameXText(namex2.SheetRefIndex, namex2.NameIndex, null));
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
#endregion
namespace Pickture
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
#region Properties
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup
{
get { return isPopup; }
protected set { isPopup = value; }
}
bool isPopup = false;
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return transitionOnTime; }
protected set { transitionOnTime = value; }
}
TimeSpan transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return transitionOffTime; }
protected set { transitionOffTime = value; }
}
TimeSpan transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition
{
get { return transitionPosition; }
protected set { transitionPosition = value; }
}
float transitionPosition = 1;
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 255 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public byte TransitionAlpha
{
get { return (byte)(255 - TransitionPosition * 255); }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return screenState; }
protected set { screenState = value; }
}
ScreenState screenState = ScreenState.TransitionOn;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return isExiting; }
protected internal set { isExiting = value; }
}
bool isExiting = false;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !otherScreenHasFocus &&
(screenState == ScreenState.TransitionOn ||
screenState == ScreenState.Active);
}
}
bool otherScreenHasFocus;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ScreenManager ScreenManager
{
get { return screenManager; }
internal set { screenManager = value; }
}
ScreenManager screenManager;
#endregion
#region Initialization
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public virtual void LoadContent() { }
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent() { }
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
this.otherScreenHasFocus = otherScreenHasFocus;
if (isExiting)
{
// If the screen is going away to die, it should transition off.
screenState = ScreenState.TransitionOff;
if (!UpdateTransition(gameTime, transitionOffTime, 1))
{
// When the transition finishes, remove the screen.
ScreenManager.RemoveScreen(this);
}
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
if (UpdateTransition(gameTime, transitionOffTime, 1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOff;
}
else
{
// Transition finished!
screenState = ScreenState.Hidden;
}
}
else
{
// Otherwise the screen should transition on and become active.
if (UpdateTransition(gameTime, transitionOnTime, -1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOn;
}
else
{
// Transition finished!
screenState = ScreenState.Active;
}
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds /
time.TotalMilliseconds);
// Update the transition position.
transitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if ((transitionPosition <= 0) || (transitionPosition >= 1))
{
transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(InputState input) { }
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public virtual void Draw(GameTime gameTime) { }
#endregion
#region Public Methods
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
isExiting = true;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using Xunit.Abstractions;
using Tester;
using Orleans.Hosting;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers.Streams.AzureQueue;
using Tester.AzureUtils.Streaming;
namespace UnitTests.StreamingTests
{
[TestCategory("Streaming"), TestCategory("Limits")]
public class StreamLimitTests : TestClusterPerTest
{
public const string AzureQueueStreamProviderName = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
public const string SmsStreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
private static int MaxExpectedPerStream = 500;
private static int MaxConsumersPerStream;
private static int MaxProducersPerStream;
private const int MessagePipelineSize = 1000;
private const int InitPipelineSize = 500;
private IManagementGrain mgmtGrain;
private string StreamNamespace;
private readonly ITestOutputHelper output;
private const int queueCount = 8;
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
TestUtils.CheckForAzureStorage();
builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>();
}
private class SiloBuilderConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder
.AddSimpleMessageStreamProvider(SmsStreamProviderName)
.AddSimpleMessageStreamProvider("SMSProviderDoNotOptimizeForImmutableData", options => options.OptimizeForImmutableData = false)
.AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.DeleteStateOnClear = true;
}))
.AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.DeleteStateOnClear = true;
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
}))
.AddAzureQueueStreams<AzureQueueDataAdapterV2>(AzureQueueStreamProviderName, ob => ob.Configure<IOptions<ClusterOptions>>(
(options, dep) =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount);
}))
.AddAzureQueueStreams<AzureQueueDataAdapterV2>("AzureQueueProvider2", ob=>ob.Configure<IOptions<ClusterOptions>>(
(options, dep) =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.QueueNames = AzureQueueUtilities.GenerateQueueNames($"{dep.Value.ClusterId}2", queueCount);
}))
.AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1);
}
}
public StreamLimitTests(ITestOutputHelper output)
{
this.output = output;
StreamNamespace = StreamTestsConstants.StreamLifecycleTestsNamespace;
this.mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0);
}
public override void Dispose()
{
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance,
AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount),
TestDefaultConfiguration.DataConnectionString).Wait();
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance,
AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount),
TestDefaultConfiguration.DataConnectionString).Wait();
base.Dispose();
}
[SkippableFact]
public async Task SMS_Limits_FindMax_Consumers()
{
// 1 Stream, 1 Producer, X Consumers
Guid streamId = Guid.NewGuid();
string streamProviderName = SmsStreamProviderName;
output.WriteLine("Starting search for MaxConsumersPerStream value using stream {0}", streamId);
IStreamLifecycleProducerGrain producer = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, this.StreamNamespace, streamProviderName);
int loopCount = 0;
try
{
// Loop until something breaks!
for (loopCount = 1; loopCount <= MaxExpectedPerStream; loopCount++)
{
IStreamLifecycleConsumerGrain consumer = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, this.StreamNamespace, streamProviderName);
}
}
catch (Exception exc)
{
this.output.WriteLine("Stopping loop at loopCount={0} due to exception {1}", loopCount, exc);
}
MaxConsumersPerStream = loopCount - 1;
output.WriteLine("Finished search for MaxConsumersPerStream with value {0}", MaxConsumersPerStream);
Assert.NotEqual(0, MaxConsumersPerStream); // "MaxConsumersPerStream should be greater than zero."
output.WriteLine("MaxConsumersPerStream={0}", MaxConsumersPerStream);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_Limits_FindMax_Producers()
{
// 1 Stream, X Producers, 1 Consumer
Guid streamId = Guid.NewGuid();
string streamProviderName = SmsStreamProviderName;
output.WriteLine("Starting search for MaxProducersPerStream value using stream {0}", streamId);
IStreamLifecycleConsumerGrain consumer = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, this.StreamNamespace, streamProviderName);
int loopCount = 0;
try
{
// Loop until something breaks!
for (loopCount = 1; loopCount <= MaxExpectedPerStream; loopCount++)
{
IStreamLifecycleProducerGrain producer = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, this.StreamNamespace, streamProviderName);
}
}
catch (Exception exc)
{
this.output.WriteLine("Stopping loop at loopCount={0} due to exception {1}", loopCount, exc);
}
MaxProducersPerStream = loopCount - 1;
output.WriteLine("Finished search for MaxProducersPerStream with value {0}", MaxProducersPerStream);
Assert.NotEqual(0, MaxProducersPerStream); // "MaxProducersPerStream should be greater than zero."
output.WriteLine("MaxProducersPerStream={0}", MaxProducersPerStream);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_Limits_P1_C128_S1()
{
// 1 Stream, 1 Producer, 128 Consumers
await Test_Stream_Limits(
SmsStreamProviderName,
1, 1, 128);
}
[SkippableFact, TestCategory("Failures")]
public async Task SMS_Limits_P128_C1_S1()
{
// 1 Stream, 128 Producers, 1 Consumer
await Test_Stream_Limits(
SmsStreamProviderName,
1, 128, 1);
}
[SkippableFact, TestCategory("Failures")]
public async Task SMS_Limits_P128_C128_S1()
{
// 1 Stream, 128 Producers, 128 Consumers
await Test_Stream_Limits(
SmsStreamProviderName,
1, 128, 128);
}
[SkippableFact, TestCategory("Failures")]
public async Task SMS_Limits_P1_C400_S1()
{
// 1 Stream, 1 Producer, 400 Consumers
int numConsumers = 400;
await Test_Stream_Limits(
SmsStreamProviderName,
1, 1, numConsumers);
}
[SkippableFact, TestCategory("Burst")]
public async Task SMS_Limits_Max_Producers_Burst()
{
if (MaxProducersPerStream == 0) await SMS_Limits_FindMax_Producers();
output.WriteLine("Using MaxProducersPerStream={0}", MaxProducersPerStream);
// 1 Stream, Max Producers, 1 Consumer
await Test_Stream_Limits(
SmsStreamProviderName,
1, MaxProducersPerStream, 1, useFanOut: true);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_Limits_Max_Producers_NoBurst()
{
if (MaxProducersPerStream == 0) await SMS_Limits_FindMax_Producers();
output.WriteLine("Using MaxProducersPerStream={0}", MaxProducersPerStream);
// 1 Stream, Max Producers, 1 Consumer
await Test_Stream_Limits(
SmsStreamProviderName,
1, MaxProducersPerStream, 1, useFanOut: false);
}
[SkippableFact, TestCategory("Burst")]
public async Task SMS_Limits_Max_Consumers_Burst()
{
if (MaxConsumersPerStream == 0) await SMS_Limits_FindMax_Consumers();
output.WriteLine("Using MaxConsumersPerStream={0}", MaxConsumersPerStream);
// 1 Stream, Max Producers, 1 Consumer
await Test_Stream_Limits(
SmsStreamProviderName,
1, 1, MaxConsumersPerStream, useFanOut: true);
}
[SkippableFact]
public async Task SMS_Limits_Max_Consumers_NoBurst()
{
if (MaxConsumersPerStream == 0) await SMS_Limits_FindMax_Consumers();
output.WriteLine("Using MaxConsumersPerStream={0}", MaxConsumersPerStream);
// 1 Stream, Max Producers, 1 Consumer
await Test_Stream_Limits(
SmsStreamProviderName,
1, 1, MaxConsumersPerStream, useFanOut: false);
}
[SkippableFact, TestCategory("Failures"), TestCategory("Burst")]
public async Task SMS_Limits_P9_C9_S152_Burst()
{
// 152 * 9 ~= 1360 target per second
// 152 Streams, x9 Producers, x9 Consumers
int numStreams = 152;
await Test_Stream_Limits(
SmsStreamProviderName,
numStreams, 9, 9, useFanOut: true);
}
[SkippableFact, TestCategory("Failures")]
public async Task SMS_Limits_P9_C9_S152_NoBurst()
{
// 152 * 9 ~= 1360 target per second
// 152 Streams, x9 Producers, x9 Consumers
int numStreams = 152;
await Test_Stream_Limits(
SmsStreamProviderName,
numStreams, 9, 9, useFanOut: false);
}
[SkippableFact, TestCategory("Failures"), TestCategory("Burst")]
public async Task SMS_Limits_P1_C9_S152_Burst()
{
// 152 * 9 ~= 1360 target per second
// 152 Streams, x1 Producer, x9 Consumers
int numStreams = 152;
await Test_Stream_Limits(
SmsStreamProviderName,
numStreams, 1, 9, useFanOut: true);
}
[SkippableFact, TestCategory("Failures")]
public async Task SMS_Limits_P1_C9_S152_NoBurst()
{
// 152 * 9 ~= 1360 target per second
// 152 Streams, x1 Producer, x9 Consumers
int numStreams = 152;
await Test_Stream_Limits(
SmsStreamProviderName,
numStreams, 1, 9, useFanOut: false);
}
[SkippableFact(Skip = "Ignore"), TestCategory("Performance"), TestCategory("Burst")]
public async Task SMS_Churn_Subscribers_P0_C10_ManyStreams()
{
int numStreams = 2000;
int pipelineSize = 10000;
await Test_Stream_Churn_NumStreams(
SmsStreamProviderName,
pipelineSize,
numStreams,
numConsumers: 10,
numProducers: 0
);
}
//[SkippableFact, TestCategory("Performance"), TestCategory("Burst")]
//public async Task SMS_Churn_Subscribers_P1_C9_ManyStreams_TimePeriod()
//{
// await Test_Stream_Churn_TimePeriod(
// StreamReliabilityTests.SMS_STREAM_PROVIDER_NAME,
// InitPipelineSize,
// TimeSpan.FromSeconds(60),
// numProducers: 1
// );
//}
[SkippableFact, TestCategory("Performance"), TestCategory("Burst")]
public async Task SMS_Churn_FewPublishers_C9_ManyStreams()
{
int numProducers = 0;
int numStreams = 1000;
int pipelineSize = 100;
await Test_Stream_Churn_NumStreams_FewPublishers(
SmsStreamProviderName,
pipelineSize,
numStreams,
numProducers: numProducers,
warmUpPubSub: true
);
}
[SkippableFact, TestCategory("Performance"), TestCategory("Burst")]
public async Task SMS_Churn_FewPublishers_C9_ManyStreams_PubSubDirect()
{
int numProducers = 0;
int numStreams = 1000;
int pipelineSize = 100;
await Test_Stream_Churn_NumStreams_FewPublishers(
SmsStreamProviderName,
pipelineSize,
numStreams,
numProducers: numProducers,
warmUpPubSub: true,
normalSubscribeCalls: false
);
}
private Task Test_Stream_Churn_NumStreams_FewPublishers(
string streamProviderName,
int pipelineSize,
int numStreams,
int numConsumers = 9,
int numProducers = 4,
bool warmUpPubSub = true,
bool warmUpProducers = false,
bool normalSubscribeCalls = true)
{
output.WriteLine("Testing churn with {0} Streams on {1} Producers with {2} Consumers per Stream",
numStreams, numProducers, numConsumers);
AsyncPipeline pipeline = new AsyncPipeline(pipelineSize);
// Create streamId Guids
Guid[] streamIds = new Guid[numStreams];
for (int i = 0; i < numStreams; i++)
{
streamIds[i] = Guid.NewGuid();
}
int activeConsumerGrains = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain).FullName);
Assert.Equal(0, activeConsumerGrains); // "Initial Consumer count should be zero"
int activeProducerGrains = ActiveGrainCount(typeof(StreamLifecycleProducerGrain).FullName);
Assert.Equal(0, activeProducerGrains); // "Initial Producer count should be zero"
if (warmUpPubSub)
{
WarmUpPubSub(streamProviderName, streamIds, pipeline);
pipeline.Wait();
int activePubSubGrains = ActiveGrainCount(typeof(PubSubRendezvousGrain).FullName);
Assert.Equal(streamIds.Length, activePubSubGrains); // "Initial PubSub count -- should all be warmed up"
}
Guid[] producerIds = new Guid[numProducers];
if (numProducers > 0 && warmUpProducers)
{
// Warm up Producers to pre-create grains
for (int i = 0; i < numProducers; i++)
{
producerIds[i] = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(producerIds[i]);
Task promise = grain.Ping();
pipeline.Add(promise);
}
pipeline.Wait();
int activePublisherGrains = this.ActiveGrainCount(typeof(StreamLifecycleProducerGrain).FullName);
Assert.Equal(numProducers, activePublisherGrains); // "Initial Publisher count -- should all be warmed up"
}
var promises = new List<Task>();
Stopwatch sw = Stopwatch.StartNew();
if (numProducers > 0)
{
// Producers
for (int i = 0; i < numStreams; i++)
{
Guid streamId = streamIds[i];
Guid producerId = producerIds[i % numProducers];
var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(producerId);
Task promise = grain.BecomeProducer(streamId, this.StreamNamespace, streamProviderName);
promises.Add(promise);
pipeline.Add(promise);
}
pipeline.Wait();
promises.Clear();
}
// Consumers
for (int i = 0; i < numStreams; i++)
{
Guid streamId = streamIds[i];
Task promise = SetupOneStream(streamId, streamProviderName, pipeline, numConsumers, 0, normalSubscribeCalls);
promises.Add(promise);
}
pipeline.Wait();
Task.WhenAll(promises).Wait();
sw.Stop();
int consumerCount = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain).FullName);
Assert.Equal(activeConsumerGrains + (numStreams * numConsumers), consumerCount); // "The right number of Consumer grains are active"
int producerCount = ActiveGrainCount(typeof(StreamLifecycleProducerGrain).FullName);
Assert.Equal(activeProducerGrains + (numStreams * numProducers), producerCount); // "The right number of Producer grains are active"
int pubSubCount = ActiveGrainCount(typeof(PubSubRendezvousGrain).FullName);
Assert.Equal(streamIds.Length, pubSubCount); // "Final PubSub count -- no more started"
TimeSpan elapsed = sw.Elapsed;
int totalSubscriptions = numStreams * numConsumers;
double rps = totalSubscriptions / elapsed.TotalSeconds;
output.WriteLine("Subscriptions-per-second = {0} during period {1}", rps, elapsed);
Assert.NotEqual(0.0, rps); // "RPS greater than zero"
return Task.CompletedTask;
}
private Task Test_Stream_Churn_NumStreams(
string streamProviderName,
int pipelineSize,
int numStreams,
int numConsumers = 9,
int numProducers = 1,
bool warmUpPubSub = true,
bool normalSubscribeCalls = true)
{
output.WriteLine("Testing churn with {0} Streams with {1} Consumers and {2} Producers per Stream NormalSubscribe={3}",
numStreams, numConsumers, numProducers, normalSubscribeCalls);
AsyncPipeline pipeline = new AsyncPipeline(pipelineSize);
var promises = new List<Task>();
// Create streamId Guids
Guid[] streamIds = new Guid[numStreams];
for (int i = 0; i < numStreams; i++)
{
streamIds[i] = Guid.NewGuid();
}
if (warmUpPubSub)
{
WarmUpPubSub(streamProviderName, streamIds, pipeline);
pipeline.Wait();
int activePubSubGrains = ActiveGrainCount(typeof(PubSubRendezvousGrain).FullName);
Assert.Equal(streamIds.Length, activePubSubGrains); // "Initial PubSub count -- should all be warmed up"
}
int activeConsumerGrains = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain).FullName);
Assert.Equal(0, activeConsumerGrains); // "Initial Consumer count should be zero"
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < numStreams; i++)
{
Task promise = SetupOneStream(streamIds[i], streamProviderName, pipeline, numConsumers, numProducers, normalSubscribeCalls);
promises.Add(promise);
}
Task.WhenAll(promises).Wait();
sw.Stop();
int consumerCount = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain).FullName);
Assert.Equal(activeConsumerGrains + (numStreams * numConsumers), consumerCount); // "The correct number of new Consumer grains are active"
TimeSpan elapsed = sw.Elapsed;
int totalSubscriptions = numStreams * numConsumers;
double rps = totalSubscriptions / elapsed.TotalSeconds;
output.WriteLine("Subscriptions-per-second = {0} during period {1}", rps, elapsed);
Assert.NotEqual(0.0, rps); // "RPS greater than zero"
return Task.CompletedTask;
}
//private async Task Test_Stream_Churn_TimePeriod(
// string streamProviderName,
// int pipelineSize,
// TimeSpan duration,
// int numConsumers = 9,
// int numProducers = 1)
//{
// output.WriteLine("Testing Subscription churn for duration {0} with {1} Consumers and {2} Producers per Stream",
// duration, numConsumers, numProducers);
// AsyncPipeline pipeline = new AsyncPipeline(pipelineSize);
// var promises = new List<Task>();
// Stopwatch sw = Stopwatch.StartNew();
// for (int i = 0; sw.Elapsed <= duration; i++)
// {
// Guid streamId = Guid.NewGuid();
// Task promise = SetupOneStream(streamId, streamProviderName, pipeline, numConsumers, numProducers);
// promises.Add(promise);
// }
// await Task.WhenAll(promises);
// sw.Stop();
// TimeSpan elapsed = sw.Elapsed;
// int totalSubscription = numSt* numConsumers);
// double rps = totalSubscription/elapsed.TotalSeconds;
// output.WriteLine("Subscriptions-per-second = {0} during period {1}", rps, elapsed);
// Assert.NotEqual(0.0, rps, "RPS greater than zero");
//}
private void WarmUpPubSub(string streamProviderName, Guid[] streamIds, AsyncPipeline pipeline)
{
int numStreams = streamIds.Length;
// Warm up PubSub for the appropriate streams
for (int i = 0; i < numStreams; i++)
{
Guid streamId = streamIds[i];
string extKey = streamProviderName + "_" + this.StreamNamespace;
IPubSubRendezvousGrain pubsub = this.GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamId, extKey, null);
Task promise = pubsub.Validate();
pipeline.Add(promise);
}
pipeline.Wait();
}
private static bool producersFirst = true;
private SimpleGrainStatistic[] grainCounts;
private Task SetupOneStream(
Guid streamId, string streamProviderName,
AsyncPipeline pipeline,
int numConsumers,
int numProducers,
bool normalSubscribeCalls)
{
//output.WriteLine("Initializing Stream {0} with Consumers={1} Producers={2}", streamId, numConsumers, numProducers);
List<Task> promises = new List<Task>();
if (producersFirst && numProducers > 0)
{
// Producers
var p1 = SetupProducers(streamId, this.StreamNamespace, streamProviderName, pipeline, numProducers);
promises.AddRange(p1);
}
// Consumers
if (numConsumers > 0)
{
var c = SetupConsumers(streamId, this.StreamNamespace, streamProviderName, pipeline, numConsumers, normalSubscribeCalls);
promises.AddRange(c);
}
if (!producersFirst && numProducers > 0)
{
// Producers
var p2 = SetupProducers(streamId, this.StreamNamespace, streamProviderName, pipeline, numProducers);
promises.AddRange(p2);
}
return Task.WhenAll(promises);
}
private IList<Task> SetupProducers(Guid streamId, string streamNamespace, string streamProviderName, AsyncPipeline pipeline, int numProducers)
{
var producers = new List<IStreamLifecycleProducerGrain>();
var promises = new List<Task>();
for (int loopCount = 0; loopCount < numProducers; loopCount++)
{
var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid());
producers.Add(grain);
Task promise = grain.BecomeProducer(streamId, streamNamespace, streamProviderName);
if (loopCount == 0)
{
// First call for this stream, so wait for call to complete successfully so we know underlying infrastructure is set up.
promise.Wait();
}
promises.Add(promise);
pipeline.Add(promise);
}
return promises;
}
private IList<Task> SetupConsumers(Guid streamId, string streamNamespace, string streamProviderName, AsyncPipeline pipeline, int numConsumers, bool normalSubscribeCalls)
{
var consumers = new List<IStreamLifecycleConsumerGrain>();
var promises = new List<Task>();
long consumerIdStart = random.Next();
for (int loopCount = 0; loopCount < numConsumers; loopCount++)
{
var grain = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid());
consumers.Add(grain);
Task promise;
if (normalSubscribeCalls)
{
promise = grain.BecomeConsumer(streamId, streamNamespace, streamProviderName);
}
else
{
promise = grain.TestBecomeConsumerSlim(streamId, streamNamespace, streamProviderName);
}
//if (loopCount == 0)
//{
// // First call for this stream, so wait for call to complete successfully so we know underlying infrastructure is set up.
// promise.Wait();
//}
promises.Add(promise);
pipeline.Add(promise);
}
return promises;
}
private async Task Test_Stream_Limits(
string streamProviderName,
int numStreams,
int numProducers,
int numConsumers,
int numMessages = 1,
bool useFanOut = true)
{
output.WriteLine("Testing {0} Streams x Producers={1} Consumers={2} per stream with {3} messages each",
1, numProducers, numConsumers, numMessages);
Stopwatch sw = Stopwatch.StartNew();
var promises = new List<Task<double>>();
for (int s = 0; s < numStreams; s++)
{
Guid streamId = Guid.NewGuid();
Task<double> promise = Task.Run(
() => TestOneStream(streamId, streamProviderName, numProducers, numConsumers, numMessages, useFanOut));
promises.Add(promise);
if (!useFanOut)
{
await promise;
}
}
if (useFanOut)
{
output.WriteLine("Test: Waiting for {0} streams to finish", promises.Count);
}
double rps = (await Task.WhenAll(promises)).Sum();
promises.Clear();
output.WriteLine("Got total {0} RPS on {1} streams, or {2} RPS per streams",
rps, numStreams, rps/numStreams);
sw.Stop();
int totalMessages = numMessages * numStreams * numProducers;
output.WriteLine("Sent {0} messages total on {1} Streams from {2} Producers to {3} Consumers in {4} at {5} RPS",
totalMessages, numStreams, numStreams * numProducers, numStreams * numConsumers,
sw.Elapsed, totalMessages / sw.Elapsed.TotalSeconds);
}
private async Task<double> TestOneStream(Guid streamId, string streamProviderName,
int numProducers, int numConsumers, int numMessages,
bool useFanOut = true)
{
output.WriteLine("Testing Stream {0} with Producers={1} Consumers={2} x {3} messages",
streamId, numProducers, numConsumers, numMessages);
Stopwatch sw = Stopwatch.StartNew();
List<IStreamLifecycleConsumerGrain> consumers = new List<IStreamLifecycleConsumerGrain>();
List<IStreamLifecycleProducerGrain> producers = new List<IStreamLifecycleProducerGrain>();
await InitializeTopology(streamId, this.StreamNamespace, streamProviderName,
numProducers, numConsumers,
producers, consumers, useFanOut);
var promises = new List<Task>();
// Producers send M message each
int item = 1;
AsyncPipeline pipeline = new AsyncPipeline(MessagePipelineSize);
foreach (var grain in producers)
{
for (int m = 0; m < numMessages; m++)
{
Task promise = grain.SendItem(item++);
if (useFanOut)
{
pipeline.Add(promise);
promises.Add(promise);
}
else
{
await promise;
}
}
}
if (useFanOut)
{
//output.WriteLine("Test: Waiting for {0} producers to finish sending {1} messages", producers.Count, promises.Count);
await Task.WhenAll(promises);
promises.Clear();
}
var pubSub = StreamTestUtils.GetStreamPubSub(this.InternalClient);
// Check Consumer counts
int consumerCount = await pubSub.ConsumerCount(streamId, streamProviderName, StreamNamespace);
Assert.Equal(numConsumers, consumerCount); // "ConsumerCount for Stream {0}", streamId
// Check Producer counts
int producerCount = await pubSub.ProducerCount(streamId, streamProviderName, StreamNamespace);
Assert.Equal(numProducers, producerCount); // "ProducerCount for Stream {0}", streamId
// Check message counts received by consumers
int totalMessages = (numMessages + 1) * numProducers;
foreach (var grain in consumers)
{
int count = await grain.GetReceivedCount();
Assert.Equal(totalMessages, count); // "ReceivedCount for Consumer grain {0}", grain.GetPrimaryKey());
}
double rps = totalMessages/sw.Elapsed.TotalSeconds;
//output.WriteLine("Sent {0} messages total from {1} Producers to {2} Consumers in {3} at {4} RPS",
// totalMessages, numProducers, numConsumers,
// sw.Elapsed, rps);
return rps;
}
private async Task InitializeTopology(Guid streamId, string streamNamespace, string streamProviderName,
int numProducers, int numConsumers,
List<IStreamLifecycleProducerGrain> producers, List<IStreamLifecycleConsumerGrain> consumers,
bool useFanOut)
{
long nextGrainId = random.Next();
//var promises = new List<Task>();
AsyncPipeline pipeline = new AsyncPipeline(InitPipelineSize);
// Consumers
long consumerIdStart = nextGrainId;
for (int loopCount = 0; loopCount < numConsumers; loopCount++)
{
var grain = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid());
consumers.Add(grain);
Task promise = grain.BecomeConsumer(streamId, streamNamespace, streamProviderName);
if (useFanOut)
{
pipeline.Add(promise);
//promises.Add(promise);
//if (loopCount%WaitBatchSize == 0)
//{
// output.WriteLine("InitializeTopology: Waiting for {0} consumers to initialize", promises.Count);
// await Task.WhenAll(promises);
// promises.Clear();
//}
}
else
{
await promise;
}
}
if (useFanOut)
{
//output.WriteLine("InitializeTopology: Waiting for {0} consumers to initialize", promises.Count);
//await Task.WhenAll(promises);
//promises.Clear();
//output.WriteLine("InitializeTopology: Waiting for {0} consumers to initialize", pipeline.Count);
pipeline.Wait();
}
nextGrainId += numConsumers;
// Producers
long producerIdStart = nextGrainId;
pipeline = new AsyncPipeline(InitPipelineSize);
for (int loopCount = 0; loopCount < numProducers; loopCount++)
{
var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid());
producers.Add(grain);
Task promise = grain.BecomeProducer(streamId, streamNamespace, streamProviderName);
if (useFanOut)
{
pipeline.Add(promise);
//promises.Add(promise);
}
else
{
await promise;
}
}
if (useFanOut)
{
//output.WriteLine("InitializeTopology: Waiting for {0} producers to initialize", promises.Count);
//await Task.WhenAll(promises);
//promises.Clear();
//output.WriteLine("InitializeTopology: Waiting for {0} producers to initialize", pipeline.Count);
pipeline.Wait();
}
//nextGrainId += numProducers;
}
private int ActiveGrainCount(string grainTypeName)
{
grainCounts = mgmtGrain.GetSimpleGrainStatistics().Result; // Blocking Wait
int grainCount = grainCounts
.Where(g => g.GrainType == grainTypeName)
.Select(s => s.ActivationCount)
.Sum();
return grainCount;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Prism.Common
{
/// <summary>
/// A dictionary of lists.
/// </summary>
/// <typeparam name="TKey">The key to use for lists.</typeparam>
/// <typeparam name="TValue">The type of the value held by lists.</typeparam>
public sealed class ListDictionary<TKey, TValue> : IDictionary<TKey, IList<TValue>>
{
Dictionary<TKey, IList<TValue>> innerValues = new Dictionary<TKey, IList<TValue>>();
#region Public Methods
/// <summary>
/// If a list does not already exist, it will be created automatically.
/// </summary>
/// <param name="key">The key of the list that will hold the value.</param>
public void Add(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
CreateNewList(key);
}
/// <summary>
/// Adds a value to a list with the given key. If a list does not already exist,
/// it will be created automatically.
/// </summary>
/// <param name="key">The key of the list that will hold the value.</param>
/// <param name="value">The value to add to the list under the given key.</param>
public void Add(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (innerValues.ContainsKey(key))
{
innerValues[key].Add(value);
}
else
{
List<TValue> values = CreateNewList(key);
values.Add(value);
}
}
private List<TValue> CreateNewList(TKey key)
{
List<TValue> values = new List<TValue>();
innerValues.Add(key, values);
return values;
}
/// <summary>
/// Removes all entries in the dictionary.
/// </summary>
public void Clear()
{
innerValues.Clear();
}
/// <summary>
/// Determines whether the dictionary contains the specified value.
/// </summary>
/// <param name="value">The value to locate.</param>
/// <returns>true if the dictionary contains the value in any list; otherwise, false.</returns>
public bool ContainsValue(TValue value)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
{
if (pair.Value.Contains(value))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether the dictionary contains the given key.
/// </summary>
/// <param name="key">The key to locate.</param>
/// <returns>true if the dictionary contains the given key; otherwise, false.</returns>
public bool ContainsKey(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
return innerValues.ContainsKey(key);
}
/// <summary>
/// Retrieves the all the elements from the list which have a key that matches the condition
/// defined by the specified predicate.
/// </summary>
/// <param name="keyFilter">The filter with the condition to use to filter lists by their key.</param>
/// <returns>The elements that have a key that matches the condition defined by the specified predicate.</returns>
public IEnumerable<TValue> FindAllValuesByKey(Predicate<TKey> keyFilter)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
{
if (keyFilter(pair.Key))
{
foreach (TValue value in pair.Value)
{
yield return value;
}
}
}
}
/// <summary>
/// Retrieves all the elements that match the condition defined by the specified predicate.
/// </summary>
/// <param name="valueFilter">The filter with the condition to use to filter values.</param>
/// <returns>The elements that match the condition defined by the specified predicate.</returns>
public IEnumerable<TValue> FindAllValues(Predicate<TValue> valueFilter)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
{
foreach (TValue value in pair.Value)
{
if (valueFilter(value))
{
yield return value;
}
}
}
}
/// <summary>
/// Removes a list by key.
/// </summary>
/// <param name="key">The key of the list to remove.</param>
/// <returns><see langword="true" /> if the element was removed.</returns>
public bool Remove(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
return innerValues.Remove(key);
}
/// <summary>
/// Removes a value from the list with the given key.
/// </summary>
/// <param name="key">The key of the list where the value exists.</param>
/// <param name="value">The value to remove.</param>
public void Remove(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (innerValues.ContainsKey(key))
{
List<TValue> innerList = (List<TValue>)innerValues[key];
innerList.RemoveAll(delegate(TValue item)
{
return value.Equals(item);
});
}
}
/// <summary>
/// Removes a value from all lists where it may be found.
/// </summary>
/// <param name="value">The value to remove.</param>
public void Remove(TValue value)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
{
Remove(pair.Key, value);
}
}
#endregion
#region Properties
/// <summary>
/// Gets a shallow copy of all values in all lists.
/// </summary>
/// <value>List of values.</value>
public IList<TValue> Values
{
get
{
List<TValue> values = new List<TValue>();
foreach (IEnumerable<TValue> list in innerValues.Values)
{
values.AddRange(list);
}
return values;
}
}
/// <summary>
/// Gets the list of keys in the dictionary.
/// </summary>
/// <value>Collection of keys.</value>
public ICollection<TKey> Keys
{
get { return innerValues.Keys; }
}
/// <summary>
/// Gets or sets the list associated with the given key. The
/// access always succeeds, eventually returning an empty list.
/// </summary>
/// <param name="key">The key of the list to access.</param>
/// <returns>The list associated with the key.</returns>
public IList<TValue> this[TKey key]
{
get
{
if (innerValues.ContainsKey(key) == false)
{
innerValues.Add(key, new List<TValue>());
}
return innerValues[key];
}
set { innerValues[key] = value; }
}
/// <summary>
/// Gets the number of lists in the dictionary.
/// </summary>
/// <value>Value indicating the values count.</value>
public int Count
{
get { return innerValues.Count; }
}
#endregion
#region IDictionary<TKey,List<TValue>> Members
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.Add"/> for more information.
/// </summary>
void IDictionary<TKey, IList<TValue>>.Add(TKey key, IList<TValue> value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
innerValues.Add(key, value);
}
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.TryGetValue"/> for more information.
/// </summary>
bool IDictionary<TKey, IList<TValue>>.TryGetValue(TKey key, out IList<TValue> value)
{
value = this[key];
return true;
}
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.Values"/> for more information.
/// </summary>
ICollection<IList<TValue>> IDictionary<TKey, IList<TValue>>.Values
{
get { return innerValues.Values; }
}
#endregion
#region ICollection<KeyValuePair<TKey,List<TValue>>> Members
/// <summary>
/// See <see cref="ICollection{TValue}.Add"/> for more information.
/// </summary>
void ICollection<KeyValuePair<TKey, IList<TValue>>>.Add(KeyValuePair<TKey, IList<TValue>> item)
{
((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Add(item);
}
/// <summary>
/// See <see cref="ICollection{TValue}.Contains"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Contains(KeyValuePair<TKey, IList<TValue>> item)
{
return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Contains(item);
}
/// <summary>
/// See <see cref="ICollection{TValue}.CopyTo"/> for more information.
/// </summary>
void ICollection<KeyValuePair<TKey, IList<TValue>>>.CopyTo(KeyValuePair<TKey, IList<TValue>>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).CopyTo(array, arrayIndex);
}
/// <summary>
/// See <see cref="ICollection{TValue}.IsReadOnly"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.IsReadOnly
{
get { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).IsReadOnly; }
}
/// <summary>
/// See <see cref="ICollection{TValue}.Remove"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Remove(KeyValuePair<TKey, IList<TValue>> item)
{
return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Remove(item);
}
#endregion
#region IEnumerable<KeyValuePair<TKey,List<TValue>>> Members
/// <summary>
/// See <see cref="IEnumerable{TValue}.GetEnumerator"/> for more information.
/// </summary>
IEnumerator<KeyValuePair<TKey, IList<TValue>>> IEnumerable<KeyValuePair<TKey, IList<TValue>>>.GetEnumerator()
{
return innerValues.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// See <see cref="System.Collections.IEnumerable.GetEnumerator"/> for more information.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return innerValues.GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
namespace Tests
{
[Serializable]
internal sealed class Options
{
const string RelativeRoot = @"..\..\..\..\";
const string TestHarnessDirectory = @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug";
public readonly string RootDirectory;
public readonly string SourceFile;
private readonly string compilerCode;
public string FoxtrotOptions;
private List<string> libPaths;
public readonly List<string> References;
public bool UseContractReferenceAssemblies;
public string BuildFramework = "v4.5";
public string ReferencesFramework
{
get
{
return referencesFramework ?? BuildFramework;
}
set
{
referencesFramework = value;
}
}
private string referencesFramework;
public string ContractFramework = "v4.5";
public bool UseBinDir = true;
public bool UseExe = true;
/// <summary>
/// If set to true, verification will include reading contracts back from the rewritten
/// assembly in addition to running peverify.
/// </summary>
public bool DeepVerify = false;
public List<string> LibPaths
{
get
{
if (libPaths == null) { libPaths = new List<string>(); }
return libPaths;
}
}
public string TestName
{
get
{
if (SourceFile != null) { return Path.GetFileNameWithoutExtension(SourceFile); }
else return "Unknown";
}
}
/// <summary>
/// Should be true, if old (pre-RC) Roslyn compiler needs to be used.
/// </summary>
public bool IsLegacyRoslyn { get; set; }
public string Compiler
{
get
{
switch (compilerCode)
{
case "VB":
return IsLegacyRoslyn ? "rvbc.exe" : "vbc.exe";
default:
return IsLegacyRoslyn ? "rcsc.exe" : "csc.exe";
}
}
}
public string CompilerPath
{
get { return compilerPath ?? BuildFramework; }
set { compilerPath = value; }
}
private string compilerPath;
public bool IsV35 { get { return this.BuildFramework.Contains("v3.5"); } }
public bool IsV40 { get { return this.BuildFramework.Contains("v4.0"); } }
public bool IsV45 { get { return this.BuildFramework.Contains("v4.5") || IsRoslynBasedCompiler; } }
bool IsSilverlight { get { return this.BuildFramework.Contains("Silverlight"); } }
public bool IsRoslynBasedCompiler { get { return CompilerPath.Contains("Roslyn"); } }
public string GetCompilerAbsolutePath(string toolsRoot)
{
return MakeAbsolute(Path.Combine(toolsRoot, CompilerPath, Compiler));
}
public string GetPEVerifyFullPath(string toolsRoot)
{
return MakeAbsolute(Path.Combine(toolsRoot, CompilerPath, "peverify.exe"));
}
string Moniker
{
get
{
if (!IsLegacyRoslyn) { return FrameworkMoniker; }
if (compilerCode == "VB")
{
return FrameworkMoniker + ",ROSLYN";
}
return FrameworkMoniker + ";ROSLYN";
}
}
string FrameworkMoniker
{
get
{
if (IsSilverlight)
{
if (IsV40)
{
return "SILVERLIGHT_4_0";
}
if (IsV45)
{
return "SILVERLIGHT_4_5";
}
{
return "SILVERLIGHT_3_0";
}
}
else
{
if (IsV40)
{
return "NETFRAMEWORK_4_0";
}
if (IsV45)
{
return "NETFRAMEWORK_4_5";
}
{
return "NETFRAMEWORK_3_5";
}
}
}
}
public bool UseTestHarness { get; set; }
private string DefaultCompilerOptions
{
get
{
if (compilerCode == "VB")
{
return
String.Format("/noconfig /nostdlib /define:\"DEBUG=-1,{0},CONTRACTS_FULL\",_MyType=\\\"Console\\\" " +
"/imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,System.Data,System.Diagnostics,System.Linq,System.Xml.Linq " +
"/optioncompare:Binary /optionexplicit+ /optionstrict+ /optioninfer+ ",
Moniker);
}
if (IsRoslynBasedCompiler)
{
if (UseTestHarness)
{
return String.Format("/d:CONTRACTS_FULL;ROSLYN;DEBUG;{0} /noconfig /nostdlib {1}", Moniker,
MakeAbsolute(@"Foxtrot\Tests\Sources\TestHarness.cs"));
}
else
{
return String.Format("/d:CONTRACTS_FULL;ROSLYN;DEBUG;{0} /noconfig /nostdlib", Moniker);
}
}
else
{
if (UseTestHarness)
{
return String.Format("/d:CONTRACTS_FULL;DEBUG;{0} /noconfig /nostdlib {1}", Moniker,
MakeAbsolute(@"Foxtrot\Tests\Sources\TestHarness.cs"));
}
else
{
return String.Format("/d:CONTRACTS_FULL;DEBUG;{0} /noconfig /nostdlib", Moniker);
}
}
}
}
public string FinalCompilerOptions
{
get
{
return DefaultCompilerOptions + " " + CompilerOptions;
}
}
public string CompilerOptions { get; set; }
public Options(
string sourceFile,
string foxtrotOptions,
bool useContractReferenceAssemblies,
string compilerOptions,
string[] references,
string[] libPaths,
string compilerCode,
bool useBinDir,
bool useExe,
bool mustSucceed)
{
this.SourceFile = sourceFile;
this.FoxtrotOptions = foxtrotOptions;
this.UseContractReferenceAssemblies = useContractReferenceAssemblies;
this.CompilerOptions = compilerOptions;
this.References = new List<string>(new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" });
this.References.AddRange(references);
this.libPaths = new List<string>(libPaths ?? Enumerable.Empty<string>());
this.compilerCode = compilerCode;
this.UseBinDir = useBinDir;
this.UseExe = useExe;
this.MustSucceed = mustSucceed;
this.RootDirectory = Path.GetFullPath(RelativeRoot);
}
public bool ReleaseMode { get; set; }
private static string LoadString(System.Data.DataRow dataRow, string name)
{
if (!ColumnExists(dataRow, name)) return "";
return dataRow[name] as string;
}
private static List<string> LoadList(System.Data.DataRow dataRow, string name, params string[] initial)
{
var result = new List<string>(initial);
if (!ColumnExists(dataRow, name)) return result;
string listdata = dataRow[name] as string;
if (!string.IsNullOrEmpty(listdata))
{
result.AddRange(listdata.Split(';'));
}
return result;
}
private static bool ColumnExists(System.Data.DataRow dataRow, string name)
{
return dataRow.Table.Columns.IndexOf(name) >= 0;
}
private bool LoadBool(string name, System.Data.DataRow dataRow, bool defaultValue)
{
if (!ColumnExists(dataRow, name)) return defaultValue;
var booloption = dataRow[name] as string;
if (!string.IsNullOrEmpty(booloption))
{
bool result;
if (bool.TryParse(booloption, out result))
{
return result;
}
}
return defaultValue;
}
private string LoadString(string name, System.Data.DataRow dataRow, string defaultValue)
{
if (!ColumnExists(dataRow, name)) return defaultValue;
var option = dataRow[name] as string;
if (!string.IsNullOrEmpty(option))
{
return option;
}
return defaultValue;
}
/// <summary>
/// Not only makes the exe absolute but also tries to find it in the deployment dir to make code coverage work.
/// </summary>
public string GetFullExecutablePath(string relativePath)
{
return MakeAbsolute(relativePath);
}
public string MakeAbsolute(string relativeToRoot)
{
return Path.GetFullPath(Path.Combine(this.RootDirectory, relativeToRoot));
}
internal void Delete(string fileName)
{
var absolute = MakeAbsolute(fileName);
if (File.Exists(absolute))
{
File.Delete(absolute);
}
}
public bool MustSucceed { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RestSharp;
using Systran.NlpClientLib.Client;
using Systran.NlpClientLib.Model;
namespace Systran.NlpClientLib.Api {
public interface IMorphologyApi {
/// <summary>
/// Get lemma Get the lemma for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractLemmaResponse</returns>
MorphologyExtractLemmaResponse NlpMorphologyExtractLemmaGet (string Input, string InputFile, string Lang, int? Profile, string Callback);
/// <summary>
/// Get lemma Get the lemma for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractLemmaResponse</returns>
Task<MorphologyExtractLemmaResponse> NlpMorphologyExtractLemmaGetAsync (string Input, string InputFile, string Lang, int? Profile, string Callback);
/// <summary>
/// Get NP/chunks Get Noun-phrases and chunks from an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractNPResponse</returns>
MorphologyExtractNPResponse NlpMorphologyExtractNpGet (string Input, string InputFile, string Lang, int? Profile, string Callback);
/// <summary>
/// Get NP/chunks Get Noun-phrases and chunks from an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractNPResponse</returns>
Task<MorphologyExtractNPResponse> NlpMorphologyExtractNpGetAsync (string Input, string InputFile, string Lang, int? Profile, string Callback);
/// <summary>
/// Get part of speech Get the part of speech for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractPosResponse</returns>
MorphologyExtractPosResponse NlpMorphologyExtractPosGet (string Input, string InputFile, string Lang, int? Profile, string Callback);
/// <summary>
/// Get part of speech Get the part of speech for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractPosResponse</returns>
Task<MorphologyExtractPosResponse> NlpMorphologyExtractPosGetAsync (string Input, string InputFile, string Lang, int? Profile, string Callback);
/// <summary>
/// Supported Languages List of languages pairs in which Morphological analysis is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
SupportedLanguagesResponse NlpMorphologySupportedLanguagesGet (string Callback);
/// <summary>
/// Supported Languages List of languages pairs in which Morphological analysis is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
Task<SupportedLanguagesResponse> NlpMorphologySupportedLanguagesGetAsync (string Callback);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class MorphologyApi : IMorphologyApi {
/// <summary>
/// Initializes a new instance of the <see cref="MorphologyApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public MorphologyApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MorphologyApi"/> class.
/// </summary>
/// <returns></returns>
public MorphologyApi(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient apiClient {get; set;}
/// <summary>
/// Get lemma Get the lemma for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractLemmaResponse</returns>
public MorphologyExtractLemmaResponse NlpMorphologyExtractLemmaGet (string Input, string InputFile, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpMorphologyExtractLemmaGet");
var path = "/nlp/morphology/extract/lemma";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologyExtractLemmaGet: " + response.Content, response.Content);
}
return (MorphologyExtractLemmaResponse) apiClient.Deserialize(response.Content, typeof(MorphologyExtractLemmaResponse));
}
/// <summary>
/// Get lemma Get the lemma for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractLemmaResponse</returns>
public async Task<MorphologyExtractLemmaResponse> NlpMorphologyExtractLemmaGetAsync (string Input, string InputFile, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpMorphologyExtractLemmaGet");
var path = "/nlp/morphology/extract/lemma";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologyExtractLemmaGet: " + response.Content, response.Content);
}
return (MorphologyExtractLemmaResponse) apiClient.Deserialize(response.Content, typeof(MorphologyExtractLemmaResponse));
}
/// <summary>
/// Get NP/chunks Get Noun-phrases and chunks from an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractNPResponse</returns>
public MorphologyExtractNPResponse NlpMorphologyExtractNpGet (string Input, string InputFile, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpMorphologyExtractNpGet");
var path = "/nlp/morphology/extract/np";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologyExtractNpGet: " + response.Content, response.Content);
}
return (MorphologyExtractNPResponse) apiClient.Deserialize(response.Content, typeof(MorphologyExtractNPResponse));
}
/// <summary>
/// Get NP/chunks Get Noun-phrases and chunks from an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractNPResponse</returns>
public async Task<MorphologyExtractNPResponse> NlpMorphologyExtractNpGetAsync (string Input, string InputFile, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpMorphologyExtractNpGet");
var path = "/nlp/morphology/extract/np";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologyExtractNpGet: " + response.Content, response.Content);
}
return (MorphologyExtractNPResponse) apiClient.Deserialize(response.Content, typeof(MorphologyExtractNPResponse));
}
/// <summary>
/// Get part of speech Get the part of speech for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractPosResponse</returns>
public MorphologyExtractPosResponse NlpMorphologyExtractPosGet (string Input, string InputFile, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpMorphologyExtractPosGet");
var path = "/nlp/morphology/extract/pos";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologyExtractPosGet: " + response.Content, response.Content);
}
return (MorphologyExtractPosResponse) apiClient.Deserialize(response.Content, typeof(MorphologyExtractPosResponse));
}
/// <summary>
/// Get part of speech Get the part of speech for elements of an input text.\n
/// </summary>
/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>MorphologyExtractPosResponse</returns>
public async Task<MorphologyExtractPosResponse> NlpMorphologyExtractPosGetAsync (string Input, string InputFile, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpMorphologyExtractPosGet");
var path = "/nlp/morphology/extract/pos";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologyExtractPosGet: " + response.Content, response.Content);
}
return (MorphologyExtractPosResponse) apiClient.Deserialize(response.Content, typeof(MorphologyExtractPosResponse));
}
/// <summary>
/// Supported Languages List of languages pairs in which Morphological analysis is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
public SupportedLanguagesResponse NlpMorphologySupportedLanguagesGet (string Callback) {
var path = "/nlp/morphology/supportedLanguages";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologySupportedLanguagesGet: " + response.Content, response.Content);
}
return (SupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(SupportedLanguagesResponse));
}
/// <summary>
/// Supported Languages List of languages pairs in which Morphological analysis is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
public async Task<SupportedLanguagesResponse> NlpMorphologySupportedLanguagesGetAsync (string Callback) {
var path = "/nlp/morphology/supportedLanguages";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpMorphologySupportedLanguagesGet: " + response.Content, response.Content);
}
return (SupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(SupportedLanguagesResponse));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace XDomainProxy.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Text;
namespace RzAspects
{
/// <summary>
/// SimpleRNG is a simple random number generator based on
/// George Marsaglia's MWC (multiply with carry) generator.
/// Although it is very simple, it passes Marsaglia's DIEHARD
/// series of random number generator tests.
///
/// Written by John D. Cook
/// http://www.johndcook.com
/// </summary>
public class SimpleRNG
{
private static uint m_w;
private static uint m_z;
static SimpleRNG()
{
SetSeed( (uint)DateTime.Now.Millisecond );
// These values are not magical, just the default values Marsaglia used.
// Any pair of unsigned integers should be fine.
m_w = 521288629;
m_z = 362436069;
}
// The random generator seed can be set three ways:
// 1) specifying two non-zero unsigned integers
// 2) specifying one non-zero unsigned integer and taking a default value for the second
// 3) setting the seed from the system time
public static void SetSeed(uint u, uint v)
{
if (u != 0) m_w = u;
if (v != 0) m_z = v;
}
public static void SetSeed(uint u)
{
m_w = u;
}
public static void SetSeedFromSystemTime()
{
System.DateTime dt = System.DateTime.Now;
long x = dt.ToFileTime();
SetSeed((uint)(x >> 16), (uint)(x % 4294967296));
}
// Produce a uniform random sample from the open interval (0, 1).
// The method will not return either end point.
public static double GetUniform()
{
// 0 <= u < 2^32
uint u = GetUint();
// The magic number below is 1/(2^32 + 2).
// The result is strictly between 0 and 1.
return (u + 1.0) * 2.328306435454494e-10;
}
/// <summary>
/// Rolls against a specified percentage. Returns true if the value is smaller than the specific percentage. False otherwise.
/// </summary>
/// <param name="percentage">Value between 0 and 1 representing the percentage chance the roll returns true.</param>
/// <returns>True if the roll was less than the percentage. False otherwise.</returns>
public static bool RollPercentage( double percentage )
{
return GetUniform() <= percentage;
}
// This is the heart of the generator.
// It uses George Marsaglia's MWC algorithm to produce an unsigned integer.
// See http://www.bobwheeler.com/statistics/Password/MarsagliaPost.txt
private static uint GetUint()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w;
}
// Get normal (Gaussian) random sample with mean 0 and standard deviation 1
public static double GetNormal()
{
// Use Box-Muller algorithm
double u1 = GetUniform();
double u2 = GetUniform();
double r = Math.Sqrt( -2.0*Math.Log(u1) );
double theta = 2.0*Math.PI*u2;
return r*Math.Sin(theta);
}
// Get normal (Gaussian) random sample with specified mean and standard deviation
public static double GetNormal(double mean, double standardDeviation)
{
if (standardDeviation <= 0.0)
{
string msg = string.Format("Shape must be positive. Received {0}.", standardDeviation);
throw new ArgumentOutOfRangeException(msg);
}
return mean + standardDeviation*GetNormal();
}
public static double GetNormal( double mean, double standardDeviation, double min, double max )
{
return GetNormal( mean, standardDeviation ).Clamp( min, max );
}
// Get exponential random sample with mean 1
public static double GetExponential()
{
return -Math.Log( GetUniform() );
}
// Get exponential random sample with specified mean
public static double GetExponential(double mean)
{
if (mean <= 0.0)
{
string msg = string.Format("Mean must be positive. Received {0}.", mean);
throw new ArgumentOutOfRangeException(msg);
}
return mean*GetExponential();
}
public static double GetGamma(double shape, double scale)
{
// Implementation based on "A Simple Method for Generating Gamma Variables"
// by George Marsaglia and Wai Wan Tsang. ACM Transactions on Mathematical Software
// Vol 26, No 3, September 2000, pages 363-372.
double d, c, x, xsquared, v, u;
if (shape >= 1.0)
{
d = shape - 1.0/3.0;
c = 1.0/Math.Sqrt(9.0*d);
for (;;)
{
do
{
x = GetNormal();
v = 1.0 + c*x;
}
while (v <= 0.0);
v = v*v*v;
u = GetUniform();
xsquared = x*x;
if (u < 1.0 -.0331*xsquared*xsquared || Math.Log(u) < 0.5*xsquared + d*(1.0 - v + Math.Log(v)))
return scale*d*v;
}
}
else if (shape <= 0.0)
{
string msg = string.Format("Shape must be positive. Received {0}.", shape);
throw new ArgumentOutOfRangeException(msg);
}
else
{
double g = GetGamma(shape+1.0, 1.0);
double w = GetUniform();
return scale*g*Math.Pow(w, 1.0/shape);
}
}
public static double GetChiSquare(double degreesOfFreedom)
{
// A chi squared distribution with n degrees of freedom
// is a gamma distribution with shape n/2 and scale 2.
return GetGamma(0.5 * degreesOfFreedom, 2.0);
}
public static double GetInverseGamma(double shape, double scale)
{
// If X is gamma(shape, scale) then
// 1/Y is inverse gamma(shape, 1/scale)
return 1.0 / GetGamma(shape, 1.0 / scale);
}
public static double GetWeibull(double shape, double scale)
{
if (shape <= 0.0 || scale <= 0.0)
{
string msg = string.Format("Shape and scale parameters must be positive. Recieved shape {0} and scale{1}.", shape, scale);
throw new ArgumentOutOfRangeException(msg);
}
return scale * Math.Pow(-Math.Log(GetUniform()), 1.0 / shape);
}
public static double GetCauchy(double median, double scale)
{
if (scale <= 0)
{
string msg = string.Format("Scale must be positive. Received {0}.", scale);
throw new ArgumentException(msg);
}
double p = GetUniform();
// Apply inverse of the Cauchy distribution function to a uniform
return median + scale*Math.Tan(Math.PI*(p - 0.5));
}
public static double GetStudentT(double degreesOfFreedom)
{
if (degreesOfFreedom <= 0)
{
string msg = string.Format("Degrees of freedom must be positive. Received {0}.", degreesOfFreedom);
throw new ArgumentException(msg);
}
// See Seminumerical Algorithms by Knuth
double y1 = GetNormal();
double y2 = GetChiSquare(degreesOfFreedom);
return y1 / Math.Sqrt(y2 / degreesOfFreedom);
}
// The Laplace distribution is also known as the double exponential distribution.
public static double GetLaplace(double mean, double scale)
{
double u = GetUniform();
return (u < 0.5) ?
mean + scale*Math.Log(2.0*u) :
mean - scale*Math.Log(2*(1-u));
}
public static double GetLogNormal(double mu, double sigma)
{
return Math.Exp(GetNormal(mu, sigma));
}
public static double GetBeta(double a, double b)
{
if (a <= 0.0 || b <= 0.0)
{
string msg = string.Format("Beta parameters must be positive. Received {0} and {1}.", a, b);
throw new ArgumentOutOfRangeException(msg);
}
// There are more efficient methods for generating beta samples.
// However such methods are a little more efficient and much more complicated.
// For an explanation of why the following method works, see
// http://www.johndcook.com/distribution_chart.html#gamma_beta
double u = GetGamma(a, 1.0);
double v = GetGamma(b, 1.0);
return u / (u + v);
}
public static int GetUniformInt( int min, int max )
{
double rand = GetUniform();
return min + (int)( rand * ( max - min ) );
}
public static string GetRandomString( int size )
{
StringBuilder builder = new StringBuilder();
char ch;
for( int i = 0; i < size; i++ )
{
ch = Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * GetUniform() + 65 ) ) );
builder.Append( ch );
}
return builder.ToString();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace RESTServiceTest.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using UnityEngine;
/* Based on the JSON parser from
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* I simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*/
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
public class MiniJSON
{
private const int TOKEN_NONE = 0;
private const int TOKEN_CURLY_OPEN = 1;
private const int TOKEN_CURLY_CLOSE = 2;
private const int TOKEN_SQUARED_OPEN = 3;
private const int TOKEN_SQUARED_CLOSE = 4;
private const int TOKEN_COLON = 5;
private const int TOKEN_COMMA = 6;
private const int TOKEN_STRING = 7;
private const int TOKEN_NUMBER = 8;
private const int TOKEN_TRUE = 9;
private const int TOKEN_FALSE = 10;
private const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
/// <summary>
/// On decoding, this value holds the position at which the parse failed (-1 = no error).
/// </summary>
protected static int lastErrorIndex = -1;
protected static string lastDecode = "";
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object jsonDecode( string json )
{
// save the string for debug information
MiniJSON.lastDecode = json;
if( json != null )
{
char[] charArray = json.ToCharArray();
int index = 0;
bool success = true;
object value = MiniJSON.parseValue( charArray, ref index, ref success );
if( success )
MiniJSON.lastErrorIndex = -1;
else
MiniJSON.lastErrorIndex = index;
return value;
}
else
{
return null;
}
}
/// <summary>
/// Converts a Hashtable / ArrayList / Dictionary(string,string) object into a JSON string
/// </summary>
/// <param name="json">A Hashtable / ArrayList</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string jsonEncode( object json )
{
var builder = new StringBuilder( BUILDER_CAPACITY );
var success = MiniJSON.serializeValue( json, builder );
return ( success ? builder.ToString() : null );
}
/// <summary>
/// On decoding, this function returns the position at which the parse failed (-1 = no error).
/// </summary>
/// <returns></returns>
public static bool lastDecodeSuccessful()
{
return ( MiniJSON.lastErrorIndex == -1 );
}
/// <summary>
/// On decoding, this function returns the position at which the parse failed (-1 = no error).
/// </summary>
/// <returns></returns>
public static int getLastErrorIndex()
{
return MiniJSON.lastErrorIndex;
}
/// <summary>
/// If a decoding error occurred, this function returns a piece of the JSON string
/// at which the error took place. To ease debugging.
/// </summary>
/// <returns></returns>
public static string getLastErrorSnippet()
{
if( MiniJSON.lastErrorIndex == -1 )
{
return "";
}
else
{
int startIndex = MiniJSON.lastErrorIndex - 5;
int endIndex = MiniJSON.lastErrorIndex + 15;
if( startIndex < 0 )
startIndex = 0;
if( endIndex >= MiniJSON.lastDecode.Length )
endIndex = MiniJSON.lastDecode.Length - 1;
return MiniJSON.lastDecode.Substring( startIndex, endIndex - startIndex + 1 );
}
}
#region Parsing
protected static Hashtable parseObject( char[] json, ref int index )
{
Hashtable table = new Hashtable();
int token;
// {
nextToken( json, ref index );
bool done = false;
while( !done )
{
token = lookAhead( json, index );
if( token == MiniJSON.TOKEN_NONE )
{
return null;
}
else if( token == MiniJSON.TOKEN_COMMA )
{
nextToken( json, ref index );
}
else if( token == MiniJSON.TOKEN_CURLY_CLOSE )
{
nextToken( json, ref index );
return table;
}
else
{
// name
string name = parseString( json, ref index );
if( name == null )
{
return null;
}
// :
token = nextToken( json, ref index );
if( token != MiniJSON.TOKEN_COLON )
return null;
// value
bool success = true;
object value = parseValue( json, ref index, ref success );
if( !success )
return null;
table[name] = value;
}
}
return table;
}
protected static ArrayList parseArray( char[] json, ref int index )
{
ArrayList array = new ArrayList();
// [
nextToken( json, ref index );
bool done = false;
while( !done )
{
int token = lookAhead( json, index );
if( token == MiniJSON.TOKEN_NONE )
{
return null;
}
else if( token == MiniJSON.TOKEN_COMMA )
{
nextToken( json, ref index );
}
else if( token == MiniJSON.TOKEN_SQUARED_CLOSE )
{
nextToken( json, ref index );
break;
}
else
{
bool success = true;
object value = parseValue( json, ref index, ref success );
if( !success )
return null;
array.Add( value );
}
}
return array;
}
protected static object parseValue( char[] json, ref int index, ref bool success )
{
switch( lookAhead( json, index ) )
{
case MiniJSON.TOKEN_STRING:
return parseString( json, ref index );
case MiniJSON.TOKEN_NUMBER:
return parseNumber( json, ref index );
case MiniJSON.TOKEN_CURLY_OPEN:
return parseObject( json, ref index );
case MiniJSON.TOKEN_SQUARED_OPEN:
return parseArray( json, ref index );
case MiniJSON.TOKEN_TRUE:
nextToken( json, ref index );
return Boolean.Parse( "TRUE" );
case MiniJSON.TOKEN_FALSE:
nextToken( json, ref index );
return Boolean.Parse( "FALSE" );
case MiniJSON.TOKEN_NULL:
nextToken( json, ref index );
return null;
case MiniJSON.TOKEN_NONE:
break;
}
success = false;
return null;
}
static private System.Text.StringBuilder sb = new StringBuilder();
static private char[] unicodeCharArray = new char[4];
protected static string parseString( char[] json, ref int index )
{
sb.Length = 0;
char c;
eatWhitespace( json, ref index );
// "
c = json[index++];
bool complete = false;
while( !complete )
{
if( index == json.Length )
break;
c = json[index++];
if( c == '"' )
{
complete = true;
break;
}
else if( c == '\\' )
{
if( index == json.Length )
break;
c = json[index++];
if( c == '"' )
{
sb.Append('"');
}
else if( c == '\\' )
{
sb.Append('\\');
}
else if( c == '/' )
{
sb.Append('/');
}
else if( c == 'b' )
{
sb.Append('\b');
}
else if( c == 'f' )
{
sb.Append('\f');
}
else if( c == 'n' )
{
sb.Append('\n');
}
else if( c == 'r' )
{
sb.Append('\r');
}
else if( c == 't' )
{
sb.Append('\t');
}
else if( c == 'u' )
{
int remainingLength = json.Length - index;
if( remainingLength >= 4 )
{
Array.Copy( json, index, unicodeCharArray, 0, 4 );
//Drop in the HTML markup for the unicode character
//sb.Append("&#x" + new string( unicodeCharArray ) + ";");
//Put the decoded character
sb.Append((char) Convert.ToInt32(new string(unicodeCharArray), 16));
// skip 4 chars
index += 4;
}
else
{
break;
}
}
}
else
{
sb.Append(c);
}
}
if( !complete )
return null;
return sb.ToString();
}
protected static double parseNumber( char[] json, ref int index )
{
eatWhitespace( json, ref index );
int lastIndex = getLastIndexOfNumber( json, index );
int charLength = ( lastIndex - index ) + 1;
char[] numberCharArray = new char[charLength];
Array.Copy( json, index, numberCharArray, 0, charLength );
index = lastIndex + 1;
return Double.Parse( new string( numberCharArray ) ); // , CultureInfo.InvariantCulture);
}
protected static int getLastIndexOfNumber( char[] json, int index )
{
int lastIndex;
for( lastIndex = index; lastIndex < json.Length; lastIndex++ )
if( "0123456789+-.eE".IndexOf( json[lastIndex] ) == -1 )
{
break;
}
return lastIndex - 1;
}
protected static void eatWhitespace( char[] json, ref int index )
{
for( ; index < json.Length; index++ )
{
char c = json[index];
if (c != ' ' &&
c != '\t' &&
c != '\n' &&
c != '\r')
{
break;
}
}
}
protected static int lookAhead( char[] json, int index )
{
int saveIndex = index;
return nextToken( json, ref saveIndex );
}
protected static int nextToken( char[] json, ref int index )
{
eatWhitespace( json, ref index );
if( index == json.Length )
{
return MiniJSON.TOKEN_NONE;
}
char c = json[index];
index++;
switch( c )
{
case '{':
return MiniJSON.TOKEN_CURLY_OPEN;
case '}':
return MiniJSON.TOKEN_CURLY_CLOSE;
case '[':
return MiniJSON.TOKEN_SQUARED_OPEN;
case ']':
return MiniJSON.TOKEN_SQUARED_CLOSE;
case ',':
return MiniJSON.TOKEN_COMMA;
case '"':
return MiniJSON.TOKEN_STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return MiniJSON.TOKEN_NUMBER;
case ':':
return MiniJSON.TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if( remainingLength >= 5 )
{
if( json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e' )
{
index += 5;
return MiniJSON.TOKEN_FALSE;
}
}
// true
if( remainingLength >= 4 )
{
if( json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e' )
{
index += 4;
return MiniJSON.TOKEN_TRUE;
}
}
// null
if( remainingLength >= 4 )
{
if( json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l' )
{
index += 4;
return MiniJSON.TOKEN_NULL;
}
}
return MiniJSON.TOKEN_NONE;
}
#endregion
#region Serialization
protected static bool serializeObjectOrArray( object objectOrArray, StringBuilder builder )
{
if( objectOrArray is Hashtable )
{
return serializeObject( (Hashtable)objectOrArray, builder );
}
else if( objectOrArray is ArrayList )
{
return serializeArray( (ArrayList)objectOrArray, builder );
}
else
{
return false;
}
}
protected static bool serializeObject( Hashtable anObject, StringBuilder builder )
{
builder.Append( "{" );
IDictionaryEnumerator e = anObject.GetEnumerator();
bool first = true;
while( e.MoveNext() )
{
string key = e.Key.ToString();
object value = e.Value;
if( !first )
{
builder.Append( ", " );
}
serializeString( key, builder );
builder.Append( ":" );
if( !serializeValue( value, builder ) )
{
return false;
}
first = false;
}
builder.Append( "}" );
return true;
}
protected static bool serializeDictionary( Dictionary<string,string> dict, StringBuilder builder )
{
builder.Append( "{" );
bool first = true;
foreach( var kv in dict )
{
if( !first )
builder.Append( ", " );
serializeString( kv.Key, builder );
builder.Append( ":" );
serializeString( kv.Value, builder );
first = false;
}
builder.Append( "}" );
return true;
}
protected static bool serializeArray( ArrayList anArray, StringBuilder builder )
{
builder.Append( "[" );
bool first = true;
for( int i = 0; i < anArray.Count; i++ )
{
object value = anArray[i];
if( !first )
{
builder.Append( ", " );
}
if( !serializeValue( value, builder ) )
{
return false;
}
first = false;
}
builder.Append( "]" );
return true;
}
protected static bool serializeValue( object value, StringBuilder builder )
{
// Type t = value.GetType();
// Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray);
if( value == null )
{
builder.Append( "null" );
}
else if( value.GetType().IsArray )
{
serializeArray( new ArrayList( (ICollection)value ), builder );
}
else if( value is string )
{
serializeString( (string)value, builder );
}
else if( value is Char )
{
serializeString( Convert.ToString( (char)value ), builder );
}
else if( value is Hashtable )
{
serializeObject( (Hashtable)value, builder );
}
else if( value is Dictionary<string,string> )
{
serializeDictionary( (Dictionary<string,string>)value, builder );
}
else if( value is ArrayList )
{
serializeArray( (ArrayList)value, builder );
}
else if( ( value is Boolean ) && ( (Boolean)value == true ) )
{
builder.Append( "true" );
}
else if( ( value is Boolean ) && ( (Boolean)value == false ) )
{
builder.Append( "false" );
}
else if( value.GetType().IsPrimitive )
{
serializeNumber( Convert.ToDouble( value ), builder );
}
else
{
return false;
}
return true;
}
protected static void serializeString( string aString, StringBuilder builder )
{
builder.Append( "\"" );
char[] charArray = aString.ToCharArray();
for( int i = 0; i < charArray.Length; i++ )
{
char c = charArray[i];
if( c == '"' )
{
builder.Append( "\\\"" );
}
else if( c == '\\' )
{
builder.Append( "\\\\" );
}
else if( c == '\b' )
{
builder.Append( "\\b" );
}
else if( c == '\f' )
{
builder.Append( "\\f" );
}
else if( c == '\n' )
{
builder.Append( "\\n" );
}
else if( c == '\r' )
{
builder.Append( "\\r" );
}
else if( c == '\t' )
{
builder.Append( "\\t" );
}
else
{
int codepoint = Convert.ToInt32( c );
if( ( codepoint >= 32 ) && ( codepoint <= 126 ) )
{
builder.Append( c );
}
else
{
builder.Append( "\\u" + Convert.ToString( codepoint, 16 ).PadLeft( 4, '0' ) );
}
}
}
builder.Append( "\"" );
}
protected static void serializeNumber( double number, StringBuilder builder )
{
builder.Append( Convert.ToString( number ) ); // , CultureInfo.InvariantCulture));
}
#endregion
}
#region Extension methods
public static class MiniJsonExtensions
{
public static string encodeToJSON( this Hashtable obj )
{
return MiniJSON.jsonEncode( obj );
}
public static string toJson( this Dictionary<string,string> obj )
{
return MiniJSON.jsonEncode( obj );
}
public static ArrayList arrayListFromJson( this string json )
{
return MiniJSON.jsonDecode( json ) as ArrayList;
}
public static Hashtable hashtableFromJson( this string json )
{
return MiniJSON.jsonDecode( json ) as Hashtable;
}
}
#endregion
| |
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Xml;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Net;
using log4net.Appender;
using log4net.Util;
using log4net.Repository;
namespace log4net.Config
{
/// <summary>
/// Use this class to initialize the log4net environment using an Xml tree.
/// </summary>
/// <remarks>
/// <para>
/// Configures a <see cref="ILoggerRepository"/> using an Xml tree.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class XmlConfigurator
{
#region Private Instance Constructors
/// <summary>
/// Private constructor
/// </summary>
private XmlConfigurator()
{
}
#endregion Protected Instance Constructors
#region Configure static methods
#if !NETCF
/// <summary>
/// Automatically configures the log4net system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// <para>
/// To use this method to configure log4net you must specify
/// the <see cref="Log4NetConfigurationSectionHandler"/> section
/// handler for the <c>log4net</c> configuration section. See the
/// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
/// </para>
/// </remarks>
/// <seealso cref="Log4NetConfigurationSectionHandler"/>
#else
/// <summary>
/// Automatically configures the log4net system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// </remarks>
#endif
static public void Configure()
{
Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
}
#if !NETCF
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// <para>
/// To use this method to configure log4net you must specify
/// the <see cref="Log4NetConfigurationSectionHandler"/> section
/// handler for the <c>log4net</c> configuration section. See the
/// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
/// </para>
/// </remarks>
/// <param name="repository">The repository to configure.</param>
#else
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// </remarks>
/// <param name="repository">The repository to configure.</param>
#endif
static public void Configure(ILoggerRepository repository)
{
LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using .config file section");
try
{
LogLog.Debug("XmlConfigurator: Application config file is [" + SystemInfo.ConfigurationFileLocation + "]");
}
catch
{
// ignore error
LogLog.Debug("XmlConfigurator: Application config file location unknown");
}
#if NETCF
// No config file reading stuff. Just go straight for the file
Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation));
#else
try
{
XmlElement configElement = null;
#if NET_2_0
configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement;
#else
configElement = System.Configuration.ConfigurationSettings.GetConfig("log4net") as XmlElement;
#endif
if (configElement == null)
{
// Failed to load the xml config using configuration settings handler
LogLog.Error("XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />");
}
else
{
// Configure using the xml loaded from the config file
ConfigureFromXml(repository, configElement);
}
}
catch(System.Configuration.ConfigurationException confEx)
{
if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0)
{
// Looks like the XML file is not valid
LogLog.Error("XmlConfigurator: Failed to parse config file. Check your .config file is well formed XML.", confEx);
}
else
{
// This exception is typically due to the assembly name not being correctly specified in the section type.
string configSectionStr = "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler," + Assembly.GetExecutingAssembly().FullName + "\" />";
LogLog.Error("XmlConfigurator: Failed to parse config file. Is the <configSections> specified as: " + configSectionStr, confEx);
}
}
#endif
}
/// <summary>
/// Configures log4net using a <c>log4net</c> element
/// </summary>
/// <remarks>
/// <para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </para>
/// </remarks>
/// <param name="element">The element to parse.</param>
static public void Configure(XmlElement element)
{
ConfigureFromXml(LogManager.GetRepository(Assembly.GetCallingAssembly()), element);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified XML
/// element.
/// </summary>
/// <remarks>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </remarks>
/// <param name="repository">The repository to configure.</param>
/// <param name="element">The element to parse.</param>
static public void Configure(ILoggerRepository repository, XmlElement element)
{
LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using XML element");
ConfigureFromXml(repository, element);
}
#if !NETCF
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <para>
/// The first element matching <c><configuration></c> will be read as the
/// configuration. If this file is also a .NET .config file then you must specify
/// a configuration section for the <c>log4net</c> element otherwise .NET will
/// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
/// <code lang="XML" escaped="true">
/// <configSections>
/// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
/// </configSections>
/// </code>
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#else
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#endif
static public void Configure(FileInfo configFile)
{
Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
/// <summary>
/// Configures log4net using the specified configuration URI.
/// </summary>
/// <param name="configUri">A URI to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
/// </para>
/// </remarks>
static public void Configure(Uri configUri)
{
Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configUri);
}
/// <summary>
/// Configures log4net using the specified configuration data stream.
/// </summary>
/// <param name="configStream">A stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
static public void Configure(Stream configStream)
{
Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream);
}
#if !NETCF
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <para>
/// The first element matching <c><configuration></c> will be read as the
/// configuration. If this file is also a .NET .config file then you must specify
/// a configuration section for the <c>log4net</c> element otherwise .NET will
/// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
/// <code lang="XML" escaped="true">
/// <configSections>
/// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
/// </configSections>
/// </code>
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#else
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#endif
static public void Configure(ILoggerRepository repository, FileInfo configFile)
{
LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using file [" + configFile + "]");
if (configFile == null)
{
LogLog.Error("XmlConfigurator: Configure called with null 'configFile' parameter");
}
else
{
// Have to use File.Exists() rather than configFile.Exists()
// because configFile.Exists() caches the value, not what we want.
if (File.Exists(configFile.FullName))
{
// Open the file for reading
FileStream fs = null;
// Try hard to open the file
for(int retry = 5; --retry >= 0; )
{
try
{
fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
break;
}
catch(IOException ex)
{
if (retry == 0)
{
LogLog.Error("XmlConfigurator: Failed to open XML config file [" + configFile.Name + "]", ex);
// The stream cannot be valid
fs = null;
}
System.Threading.Thread.Sleep(250);
}
}
if (fs != null)
{
try
{
// Load the configuration from the stream
Configure(repository, fs);
}
finally
{
// Force the file closed whatever happens
fs.Close();
}
}
}
else
{
LogLog.Debug("XmlConfigurator: config file [" + configFile.FullName + "] not found. Configuration unchanged.");
}
}
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// URI.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configUri">A URI to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
/// </para>
/// </remarks>
static public void Configure(ILoggerRepository repository, Uri configUri)
{
LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using URI ["+configUri+"]");
if (configUri == null)
{
LogLog.Error("XmlConfigurator: Configure called with null 'configUri' parameter");
}
else
{
if (configUri.IsFile)
{
// If URI is local file then call Configure with FileInfo
Configure(repository, new FileInfo(configUri.LocalPath));
}
else
{
// NETCF dose not support WebClient
WebRequest configRequest = null;
try
{
configRequest = WebRequest.Create(configUri);
}
catch(Exception ex)
{
LogLog.Error("XmlConfigurator: Failed to create WebRequest for URI ["+configUri+"]", ex);
}
if (configRequest != null)
{
#if !NETCF
// authentication may be required, set client to use default credentials
try
{
configRequest.Credentials = CredentialCache.DefaultCredentials;
}
catch
{
// ignore security exception
}
#endif
try
{
WebResponse response = configRequest.GetResponse();
if (response != null)
{
try
{
// Open stream on config URI
using(Stream configStream = response.GetResponseStream())
{
Configure(repository, configStream);
}
}
finally
{
response.Close();
}
}
}
catch(Exception ex)
{
LogLog.Error("XmlConfigurator: Failed to request config from URI ["+configUri+"]", ex);
}
}
}
}
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configStream">The stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
static public void Configure(ILoggerRepository repository, Stream configStream)
{
LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using stream");
if (configStream == null)
{
LogLog.Error("XmlConfigurator: Configure called with null 'configStream' parameter");
}
else
{
// Load the config file into a document
XmlDocument doc = new XmlDocument();
try
{
#if (NETCF)
// Create a text reader for the file stream
XmlTextReader xmlReader = new XmlTextReader(configStream);
#elif NET_2_0
// Allow the DTD to specify entity includes
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
// Create a reader over the input stream
XmlReader xmlReader = XmlReader.Create(configStream, settings);
#else
// Create a validating reader around a text reader for the file stream
XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream));
// Specify that the reader should not perform validation, but that it should
// expand entity refs.
xmlReader.ValidationType = ValidationType.None;
xmlReader.EntityHandling = EntityHandling.ExpandEntities;
#endif
// load the data into the document
doc.Load(xmlReader);
}
catch(Exception ex)
{
LogLog.Error("XmlConfigurator: Error while loading XML configuration", ex);
// The document is invalid
doc = null;
}
if (doc != null)
{
LogLog.Debug("XmlConfigurator: loading XML configuration");
// Configure using the 'log4net' element
XmlNodeList configNodeList = doc.GetElementsByTagName("log4net");
if (configNodeList.Count == 0)
{
LogLog.Debug("XmlConfigurator: XML configuration does not contain a <log4net> element. Configuration Aborted.");
}
else if (configNodeList.Count > 1)
{
LogLog.Error("XmlConfigurator: XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted.");
}
else
{
ConfigureFromXml(repository, configNodeList[0] as XmlElement);
}
}
}
}
#endregion Configure static methods
#region ConfigureAndWatch static methods
#if (!NETCF && !SSCLI)
/// <summary>
/// Configures log4net using the file specified, monitors the file for changes
/// and reloads the configuration if a change is detected.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="Configure(FileInfo)"/>
static public void ConfigureAndWatch(FileInfo configFile)
{
ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the file specified,
/// monitors the file for changes and reloads the configuration if a change
/// is detected.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="Configure(FileInfo)"/>
static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates");
if (configFile == null)
{
LogLog.Error("XmlConfigurator: ConfigureAndWatch called with null 'configFile' parameter");
}
else
{
// Configure log4net now
Configure(repository, configFile);
try
{
// Create a watch handler that will reload the
// configuration whenever the config file is modified.
ConfigureAndWatchHandler.StartWatching(repository, configFile);
}
catch(Exception ex)
{
LogLog.Error("XmlConfigurator: Failed to initialize configuration file watcher for file ["+configFile.FullName+"]", ex);
}
}
}
#endif
#endregion ConfigureAndWatch static methods
#region ConfigureAndWatchHandler
#if (!NETCF && !SSCLI)
/// <summary>
/// Class used to watch config files.
/// </summary>
/// <remarks>
/// <para>
/// Uses the <see cref="FileSystemWatcher"/> to monitor
/// changes to a specified file. Because multiple change notifications
/// may be raised when the file is modified, a timer is used to
/// compress the notifications into a single event. The timer
/// waits for <see cref="TimeoutMillis"/> time before delivering
/// the event notification. If any further <see cref="FileSystemWatcher"/>
/// change notifications arrive while the timer is waiting it
/// is reset and waits again for <see cref="TimeoutMillis"/> to
/// elapse.
/// </para>
/// </remarks>
private sealed class ConfigureAndWatchHandler
{
/// <summary>
/// Watch a specified config file used to configure a repository
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The configuration file to watch.</param>
/// <remarks>
/// <para>
/// Watch a specified config file used to configure a repository
/// </para>
/// </remarks>
internal static void StartWatching(ILoggerRepository repository, FileInfo configFile)
{
new ConfigureAndWatchHandler(repository, configFile);
}
/// <summary>
/// Holds the FileInfo used to configure the XmlConfigurator
/// </summary>
private FileInfo m_configFile;
/// <summary>
/// Holds the repository being configured.
/// </summary>
private ILoggerRepository m_repository;
/// <summary>
/// The timer used to compress the notification events.
/// </summary>
private Timer m_timer;
/// <summary>
/// The default amount of time to wait after receiving notification
/// before reloading the config file.
/// </summary>
private const int TimeoutMillis = 500;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The configuration file to watch.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class.
/// </para>
/// </remarks>
private ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile)
{
m_repository = repository;
m_configFile = configFile;
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = m_configFile.DirectoryName;
watcher.Filter = m_configFile.Name;
// Set the notification filters
watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;
// Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs
watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Create the timer that will be used to deliver events. Set as disabled
m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// <para>
/// This handler reloads the configuration from the file when the event is fired.
/// </para>
/// </remarks>
private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e)
{
LogLog.Debug("ConfigureAndWatchHandler: "+e.ChangeType+" [" + m_configFile.FullName + "]");
// Deliver the event in TimeoutMillis time
// timer will fire only once
m_timer.Change(TimeoutMillis, Timeout.Infinite);
}
/// <summary>
/// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// <para>
/// This handler reloads the configuration from the file when the event is fired.
/// </para>
/// </remarks>
private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e)
{
LogLog.Debug("ConfigureAndWatchHandler: " + e.ChangeType + " [" + m_configFile.FullName + "]");
// Deliver the event in TimeoutMillis time
// timer will fire only once
m_timer.Change(TimeoutMillis, Timeout.Infinite);
}
/// <summary>
/// Called by the timer when the configuration has been updated.
/// </summary>
/// <param name="state">null</param>
private void OnWatchedFileChange(object state)
{
XmlConfigurator.Configure(m_repository, m_configFile);
}
}
#endif
#endregion ConfigureAndWatchHandler
#region Private Static Methods
/// <summary>
/// Configures the specified repository using a <c>log4net</c> element.
/// </summary>
/// <param name="repository">The hierarchy to configure.</param>
/// <param name="element">The element to parse.</param>
/// <remarks>
/// <para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </para>
/// <para>
/// This method is ultimately called by one of the Configure methods
/// to load the configuration from an <see cref="XmlElement"/>.
/// </para>
/// </remarks>
static private void ConfigureFromXml(ILoggerRepository repository, XmlElement element)
{
if (element == null)
{
LogLog.Error("XmlConfigurator: ConfigureFromXml called with null 'element' parameter");
}
else if (repository == null)
{
LogLog.Error("XmlConfigurator: ConfigureFromXml called with null 'repository' parameter");
}
else
{
LogLog.Debug("XmlConfigurator: Configuring Repository [" + repository.Name + "]");
IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator;
if (configurableRepository == null)
{
LogLog.Warn("XmlConfigurator: Repository [" + repository + "] does not support the XmlConfigurator");
}
else
{
// Copy the xml data into the root of a new document
// this isolates the xml config data from the rest of
// the document
XmlDocument newDoc = new XmlDocument();
XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true));
// Pass the configurator the config element
configurableRepository.Configure(newElement);
}
}
}
#endregion Private Static Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Xml.Schema;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_GlobalElements", Desc = "")]
public class TC_SchemaSet_GlobalElements : TC_SchemaSetBase
{
private ITestOutputHelper _output;
public TC_SchemaSet_GlobalElements(ITestOutputHelper output)
{
_output = output;
}
public XmlSchema GetSchema(string ns, string e1, string e2)
{
string xsd = string.Empty;
if (ns.Equals(string.Empty))
xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema'><element name='" + e1 + "'/><element name='" + e2 + "'/></schema>";
else
xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema' targetNamespace='" + ns + "'><element name='" + e1 + "'/><element name='" + e2 + "'/></schema>";
XmlSchema schema = XmlSchema.Read(new StringReader(xsd), null);
return schema;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - GlobalElements on empty collection", Priority = 0)]
[InlineData()]
[Theory]
public void v1()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaObjectTable table = sc.GlobalElements;
CError.Compare(table == null, false, "Count");
return;
}
// params is a pair of the following info: (namaespace, e2 e2) two schemas are made from this info
//[Variation(Desc = "v2.1 - GlobalElements with set with two schemas, both without NS", Params = new object[] { "", "e1", "e2", "", "e3", "e4" })]
[InlineData("", "e1", "e2", "", "e3", "e4")]
//[Variation(Desc = "v2.2 - GlobalElements with set with two schemas, one without NS one with NS", Params = new object[] { "a", "e1", "e2", "", "e3", "e4" })]
[InlineData("a", "e1", "e2", "", "e3", "e4")]
//[Variation(Desc = "v2.2 - GlobalElements with set with two schemas, both with NS", Params = new object[] { "a", "e1", "e2", "b", "e3", "e4" })]
[InlineData("a", "e1", "e2", "b", "e3", "e4")]
[Theory]
public void v2(object param0, object param1, object param2, object param3, object param4, object param5)
{
string ns1 = param0.ToString();
string ns2 = param3.ToString();
string e1 = param1.ToString();
string e2 = param2.ToString();
string e3 = param4.ToString();
string e4 = param5.ToString();
XmlSchema s1 = GetSchema(ns1, e1, e2);
XmlSchema s2 = GetSchema(ns2, e3, e4);
XmlSchemaSet ss = new XmlSchemaSet();
ss.Add(s1);
ss.Compile();
ss.Add(s2);
CError.Compare(ss.GlobalElements.Count, 2, "Elements Count after add"); //+1 for anyType
ss.Compile();
//Verify
CError.Compare(ss.GlobalElements.Count, 4, "Elements Count after add/compile");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e2, ns1)), true, "Contains2");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e3, ns2)), true, "Contains3");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e4, ns2)), true, "Contains4");
//Now reprocess one schema and check
ss.Reprocess(s1);
ss.Compile();
CError.Compare(ss.GlobalElements.Count, 4, "Elements Count after reprocess/compile");
//Now Remove one schema and check
ss.Remove(s1);
CError.Compare(ss.GlobalElements.Count, 2, "Elements Count after remove no compile");
ss.Compile();
CError.Compare(ss.GlobalElements.Count, 2, "Elements Count adter remove and compile");
return;
}
// params is a pair of the following info: (namaespace, e1 e2)*, doCompile?
//[Variation(Desc = "v3.1 - GlobalElements with a set having schema (nons) to another set with schema(nons)", Params = new object[] { "", "e1", "e2", "", "e3", "e4", true })]
[InlineData("", "e1", "e2", "", "e3", "e4", true)]
//[Variation(Desc = "v3.2 - GlobalElements with a set having schema (ns) to another set with schema(nons)", Params = new object[] { "a", "e1", "e2", "", "e3", "e4", true })]
[InlineData("a", "e1", "e2", "", "e3", "e4", true)]
//[Variation(Desc = "v3.3 - GlobalElements with a set having schema (nons) to another set with schema(ns)", Params = new object[] { "", "e1", "e2", "a", "e3", "e4", true })]
[InlineData("", "e1", "e2", "a", "e3", "e4", true)]
//[Variation(Desc = "v3.4 - GlobalElements with a set having schema (ns) to another set with schema(ns)", Params = new object[] { "a", "e1", "e2", "b", "e3", "e4", true })]
[InlineData("a", "e1", "e2", "b", "e3", "e4", true)]
//[Variation(Desc = "v3.5 - GlobalElements with a set having schema (nons) to another set with schema(nons), no compile", Params = new object[] { "", "e1", "e2", "", "e3", "e4", false })]
[InlineData("", "e1", "e2", "", "e3", "e4", false)]
//[Variation(Desc = "v3.6 - GlobalElements with a set having schema (ns) to another set with schema(nons), no compile", Params = new object[] { "a", "e1", "e2", "", "e3", "e4", false })]
[InlineData("a", "e1", "e2", "", "e3", "e4", false)]
//[Variation(Desc = "v3.7 - GlobalElements with a set having schema (nons) to another set with schema(ns), no compile", Params = new object[] { "", "e1", "e2", "a", "e3", "e4", false })]
[InlineData("", "e1", "e2", "a", "e3", "e4", false)]
//[Variation(Desc = "v3.8 - GlobalElements with a set having schema (ns) to another set with schema(ns), no compile", Params = new object[] { "a", "e1", "e2", "b", "e3", "e4", false })]
[InlineData("a", "e1", "e2", "b", "e3", "e4", false)]
[Theory]
public void v3(object param0, object param1, object param2, object param3, object param4, object param5, object param6)
{
string ns1 = param0.ToString();
string ns2 = param3.ToString();
string e1 = param1.ToString();
string e2 = param2.ToString();
string e3 = param4.ToString();
string e4 = param5.ToString();
bool doCompile = (bool)param6;
XmlSchema s1 = GetSchema(ns1, e1, e2);
XmlSchema s2 = GetSchema(ns2, e3, e4);
XmlSchemaSet ss1 = new XmlSchemaSet();
XmlSchemaSet ss2 = new XmlSchemaSet();
ss1.Add(s1);
ss1.Compile();
ss2.Add(s2);
if (doCompile)
ss2.Compile();
// add one schemaset to another
ss1.Add(ss2);
if (!doCompile)
ss1.Compile();
//Verify
CError.Compare(ss1.GlobalElements.Count, 4, "Types Count after add, compile,add");
CError.Compare(ss1.GlobalElements.Contains(new XmlQualifiedName(e1, ns1)), true, "Contains1");
CError.Compare(ss1.GlobalElements.Contains(new XmlQualifiedName(e2, ns1)), true, "Contains2");
CError.Compare(ss1.GlobalElements.Contains(new XmlQualifiedName(e3, ns2)), true, "Contains3");
CError.Compare(ss1.GlobalElements.Contains(new XmlQualifiedName(e4, ns2)), true, "Contains4");
//Now reprocess one schema and check
ss1.Reprocess(s1);
ss1.Compile();
CError.Compare(ss1.GlobalElements.Count, 4, "Types Count after reprocess/compile");
//Now Remove one schema and check
ss1.Remove(s1);
CError.Compare(ss1.GlobalElements.Count, 2, "Types Count after remove"); // count should still be 4
ss1.Compile();
CError.Compare(ss1.GlobalElements.Count, 2, "Types Count after remove/comp"); // count should NOW still be 2
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v4.1 - GlobalElements with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "e1", "", "e2" })]
[InlineData("import_v1_a.xsd", "ns-a", "e1", "", "e2")]
//[Variation(Desc = "v4.2 - GlobalElements with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "e1", "ns-b", "e2" })]
[InlineData("import_v2_a.xsd", "ns-a", "e1", "ns-b", "e2")]
[Theory]
public void v4(object param0, object param1, object param2, object param3, object param4)
{
string uri1 = param0.ToString();
string ns1 = param1.ToString();
string e1 = param2.ToString();
string ns2 = param3.ToString();
string e2 = param4.ToString();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1));
ss.Compile();
CError.Compare(ss.GlobalElements.Count, 3, "Types Count after add"); // +1 for root in ns-a
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e2, ns2)), true, "Contains2");
//get the SOM for the imported schema
foreach (XmlSchema s in ss.Schemas(ns2))
{
ss.Remove(s);
}
ss.Compile();
CError.Compare(ss.GlobalElements.Count, 2, "Types Count after Remove");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e2, ns2)), false, "Contains2");
return;
}
//[Variation(Desc = "v5.1 - GlobalElements with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "e1", "", "e2" })]
[InlineData("import_v1_a.xsd", "ns-a", "e1", "", "e2")]
//[Variation(Desc = "v5.2 - GlobalElements with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "e1", "ns-b", "e2" })]
[InlineData("import_v2_a.xsd", "ns-a", "e1", "ns-b", "e2")]
[Theory]
public void v5(object param0, object param1, object param2, object param3, object param4)
{
string uri1 = param0.ToString();
string ns1 = param1.ToString();
string e1 = param2.ToString();
string ns2 = param3.ToString();
string e2 = param4.ToString();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd"));
XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1));
ss.Compile();
CError.Compare(ss.GlobalElements.Count, 4, "Types Count"); // +1 for root in ns-a and xsdauthor
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e2, ns2)), true, "Contains2");
ss.RemoveRecursive(schema1); // should not need to compile for RemoveRecursive to take effect
CError.Compare(ss.GlobalElements.Count, 1, "Types Count");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e1, ns1)), false, "Contains1");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e2, ns2)), false, "Contains2");
return;
}
//[Variation(Desc = "v6 - GlobalElements with set with two schemas, second schema will fail to compile, no elements from it should be added", Params = new object[] { "", "e1", "e2" })]
[InlineData("", "e1", "e2")]
[Theory]
public void v6(object param0, object param1, object param2)
{
string ns1 = param0.ToString();
string e1 = param1.ToString();
string e2 = param2.ToString();
XmlSchema s1 = GetSchema(ns1, e1, e2);
XmlSchema s2 = XmlSchema.Read(new StreamReader(new FileStream(Path.Combine(TestData._Root, "invalid.xsd"), FileMode.Open, FileAccess.Read)), null);
XmlSchemaSet ss = new XmlSchemaSet();
ss.Add(s1);
ss.Compile();
ss.Add(s2);
CError.Compare(ss.GlobalElements.Count, 2, "Elements Count"); //+1 for anyType
try
{
ss.Compile();
}
catch (XmlSchemaException)
{
//Verify
CError.Compare(ss.GlobalElements.Count, 2, "Elements Count after compile");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalElements.Contains(new XmlQualifiedName(e2, ns1)), true, "Contains2");
return;
}
Assert.True(false);
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.PythonTools.Analysis;
namespace Microsoft.PythonTools.Parsing.Ast {
/// <summary>
/// Top-level ast for all Python code. Holds onto the body and the line mapping information.
/// </summary>
public sealed class PythonAst : ScopeStatement, ILocationResolver {
private readonly PythonLanguageVersion _langVersion;
private readonly Statement _body;
internal readonly int[] _lineLocations;
private readonly Dictionary<Node, Dictionary<object, object>> _attributes = new Dictionary<Node, Dictionary<object, object>>();
private string _privatePrefix;
public PythonAst(Statement body, int[] lineLocations, PythonLanguageVersion langVersion) {
if (body == null) {
throw new ArgumentNullException("body");
}
_langVersion = langVersion;
_body = body;
_lineLocations = lineLocations;
}
public override string Name {
get {
return "<module>";
}
}
/// <summary>
/// Gets the class name which this AST was parsed under. The class name is appended to any member
/// accesses that occur.
/// </summary>
public string PrivatePrefix {
get {
return _privatePrefix;
}
internal set {
_privatePrefix = value;
}
}
/// <summary>
/// True if the AST was created with verbatim strings.
/// </summary>
public bool HasVerbatim { get; internal set; }
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
_body.Walk(walker);
}
walker.PostWalk(this);
}
public override Statement Body {
get { return _body; }
}
public PythonLanguageVersion LanguageVersion {
get { return _langVersion; }
}
internal bool TryGetAttribute(Node node, object key, out object value) {
Dictionary<object, object> nodeAttrs;
if (_attributes.TryGetValue(node, out nodeAttrs)) {
return nodeAttrs.TryGetValue(key, out value);
} else {
value = null;
}
return false;
}
internal void SetAttribute(Node node, object key, object value) {
Dictionary<object, object> nodeAttrs;
if (!_attributes.TryGetValue(node, out nodeAttrs)) {
nodeAttrs = _attributes[node] = new Dictionary<object, object>();
}
nodeAttrs[key] = value;
}
/// <summary>
/// Copies attributes that apply to one node and makes them available for the other node.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
public void CopyAttributes(Node from, Node to) {
Dictionary<object, object> nodeAttrs;
if (_attributes.TryGetValue(from, out nodeAttrs)) {
_attributes[to] = new Dictionary<object, object>(nodeAttrs);
}
}
internal SourceLocation IndexToLocation(int index) {
if (index == -1) {
return SourceLocation.Invalid;
}
var locs = GlobalParent._lineLocations;
int match = Array.BinarySearch(locs, index);
if (match < 0) {
// If our index = -1, it means we're on the first line.
if (match == -1) {
return new SourceLocation(index, 1, index + 1);
}
// If we couldn't find an exact match for this line number, get the nearest
// matching line number less than this one
match = ~match - 1;
}
return new SourceLocation(index, match + 2, index - locs[match] + 1);
}
#region Name Binding Support
internal override bool ExposesLocalVariable(PythonVariable variable) {
return true;
}
internal override void FinishBind(PythonNameBinder binder) {
}
internal override PythonVariable BindReference(PythonNameBinder binder, string name) {
return EnsureVariable(name);
}
internal override bool TryBindOuter(ScopeStatement from, string name, bool allowGlobals, out PythonVariable variable) {
if (allowGlobals) {
// Unbound variable
from.AddReferencedGlobal(name);
if (from.HasLateBoundVariableSets) {
// If the context contains unqualified exec, new locals can be introduced
// Therefore we need to turn this into a fully late-bound lookup which
// happens when we don't have a PythonVariable.
variable = null;
return false;
} else {
// Create a global variable to bind to.
variable = EnsureGlobalVariable(name);
return true;
}
}
variable = null;
return false;
}
internal override bool IsGlobal {
get { return true; }
}
/// <summary>
/// Creates a variable at the global level. Called for known globals (e.g. __name__),
/// for variables explicitly declared global by the user, and names accessed
/// but not defined in the lexical scope.
/// </summary>
internal PythonVariable/*!*/ EnsureGlobalVariable(string name) {
PythonVariable variable;
if (!TryGetVariable(name, out variable)) {
variable = CreateVariable(name, VariableKind.Global);
}
return variable;
}
internal PythonVariable/*!*/ EnsureNonlocalVariable(string name) {
PythonVariable variable;
if (!TryGetVariable(name, out variable)) {
variable = CreateVariable(name, VariableKind.Nonlocal);
}
return variable;
}
#endregion
internal override void AppendCodeStringStmt(StringBuilder res, PythonAst ast, CodeFormattingOptions format) {
_body.AppendCodeString(res, ast, format);
res.Append(this.GetExtraVerbatimText(ast));
}
#region ILocationResolver Members
LocationInfo ILocationResolver.ResolveLocation(IProjectEntry project, object location) {
Node node = (Node)location;
MemberExpression me = node as MemberExpression;
SourceSpan span;
if (me != null) {
span = me.GetNameSpan(this);
} else {
span = node.GetSpan(this);
}
return new LocationInfo(project, span.Start.Line, span.Start.Column);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available.
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = null;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = 64 * 1024;
private int _maxResponseDrainSize = 64 * 1024;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName);
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => ((WinHttpRequestState)s).Handler.StartRequest(s),
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
s_diagnosticListener.LogHttpResponse(tcs.Task, loggingRequestId);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (cookies != null)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO (#5523): Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
SafeWinHttpHandle sessionHandle;
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType);
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError);
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
SetSessionHandleOptions(sessionHandle);
_sessionHandle = sessionHandle;
}
}
}
}
private async void StartRequest(object obj)
{
WinHttpRequestState state = (WinHttpRequestState)obj;
bool secureConnection = false;
HttpResponseMessage responseMessage = null;
Exception savedException = null;
SafeWinHttpHandle connectHandle = null;
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
try
{
EnsureSessionHandleExists(state);
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
secureConnection = true;
}
else
{
secureConnection = false;
}
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersion.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersion.Version11)
{
httpVersion = "HTTP/1.1";
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state).ConfigureAwait(false);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state).ConfigureAwait(false);
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = (uint)_receiveDataTimeout.TotalMilliseconds;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
}
catch (Exception ex)
{
if (state.SavedException != null)
{
savedException = state.SavedException;
}
else
{
savedException = ex;
}
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
// Move the main task to a terminal state. This releases any callers of SendAsync() that are awaiting.
if (responseMessage != null)
{
state.Tcs.TrySetResult(responseMessage);
}
else
{
HandleAsyncException(state, savedException);
}
state.ClearSendRequestState();
}
}
private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle)
{
SetSessionHandleConnectionOptions(sessionHandle);
SetSessionHandleTlsOptions(sessionHandle);
SetSessionHandleTimeoutOptions(sessionHandle);
}
private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = 0;
SslProtocols sslProtocols =
(_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols;
if ((sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle)
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
sessionHandle,
0,
0,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = string.Format(
CultureInfo.InvariantCulture,
"{0}://{1}",
proxyUri.Scheme,
proxyUri.Authority);
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
{
updateProxySettings = true;
}
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials
// (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends
// default credentials to a server (401 response) if the server is considered to be on the Intranet.
// WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between
// proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in
// the request processing (after getting a 401/407 response) when the proxy or server credential is set as
// CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials
// from being automatically sent until we get a 401/407 response.
_authHelper.ChangeDefaultCredentialsPolicy(
state.RequestHandle,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER,
allowDefaultCredentials:false);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)_maxResponseHeadersLength;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST;
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
notificationFlags,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.ThrowOnInvalidHandle: error={0}", lastError);
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
private Task<bool> InternalSendRequestAsync(WinHttpRequestState state)
{
state.TcsSendRequest = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
state.Pin();
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
// Dispose (which will unpin) the state object. Since this failed, WinHTTP won't associate
// our context value (state object) to the request handle. And thus we won't get HANDLE_CLOSING
// notifications which would normally cause the state object to be unpinned and disposed.
state.Dispose();
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.TcsSendRequest.Task;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private Task<bool> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
state.TcsReceiveResponseHeaders =
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.TcsReceiveResponseHeaders.Task;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
#if !netstandard
using Internal.Runtime.CompilerServices;
#endif
#if !netstandard11
using System.Numerics;
#endif
namespace System
{
internal static partial class SpanHelpers
{
public static unsafe int SequenceCompareTo(ref char first, int firstLength, ref char second, int secondLength)
{
Debug.Assert(firstLength >= 0);
Debug.Assert(secondLength >= 0);
int lengthDelta = firstLength - secondLength;
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr minLength = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength);
IntPtr i = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
if ((byte*)minLength >= (byte*)(sizeof(UIntPtr) / sizeof(char)))
{
#if !netstandard11
if (Vector.IsHardwareAccelerated && (byte*)minLength >= (byte*)Vector<ushort>.Count)
{
IntPtr nLength = minLength - Vector<ushort>.Count;
do
{
if (Unsafe.ReadUnaligned<Vector<ushort>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref first, i))) !=
Unsafe.ReadUnaligned<Vector<ushort>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref second, i))))
{
break;
}
i += Vector<ushort>.Count;
}
while ((byte*)nLength >= (byte*)i);
}
#endif
while ((byte*)minLength >= (byte*)(i + sizeof(UIntPtr) / sizeof(char)))
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref first, i))) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref second, i))))
{
break;
}
i += sizeof(UIntPtr) / sizeof(char);
}
}
if (sizeof(UIntPtr) > sizeof(int) && (byte*)minLength >= (byte*)(i + sizeof(int) / sizeof(char)))
{
if (Unsafe.ReadUnaligned<int>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref first, i))) ==
Unsafe.ReadUnaligned<int>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref second, i))))
{
i += sizeof(int) / sizeof(char);
}
}
while ((byte*)i < (byte*)minLength)
{
int result = Unsafe.Add(ref first, i).CompareTo(Unsafe.Add(ref second, i));
if (result != 0)
return result;
i += 1;
}
Equal:
return lengthDelta;
}
public static unsafe int IndexOf(ref char searchSpace, char value, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars;
char* pEndCh = pCh + length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
int unaligned = ((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte;
length = ((Vector<ushort>.Count - unaligned) & (Vector<ushort>.Count - 1));
}
SequentialScan:
#endif
while (length >= 4)
{
length -= 4;
if (*pCh == value)
goto Found;
if (*(pCh + 1) == value)
goto Found1;
if (*(pCh + 2) == value)
goto Found2;
if (*(pCh + 3) == value)
goto Found3;
pCh += 4;
}
while (length > 0)
{
length -= 1;
if (*pCh == value)
goto Found;
pCh += 1;
}
#if !netstandard11
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh < pEndCh)
{
length = (int)((pEndCh - pCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> vComparison = new Vector<ushort>(value);
while (length > 0)
{
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned
Debug.Assert(((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vMatches = Vector.Equals(vComparison, Unsafe.Read<Vector<ushort>>(pCh));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh += Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
// Find offset of first match
return (int)(pCh - pChars) + LocateFirstFoundChar(vMatches);
}
if (pCh < pEndCh)
{
length = (int)(pEndCh - pCh);
goto SequentialScan;
}
}
#endif
return -1;
Found3:
pCh++;
Found2:
pCh++;
Found1:
pCh++;
Found:
return (int)(pCh - pChars);
}
}
public static unsafe int LastIndexOf(ref char searchSpace, char value, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars + length;
char* pEndCh = pChars;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
length = (((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte);
}
SequentialScan:
#endif
while (length >= 4)
{
length -= 4;
pCh -= 4;
if (*(pCh + 3) == value)
goto Found3;
if (*(pCh + 2) == value)
goto Found2;
if (*(pCh + 1) == value)
goto Found1;
if (*pCh == value)
goto Found;
}
while (length > 0)
{
length -= 1;
pCh -= 1;
if (*pCh == value)
goto Found;
}
#if !netstandard11
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh > pEndCh)
{
length = (int)((pCh - pEndCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> vComparison = new Vector<ushort>(value);
while (length > 0)
{
char* pStart = pCh - Vector<ushort>.Count;
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh (and hence pSart) is always vector aligned
Debug.Assert(((int)pStart & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vMatches = Vector.Equals(vComparison, Unsafe.Read<Vector<ushort>>(pStart));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh -= Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
// Find offset of last match
return (int)(pStart - pEndCh) + LocateLastFoundChar(vMatches);
}
if (pCh > pEndCh)
{
length = (int)(pCh - pEndCh);
goto SequentialScan;
}
}
#endif
return -1;
Found:
return (int)(pCh - pEndCh);
Found1:
return (int)(pCh - pEndCh) + 1;
Found2:
return (int)(pCh - pEndCh) + 2;
Found3:
return (int)(pCh - pEndCh) + 3;
}
}
#if !netstandard11
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundChar(Vector<ushort> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = 0;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i < Vector<ulong>.Count; i++)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 4 + LocateFirstFoundChar(candidate);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundChar(ulong match)
{
unchecked
{
// Flag least significant power of two bit
var powerOfTwoFlag = match ^ (match - 1);
// Shift all powers of two into the high byte and extract
return (int)((powerOfTwoFlag * XorPowerOfTwoToHighChar) >> 49);
}
}
private const ulong XorPowerOfTwoToHighChar = (0x03ul |
0x02ul << 16 |
0x01ul << 32) + 1;
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundChar(Vector<ushort> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = Vector<ulong>.Count - 1;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i >= 0; i--)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 4 + LocateLastFoundChar(candidate);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundChar(ulong match)
{
// Find the most significant char that has its highest bit set
int index = 3;
while ((long)match > 0)
{
match = match << 16;
index--;
}
return index;
}
#endif
}
}
| |
using Core.Common.MVVM.ViewModel;
using Core.Common.Reflect;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
namespace Core.Common.MVVM
{
public class ITypeService
{
[Import]
IReflectionService ReflectionService { get; set; }
}
public class IInternatializationService
{
[Import]
ITypeService TypeService { get; set; }
public string Translate(string uri, object item) { return "no translation"; }
}
/// <summary>
/// Base class for basic view models.
///
/// Properties which are of type colleciton are automatically injected with Observable Collections when Get is called
/// Commands marked with CommandAttribute are automatically added to CommandList
///
/// </summary>
public abstract class ViewModelBase : BasePropertyObject,
IViewModel,
IViewManager,
ISearchable,
IPartImportsSatisfiedNotification
{
private PropertySetterDelegate innerSetter;
private PropertyGetterDelegate innerGetter;
private CommandProvider commandProvider;
private ResourceProvider resourceProvider;
private IDispatcher dispatcher;
[Import]
public CommandProvider Commands { get { return commandProvider; } set { commandProvider = value; value.Context = this; } }
[Import]
public ResourceProvider Resources
{
get { return resourceProvider; }
set { resourceProvider = value; resourceProvider.Context = this; }
}
[Import]
public IViewModelProvider ViewModelProvider { get; set; }
[Import]
public IViewManager ViewManager { get; set; }
[Import]
public IDispatcher Dispatcher
{
get { return dispatcher; }
set
{
this.dispatcher = value;
setter = new DispatchingSetter(innerSetter, value);
}
}
public void Dispatch(Action action)
{
Dispatcher.Dispatch(action);
}
protected MessageViewModel NotifyUser(string title, string message)
{
var vm = ViewModelProvider.Require<MessageViewModel>();
vm.Title = title;
vm.Message = message;
ViewManager.ShowView(vm);
return vm;
}
private SubscriptionProvider subscriptions;
[Import]
SubscriptionProvider Subscriptions
{
get { return subscriptions; }
set
{
subscriptions = value;
if (value != null) { value.Context = this; }
}
}
public Subscription Subscribe(string propertyName, Action<object> action)
{
return subscriptions.Subscribe(propertyName, action);
}
void RegisterDependees()
{
var properties = GetType().PropertiesWith<DependsOnAttribute>();
foreach (var property in properties)
{
var info = property.Item1;
foreach (var attr in info.GetCustomAttributes<DependsOnAttribute>())
{
Subscribe(attr.PropertyName, val => RaisePropertyChanged(info.Name));
}
}
}
protected virtual IViewHandle ShowCustomView(object viewModel)
{
return null;
}
public IViewHandle ShowView(object viewModel)
{
var customView = ShowCustomView(viewModel);
if (customView != null) return customView;
return ViewManager.ShowView(viewModel);
}
public ViewModelBase()
{
innerSetter = setter;
innerGetter = getter;
getter = new ObservableCollectionGetter(getter, setter);
dispose = DoDispose;
}
private void DoDispose(object @object)
{
OnDispose();
}
public abstract void OnAfterConstruction();
public abstract void OnDispose();
public void OnImportsSatisfied()
{
RegisterDependees();
this.Subscribe(m => m.Model, OnModelChanged);
OnAfterConstruction();
}
protected virtual void OnModelChanged(object @object) { }
public virtual object Model
{
get
{
return Get<object>();
}
set
{
Set(value);
}
}
private IDictionary<Tuple<object, Type, string>, IViewModel> children = new Dictionary<Tuple<object, Type, string>, IViewModel>();
public T GetChild<T>(object value, string viewModelContract = null) where T : class,IViewModel
{
return GetChild(value, typeof(T), viewModelContract) as T;
}
public T RequireChild<T>(object value = null, string viewModelContract = null) where T : class,IViewModel
{
return RequireChild(value, typeof(T), viewModelContract) as T;
}
public IViewModel RequireChild(object value, Type viewModelType = null, string viewModelContract = null)
{
lock (children)
{
var key = Tuple.Create(value, viewModelType, viewModelContract);
if (children.ContainsKey(key)) return children[key];
var viewModel = CreateChild(value, viewModelType, viewModelContract);
children[key] = viewModel;
return viewModel;
}
}
public IViewModel GetChild(object value, Type viewModelType = null, string viewModelContract = null)
{
lock (children)
{
var key = Tuple.Create(value, viewModelType, viewModelContract);
if (!children.ContainsKey(key)) return null;
return children[key];
}
}
public IViewModel CreateChild(object value, Type viewModelType = null, string viewModelContract = null)
{
var modelType = value == null ? null : value.GetType();
// find viewmodel by comparing metadata to input
var viewModel = ViewModelProvider.RequireViewModel(metadata =>
{
if (modelType != null && modelType == metadata.ModelType) return true;
if (viewModelType != null && viewModelType == metadata.ViewModelType) return true;
if (!string.IsNullOrEmpty(viewModelContract) && viewModelContract == metadata.Contract) return true;
return false;
}) as IViewModel;
// setup connections
viewModel.Model = value;
viewModel.Parent = this;
return viewModel;
}
public virtual IViewModel Parent
{
get;
set;
}
public virtual IEnumerable<SearchTerm> SearchTerms
{
get
{
var searchable = Model as ISearchable;
if (searchable == null) return new SearchTerm[0];
return searchable.SearchTerms;
}
}
public ViewHandle ViewHandle { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Irony.Interpreter;
using Irony.Parsing;
using iSukces.Code.AutoCode;
using iSukces.Code.Interfaces;
/*
using AutoCodeGeneratorContextExtensions = iSukces.Code.AutoCode.AutoCodeGeneratorContextExtensions;
using IAutoCodeGeneratorContext = iSukces.Code.AutoCode.IAutoCodeGeneratorContext;
*/
namespace iSukces.Code.Irony
{
public partial class IronyAutocodeGenerator
{
public IronyAutocodeGenerator(GrammarNames names) => Cfg.Names = names;
private static string GetDebugFromRule(NonTerminalInfo i, ITypeNameResolver res,
IronyAutocodeGeneratorModel cfg)
{
string ff(ICsExpression src, string begin = null, string end = null)
{
if (!(src is ITokenNameSource tns)) return null;
var w = cfg.GetAstTypesInfoDelegate(tns)?.Invoke(res);
if (w is null)
return null;
var s = $"{w.AstType}, {w.DataType}".Trim();
if (string.IsNullOrEmpty(s))
return s;
return begin + s + end;
}
var debug = "rule = " + i.Rule?.GetType();
switch (i.Rule)
{
case RuleBuilder.Alternative alternative:
var alts = alternative.GetAlternatives()
.Select(a => a.GetCode(res));
debug = "rule = alternative: " + string.Join(", ", alts);
break;
/*
case RuleBuilder.ListAlternative listAlternative:
break;
case RuleBuilder.OptionAlternative optionAlternative:
break;
*/
case RuleBuilder.BinaryRule binaryRule:
break;
case RuleBuilder.PlusOrStar plusOrStar:
if ((plusOrStar.Options & TermListOptions2.AllowEmpty) != 0)
debug = "zero or more";
else
debug = "one or more";
debug += " " + plusOrStar.Element.GetTokenName().GetCode(res);
debug += ff(plusOrStar.Element.GetTokenName());
break;
case RuleBuilder.SequenceRule sequenceRule:
debug = "";
if ((sequenceRule.Map?.Count ?? 0) > 0)
foreach (var ii in sequenceRule.Map)
{
var q = sequenceRule.Expressions[ii.RuleItemIndex];
if (debug.Length > 0)
debug += ", ";
debug += q.Expression.GetCode(res) + " " + ff(q.Expression, " [", "]");
}
debug = "sequence of " + debug;
break;
}
return debug;
}
private static string OptimalJoin(IReadOnlyList<string> items) => string.Join("\r\n | ", items);
public void Generate(IAutoCodeGeneratorContext context)
{
foreach (var i in Cfg.NonTerminals)
if (i.AstBaseClassTypeName is null)
i.AstBaseClassTypeName = new TypeNameProvider(Cfg.DefaultAstBaseClass);
var fullClassName = Cfg.Names.GrammarType.FullName;
_grammarClass = context.GetOrCreateClass(fullClassName,
CsNamespaceMemberKind.Class);
_grammarClass.WithBaseClass(_grammarClass.Owner.GetTypeName<InterpretedLanguageGrammar>());
var initCode = Add_Fields()
.Where(a => a != null)
.ToArray();
Add_AutoInit(initCode);
var astClassesGenerator = new AstClassesGenerator(context, Cfg);
astClassesGenerator.Add_AstClasses();
Add_AstInterfaces(context);
new DataClassesGenerator(context, Cfg).Add_DataClasses();
if (Cfg.DoEvaluateHelper != null)
astClassesGenerator.Update(Cfg.DoEvaluateHelper);
}
public SequenceRuleBuilder GetSequenceRuleBuilder() =>
new SequenceRuleBuilder
{
ProcessToken = Cfg.GetAstTypesInfoDelegate,
GetTokenInfoByName = Cfg.GetTokenInfoByName
};
public IronyAutocodeGenerator With(string terminalName, Action<NonTerminalInfo> process = null)
{
var info = NonTerminalInfo.Parse(terminalName);
return With(info, process);
}
public IronyAutocodeGenerator With(NonTerminalInfo info, Action<NonTerminalInfo> process = null)
{
if (process != null)
process(info);
Cfg.NonTerminals.Add(info);
return this;
}
public IronyAutocodeGenerator With(params NonTerminalInfo[] infos)
{
Cfg.NonTerminals.AddRange(infos);
return this;
}
private void Add_AstInterfaces(IAutoCodeGeneratorContext context)
{
foreach (var info in Cfg.NonTerminals)
switch (info.Rule)
{
case null:
continue;
case RuleBuilder.Alternative altRule:
var ip = altRule.AlternativeInterfaceName;
if (ip.IsInterface && ip.CreateAutoCode)
{
var pn = ip.Provider.GetTypeName(context.FileLevelResolver, Cfg.Names.AstNamespace);
var iface = context.GetOrCreateClass(pn.Name,
CsNamespaceMemberKind.Interface);
iface.Description = altRule.GetDesc();
iface.Visibility = Visibilities.Public;
}
break;
case RuleBuilder.BinaryRule binaryRule:
break;
case RuleBuilder.PlusOrStar plus:
break;
case RuleBuilder.SequenceRule sequenceRule:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void Add_AutoInit(FieldCreationInfo[] initCode)
{
var code = CsCodeWriter.Create<IronyAutocodeGenerator>();
if (initCode.Any())
{
code.WriteLine("// init 1");
foreach (var i in initCode)
{
code.WriteLine($"{i.FieldName} = {i.SetValueCode};");
if (i.OtherCode == null || !i.OtherCode.Any()) continue;
foreach (var oc in i.OtherCode) code.WriteLine(oc);
}
}
code.WriteLine("// == init Terminals");
if (Cfg.Terminals.Any())
foreach (var i in Cfg.Terminals)
{
var fieldName = i.Name.GetCode(_grammarClass);
code.WriteLine($"{fieldName} = ToTerm({i.Code.CsEncode()});");
}
code.WriteLine("// == init NonTerminals");
foreach (var i in Cfg.NonTerminals)
{
var fieldName = i.Name.GetCode(_grammarClass);
var rule = i.Rule?.GetCode(_grammarClass);
if (string.IsNullOrEmpty(rule)) continue;
code.WriteLine($"{fieldName}.Rule = {rule};");
}
// add brackets
if (Cfg.BracketsPairs.Any())
{
code.WriteLine("// == brackets");
foreach (var i in Cfg.BracketsPairs)
{
var ab = new CsArgumentsBuilder()
.AddValue(i.Item1)
.AddValue(i.Item2);
code.WriteLine(ab.CallMethod("RegisterBracePair", true));
}
}
void Add(TerminalsList x, string method, string title)
{
if (!x.Any()) return;
code.WriteLine("// == mark " + title);
var ab = new CsArgumentsBuilder();
foreach (var i in x)
ab.AddValue(i.Code);
code.WriteLine(ab.CallMethod(method, true));
code.WriteLine();
}
Add(Cfg.ReservedWords, "MarkReservedWords", "reserved words");
Add(Cfg.Punctuations, "MarkPunctuation", "punctuations");
if (Cfg.SingleLineComment != null)
code.WriteLine($"NonGrammarTerminals.Add({Cfg.SingleLineComment.Name});");
if (Cfg.DelimitedComment != null)
code.WriteLine($"NonGrammarTerminals.Add({Cfg.DelimitedComment.Name});");
if (Cfg.Root != null) code.WriteLine("Root = " + Cfg.Root.Name.GetCode(_grammarClass) + ";");
_grammarClass.AddMethod("AutoInit", "void")
.WithBody(code);
}
private IEnumerable<FieldCreationInfo> Add_Fields()
{
var fields = new List<CsClassField>();
FieldCreationInfo MakeFromFactory<T>(SpecialTerminalKind key, string methodName)
{
if (!Cfg.SpecialTerminals.TryGetValue(key, out var name)) return null;
var tn = _grammarClass.GetTypeName<T>();
var factory = _grammarClass.GetTypeName(typeof(TerminalFactory));
var constValue = $"{factory}.{methodName}({name.CsEncode()})";
var field = new CsClassField(new TokenName(name).GetCode(_grammarClass),
tn); //.WithConstValue(constValue);
fields.Add(field);
field.UserAnnotations["o"] = 1;
if (key == SpecialTerminalKind.CreateCSharpNumber)
if (Cfg.CSharpNumberLiteralOptions != NumberOptions.None)
{
var code = _grammarClass.GetEnumFlagsValueCode(Cfg.CSharpNumberLiteralOptions, OptimalJoin);
code = field.Name + ".Options = " + code + ";";
return new FieldCreationInfo(field.Name, constValue, code);
}
return new FieldCreationInfo(field.Name, constValue);
}
yield return MakeFromFactory<IdentifierTerminal>(SpecialTerminalKind.CreateCSharpIdentifier,
"CreateCSharpIdentifier");
yield return MakeFromFactory<StringLiteral>(SpecialTerminalKind.CreateCSharpString, "CreateCSharpString");
yield return MakeFromFactory<NumberLiteral>(SpecialTerminalKind.CreateCSharpNumber, "CreateCSharpNumber");
Cfg.SingleLineComment?.AddTo(_grammarClass);
Cfg.DelimitedComment?.AddTo(_grammarClass);
var tnKeyTerm = _grammarClass.GetTypeName<KeyTerm>();
foreach (var i in Cfg.Terminals)
{
var field = new CsClassField(i.Name.GetCode(_grammarClass), tnKeyTerm);
field.UserAnnotations["o"] = 2;
fields.Add(field);
}
var tnNonTerminal = _grammarClass.GetTypeName<NonTerminal>();
foreach (var i in Cfg.NonTerminals)
{
ITypeNameProvider astClassNameSrc; // ? i.AstClassTypeName2 : i.AstBaseClassTypeName;
if (i.AstClass.BuiltInOrAutocode)
astClassNameSrc = i.AstClass.Provider;
else
astClassNameSrc = i.AstBaseClassTypeName;
var astClassName = astClassNameSrc.GetTypeName(_grammarClass, Cfg.Names.AstNamespace)?.Name;
/*
if (astClassName.StartsWith("."))
astClassName = Cfg.TargetNamespace + astClassName;
*/
var args = new CsArgumentsBuilder()
.AddValue(i.Name.Name);
var skip = string.IsNullOrEmpty(astClassName)
|| NestedGeneratorBase.SkipCreateClass(i);
if (!skip)
args.AddCode($"typeof({astClassName})");
var constValue = $"new {tnNonTerminal}{args.CodeEx}";
var field = new CsClassField(i.Name.GetCode(_grammarClass), tnNonTerminal);
field.UserAnnotations["o"] = 3;
fields.Add(field);
yield return new FieldCreationInfo(field.Name, constValue);
}
foreach (var field in fields
.OrderBy(a =>
{
var ord = (int)a.UserAnnotations["o"];
return ord;
})
.ThenBy(a => a.Name))
{
field.Visibility = Visibilities.Private;
_grammarClass.Fields.Add(field);
}
}
public IronyAutocodeGeneratorModel Cfg { get; } = new IronyAutocodeGeneratorModel();
private CsClass _grammarClass;
private class FieldCreationInfo
{
public FieldCreationInfo(string fieldName, string setValueCode, params string[] otherCode)
{
FieldName = fieldName;
SetValueCode = setValueCode;
OtherCode = otherCode;
}
public string FieldName { get; }
public string SetValueCode { get; }
public string[] OtherCode { get; }
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using Alachisoft.NCache.Runtime.Serialization.IO;
using System.Diagnostics;
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Common.Pooling;
namespace Alachisoft.NCache.Common.Stats
{
/// <summary>
/// HPTime represents the time based on the ticks of High Performance coutners.
/// It is a relative time not synchronized with system time. The time accuracy
/// is upto micro seconds.
/// </summary>
/// <author></author>
public class HPTime : IComparable, ICompactSerializable
{
private int _hr;
private int _min;
private int _sec;
private int _mlSec;
private int _micSec;
private static long _frequency;
private static long _baseTicks;
private static object _synObj = new Object();
private static string _col = ":";
private double _baseTime;
private double _baseRem;
static HPTime()
{
lock (_synObj)
{
_frequency = Stopwatch.Frequency;
_baseTicks = Stopwatch.GetTimestamp();
}
}
/// <summary>
/// Gets the hours component of the time of this instance.
/// </summary>
public int Hours
{
get { return _hr; }
}
/// <summary>
/// Gets the hours component of the time of this instance.
/// </summary>
public int Minutes
{
get { return _min; }
}
/// <summary>
/// Gets the Secnds component of the time of this instance.
/// </summary>
public int Seconds
{
get { return _sec; }
}
/// <summary>
/// Gets the MilliSecond component of the time of this instance.
/// </summary>
public int MilliSeconds
{
get { return _mlSec; }
}
/// <summary>
/// Gets the MicroSeconds component of the time of this instance.
/// </summary>
public int MicroSeconds
{
get { return _micSec; }
}
public double BaseTime
{
get { return _baseTime; }
set { _baseRem = value; }
}
public double ServerTicks
{
get { return _baseRem; }
}
/// <summary>
/// Gets current HP time
/// </summary>
public HPTime CurrentTime
{
get
{
double rem = 0;
long currentTicks = 0;
long diff;
HPTime time = new HPTime();
currentTicks = Stopwatch.GetTimestamp();
diff = currentTicks - _baseTicks;
rem = ((double)diff / (double)_frequency) * 1000;
//double baseTime = 0;//it will be server time;
_baseTime = rem;
time._baseTime = rem;
rem += _baseRem;
time._hr = (int)(rem / 3600000);
rem = rem - (time._hr * 3600000);
time._min = (int)rem / 60000;
rem = rem - (time._min * 60000);
time._sec = (int)rem / 1000;
rem = rem - (time._sec * 1000);
time._mlSec = (int)rem;
rem = (rem - (double)time._mlSec) * 1000;
time._micSec = (int)rem;
return time;
}
}
/// <summary>
/// Gets current HP time
/// </summary>
public static HPTime Now
{
get
{
double rem = 0;
long currentTicks = 0;
long diff;
HPTime time = new HPTime();
currentTicks = Stopwatch.GetTimestamp();
diff = currentTicks - _baseTicks;
rem = ((double)diff / (double)_frequency) * 1000;
time._hr = (int)(rem / 3600000);
rem = rem - (time._hr * 3600000);
time._min = (int)rem / 60000;
rem = rem - (time._min * 60000);
time._sec = (int)rem / 1000;
rem = rem - (time._sec * 1000);
time._mlSec = (int)rem;
rem = (rem - (double)time._mlSec) * 1000;
time._micSec = (int)rem;
return time;
}
}
/// <summary>
/// Gets the string representation of the current instance of HP time.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _hr % 24 + _col + _min % 60 + _col + _sec % 60 + _col + (long)_mlSec + _col + _micSec;
}
/// <summary>
/// Gets the string representation of the current instance of HP time.
/// </summary>
/// <returns></returns>
public string ToAbsoluteTimeString()
{
return _hr + _col + _min + _col + _sec + _col + (long)_mlSec + _col + _micSec;
}
#region IComparable Members
public int CompareTo(object obj)
{
if (obj is HPTime)
{
HPTime other = (HPTime)obj;
int result = this.Hours.CompareTo(other.Hours);
if (result == 0)
{
result = this.Minutes.CompareTo(other.Minutes);
if (result == 0)
{
result = this.Seconds.CompareTo(other.Seconds);
if (result == 0)
{
result = this.MilliSeconds.CompareTo(other.MilliSeconds);
if (result == 0)
{
return this.MicroSeconds.CompareTo(other.MicroSeconds);
}
return result;
}
return result;
}
return result;
}
return result;
}
return 1;
}
#endregion
#region ICompactSerializable Members
public void Deserialize(CompactReader reader)
{
_hr = reader.ReadInt32();
_micSec = reader.ReadInt32();
_min = reader.ReadInt32();
_mlSec = reader.ReadInt32();
_sec = reader.ReadInt32();
}
public void Serialize(CompactWriter writer)
{
writer.Write(_hr);
writer.Write(_micSec);
writer.Write(_min);
writer.Write(_mlSec);
writer.Write(_sec);
}
#endregion
#region - [Deep Cloning] -
public HPTime DeepClone(PoolManager poolManager)
{
var clonedHPTime = new HPTime();
clonedHPTime._baseRem = _baseRem;
clonedHPTime._baseTime = _baseTime;
clonedHPTime._hr = _hr;
clonedHPTime._micSec = _micSec;
clonedHPTime._min = _min;
clonedHPTime._mlSec = _mlSec;
clonedHPTime._sec = _sec;
return clonedHPTime;
}
#endregion
}
}
| |
#region FreeBSD
// Copyright (c) 2013, John Batte
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Core;
using Autofac.Extras.CommonServiceLocator;
using Microsoft.Practices.ServiceLocation;
using Moq;
using Patterns.Autofac;
using Patterns.ExceptionHandling;
using Patterns.Testing.Moq;
namespace Patterns.Testing.Autofac.Moq
{
/// <summary>
/// Provides a default implementation of the <see cref="IAutofacMoqContainer" /> interface.
/// </summary>
public sealed class AutofacMoqContainer : AccessibleContainer, IAutofacMoqContainer
{
private readonly MockBehavior _defaultBehavior;
private readonly MoqRegistrationSource _registrationSource;
/// <summary>
/// Initializes a new instance of the <see cref="AutofacMoqContainer" /> class with
/// </summary>
/// <param name="defaultBehavior">The default <see cref="MockBehavior"/>.</param>
public AutofacMoqContainer(IContainer container, MockBehavior behavior) : base(container)
{
_defaultBehavior = behavior;
Locator = new AutofacServiceLocator(this);
ComponentRegistry.AddRegistrationSource(_registrationSource = new MoqRegistrationSource(_defaultBehavior));
}
/// <summary>
/// Initializes a new instance of the <see cref="AutofacMoqContainer" /> class.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="defaultBehavior">The default <see cref="MockBehavior"/>.</param>
public AutofacMoqContainer(IContainer container) : this(container, MockBehavior.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AutofacMoqContainer" /> class.
/// </summary>
public AutofacMoqContainer() : this(new ContainerBuilder().Build())
{
}
/// <summary>
/// Gets the default <see cref="MockBehavior"/>.
/// </summary>
/// <value>
/// The default <see cref="MockBehavior"/>.
/// </value>
public MockBehavior DefaultBehavior { get { return _defaultBehavior; } }
/// <summary>
/// Gets the locator.
/// </summary>
/// <value>
/// The locator.
/// </value>
public IServiceLocator Locator { get; private set; }
/// <summary>
/// Retrieves the mock for the specified service type.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns>
/// The service mock.
/// </returns>
public Mock<TService> Mock<TService>() where TService : class
{
return Mock<TService>(_defaultBehavior);
}
/// <summary>
/// Retrieves the mock for the specified service type.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="mockBehavior">
/// The <see cref="MockBehavior" /> of the mock.
/// </param>
/// <returns>
/// The service mock.
/// </returns>
public Mock<TService> Mock<TService>(MockBehavior mockBehavior) where TService : class
{
TService service = Try.Get<TService>(Create<TService>);
var existingMock = service as IMocked<TService>;
if (existingMock != null) return existingMock.Mock;
Mock<TService> mock = _registrationSource.Repository.Create<TService>(mockBehavior);
Update(mock.Object);
return mock;
}
/// <summary>
/// Creates an instance of the specified service, injecting mocked objects
/// for all unregistered dependencies.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns>
/// The service instance.
/// </returns>
public TService Create<TService>() where TService : class
{
return Container.Resolve<TService>();
}
/// <summary>
/// Creates an instance of the specified implementation (as the specified service),
/// injecting mocked objects for all unregistered dependencies.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <returns></returns>
public TService Create<TService, TImplementation>() where TService : class where TImplementation : TService
{
Update<TService, TImplementation>();
return Create<TService>();
}
/// <summary>
/// Updates this instance by registering the implementation type as the service type.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <returns>
/// The container.
/// </returns>
public IMoqContainer Update<TService, TImplementation>() where TService : class where TImplementation : TService
{
UpdateWithBuilder(builder => builder.RegisterType<TImplementation>().As<TService>()
.PropertiesAutowired(PropertyWiringOptions.PreserveSetValues));
return this;
}
/// <summary>
/// Updates this instance by registering an instance of the specified service.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
/// <returns>
/// The container.
/// </returns>
public IMoqContainer Update<TService>(TService instance) where TService : class
{
UpdateWithBuilder(builder => builder.RegisterInstance(instance).As<TService>()
.PropertiesAutowired(PropertyWiringOptions.PreserveSetValues));
return this;
}
/// <summary>
/// Updates this instance by registering the specified activator as the service type.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="activator">The activator.</param>
/// <returns>
/// The container
/// </returns>
public IMoqContainer Update<TService>(Func<IMoqContainer, TService> activator) where TService : class
{
UpdateWithBuilder(builder => builder.Register(c => activator(this)).As<TService>()
.PropertiesAutowired(PropertyWiringOptions.PreserveSetValues));
return this;
}
/// <summary>
/// Updates the container using the specified module.
/// </summary>
/// <param name="module">The module.</param>
/// <returns>
/// The container.
/// </returns>
public IAutofacMoqContainer Update(Module module)
{
UpdateWithBuilder(builder => builder.RegisterModule(module));
return this;
}
/// <summary>
/// Updates the container using the specified registration.
/// </summary>
/// <param name="registration">The registration.</param>
/// <returns>
/// The container.
/// </returns>
public IAutofacMoqContainer Update(Action<ContainerBuilder> registration)
{
UpdateWithBuilder(registration);
return this;
}
private void UpdateWithBuilder(Action<ContainerBuilder> registration)
{
var builder = new ContainerBuilder();
registration(builder);
builder.Update(Container);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Win32;
using System.Text;
using System.IO;
namespace CodeToolsUpdate
{
internal class TargetInfo
{
#region Fields
private readonly CodeToolInfo tool;
private readonly string targetName; // name of this target; used to create unique filenames and identifiers
private readonly string fileName; // targets file
private readonly string kind; // ImportBefore | ImportAfter
private readonly string condition; // possible import condition
private readonly string versions; // just for these (semi colon seperated) msbuild versions: empty is for all
private readonly Dictionary<string, string> properties; // msbuild properties
// magic constants
private const string importAfter = "ImportAfter";
private const string importBefore = "ImportBefore";
// derived
private readonly string prefixComment;
private readonly string postfixComment;
private readonly string projectTag = "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">";
private readonly string projectEndTag = "</Project>";
#endregion
#region Constructor and equality
private TargetInfo(CodeToolInfo tool, string targetName, string fileName, string kind, string _versions, string condition, Dictionary<string, string> properties)
{
this.targetName = targetName;
this.tool = tool;
this.fileName = fileName;
this.kind = kind;
versions = _versions;
this.condition = condition;
this.properties = properties;
// sanitize
if (String.Compare(kind, importAfter, true) == 0) this.kind = importAfter;
if (String.Compare(kind, importBefore, true) == 0) this.kind = importBefore;
if (versions == null)
versions = "";
else
versions = versions.Trim();
// derived
prefixComment = " <!-- Begin CodeTools: " + tool.ToolName + ": " + targetName + " -->";
postfixComment = " <!-- End CodeTools: " + tool.ToolName + ": " + targetName + " -->";
}
public override bool Equals(object obj)
{
TargetInfo t = obj as TargetInfo;
if (t == null) return false;
if (tool.ToolName != t.tool.ToolName) return false;
if (tool.VsRoot != t.tool.VsRoot) return false;
if (targetName != t.targetName) return false;
if (fileName != t.fileName) return false;
if (kind != t.kind) return false;
if (condition != t.condition) return false;
if (versions != t.versions) return false;
if (properties.Count != t.properties.Count) return false;
foreach (string prop in properties.Keys)
{
if (!t.properties.ContainsKey(prop)) return false;
if (properties[prop] != t.properties[prop]) return false;
}
return true;
}
public override int GetHashCode()
{
// just do a simple hash
return (tool.ToolName.GetHashCode() * targetName.GetHashCode() * fileName.GetHashCode());
}
#endregion
#region Create from registry
public static TargetInfo ReadFromRegistry(CodeToolInfo tool, RegistryKey targetKey, string targetName)
{
string fileName = null;
string kind = importAfter;
string condition = "";
string versions = "";
Dictionary<string, string> properties = new Dictionary<string, string>();
foreach (string name in targetKey.GetValueNames())
{
if (String.Compare(name, "TargetsFile", true) == 0)
{
fileName = targetKey.GetValue(name) as string;
}
else if (String.Compare(name, "TargetsKind", true) == 0)
{
kind = targetKey.GetValue(name) as string;
}
else if (String.Compare(name, "TargetsCondition", true) == 0)
{
condition = targetKey.GetValue(name) as string;
}
else if (String.Compare(name, "MSBuildVersions", true) == 0 || String.Compare(name, "MSBuildVersion", true) == 0)
{
versions = targetKey.GetValue(name) as string;
}
else if (name != null && name.Length > 0)
{
string val = targetKey.GetValue(name) as string;
properties.Add(name, val);
}
}
if (fileName == null) return null;
return new TargetInfo(tool, targetName, fileName, kind, versions, condition, properties);
}
#endregion
#region Install and UnInstall
private /* ISet */ List<string> GetAssociatedMSBuildVersions()
{
List<string> buildVersions = new List<string>();
if (versions == null || versions.Length == 0)
{
RegistryKey msbuild = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\MSBuild");
if (msbuild != null)
{
foreach (string ver in msbuild.GetSubKeyNames())
{
if (ver != null && ver.Length > 0 && Char.IsDigit(ver[0]))
{
buildVersions.Add(ver);
}
}
}
}
else
{
// add the specified versions
foreach (string version in versions.Split(';'))
{
buildVersions.Add(version);
}
}
return buildVersions;
}
public void Install()
{
List<string> buildVersions = GetAssociatedMSBuildVersions();
// Create msbuild targets
foreach (string ver in buildVersions)
{
InstallVersion(ver);
}
// register as installed
RegistryKey installedKey = tool.GetInstalledTargetsKey(true);
if (installedKey != null)
{
RegistryKey targetKey = installedKey.CreateSubKey(targetName);
if (targetKey != null)
{
targetKey.SetValue("TargetsFile", fileName);
targetKey.SetValue("TargetsKind", kind);
if (condition != null && condition.Length > 0) targetKey.SetValue("TargetsCondition", condition);
if (versions != null && versions.Length > 0) targetKey.SetValue("MSBuildVersions", versions);
foreach (string key in properties.Keys)
{
targetKey.SetValue(key, properties[key]);
}
}
}
Common.Message("Installed " + tool.DisplayName + " MSBuild targets");
}
public void UnInstall()
{
try
{
List<string> buildVersions = GetAssociatedMSBuildVersions();
// remove build targets
foreach (string ver in buildVersions)
{
UnInstallVersion(ver);
}
// register as uninstalled
RegistryKey installedKey = tool.GetInstalledTargetsKey(true);
if (installedKey != null)
{
installedKey.DeleteSubKeyTree(targetName);
}
Common.Message("Uninstalled " + tool.DisplayName + " MSBuild targets");
}
catch (Exception exn)
{
Common.ErrorMessage("Failed to uninstall " + tool.DisplayName + " MSBuild targets:\n" + exn.ToString());
}
}
#endregion
#region Install for a specific msbuild version
private string TargetsFile(string msbuildVersion)
{
string msbuildRoot = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\MSBuild\\";
if (CompareVersion(msbuildVersion, "4.0") < 0)
{
if (kind == importAfter)
{
return msbuildRoot + "v" + msbuildVersion + "\\Custom.After.Microsoft.Common.targets";
}
else if (kind == importBefore)
{
return msbuildRoot + "v" + msbuildVersion + "\\Custom.Before.Microsoft.Common.targets";
}
else
{
//not good :-(
return msbuildRoot + "v" + msbuildVersion + "\\Custom." + kind + ".Microsoft.Common.targets";
}
}
else
{
return msbuildRoot + msbuildVersion + "\\Microsoft.Common.Targets\\" + kind + "\\" + tool.ToolName + targetName + ".targets";
}
}
private void InstallVersion(string msbuildVersion)
{
// Build an import block
StringBuilder content = new StringBuilder();
content.AppendLine(prefixComment);
if (properties.Count > 0)
{
content.AppendLine(" <PropertyGroup>");
foreach (string key in properties.Keys)
{
content.AppendFormat(" <{0} Condition=\"'$({0})'==''\">{1}</{0}>", key, properties[key]);
content.AppendLine("");
}
content.AppendLine(" </PropertyGroup>");
}
if (condition != null && condition.Length > 0)
{
content.AppendFormat(" <Import Condition=\"{1}\" Project=\"{0}\" />\n", fileName, condition);
content.AppendLine("");
}
else
{
content.AppendFormat(" <Import Project=\"{0}\" />", fileName);
content.AppendLine("");
}
content.AppendLine(postfixComment);
string targetsFile = TargetsFile(msbuildVersion);
bool createFresh = true;
// legacy versions: inject into one common file
if (CompareVersion(msbuildVersion, "4.0") < 0)
{
createFresh = !File.Exists(targetsFile);
}
if (createFresh)
{
EnsureDir(targetsFile);
using (StreamWriter f = File.CreateText(targetsFile))
{
f.WriteLine(projectTag);
f.Write(content.ToString());
f.WriteLine(projectEndTag);
f.Close();
}
}
else
{
// inject into a common file. Only happens for v3.5 and lower
string fcontent = File.ReadAllText(targetsFile);
string fproject;
string fafterproject;
string fprefix;
string fpostfix;
if (SplitAfter(projectTag, fcontent, out fproject, out fafterproject))
{
if (SplitBetween(prefixComment, postfixComment, fcontent, out fprefix, out fpostfix))
{
// found previous version of us: overwrite that part
fcontent = fprefix + content.ToString() + fpostfix;
}
else
{
// no previous version of us: inject fresh
fcontent = fproject + "\r\n" + content.ToString() + fafterproject;
}
File.WriteAllText(targetsFile, fcontent);
}
else
{
// this is not a project file -- give up
}
}
}
#endregion
#region UnInstall for a specific msbuild version
private void UnInstallVersion(string msbuildVersion)
{
string targetsFile = TargetsFile(msbuildVersion);
if (File.Exists(targetsFile))
{
if (CompareVersion(msbuildVersion, "4.0") < 0)
{
// legacy, un-inject from the common file
string fcontent = File.ReadAllText(targetsFile);
string fprefix;
string fpostfix;
if (SplitBetween(prefixComment, postfixComment, fcontent, out fprefix, out fpostfix))
{
// found our part, extract it
fcontent = fprefix + fpostfix;
File.WriteAllText(targetsFile, fcontent);
}
}
else
{
// msbuild v4.0 and higher: remove our file
File.Delete(targetsFile);
}
}
}
#endregion
#region String helpers
private static int CompareVersion(string version1, string version2)
{
// strip off the 'v'
string v1 = (version1 != null && version1.Length > 0 && (version1[0] == 'v' || version1[0] == 'V')) ? version1.Substring(1) : version1;
string v2 = (version2 != null && version2.Length > 0 && (version2[0] == 'v' || version2[0] == 'V')) ? version2.Substring(1) : version2;
if (v1 == v2) return 0;
try
{
var vn1 = float.Parse(v1);
var vn2 = float.Parse(v2);
return (vn1 - vn2 < 0) ? -1 : 1;
}
catch
{
return -1;
}
}
private void EnsureDir(string path)
{
List<string> directories = new List<string>();
{
string dir = Path.GetDirectoryName(path);
int i;
while ((i = dir.LastIndexOf(Path.DirectorySeparatorChar)) >= 0)
{
directories.Add(dir);
dir = dir.Substring(0, i);
}
}
directories.Reverse();
foreach (string dir in directories)
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}
private bool MatchAt(string pattern, string s, int i)
{
if (pattern == null) return true;
if (s == null) return false;
for (int j = 0; j < pattern.Length; j++)
{
if (pattern[j] != s[i + j]) return false;
}
return true;
}
private bool SplitOn(bool after, string pattern, string s, out string prefix, out string postfix)
{
if (pattern == null)
{
prefix = "";
postfix = s;
return true;
}
prefix = s;
postfix = null;
if (s == null) return false;
for (int i = 0; i < s.Length; i++)
{
if (MatchAt(pattern, s, i))
{
if (after) i += pattern.Length;
prefix = s.Substring(0, i);
postfix = s.Substring(i);
return true;
}
}
return false;
}
private bool SplitAfter(string pattern, string s, out string prefix, out string postfix)
{
return SplitOn(true, pattern, s, out prefix, out postfix);
}
private bool SplitBefore(string pattern, string s, out string prefix, out string postfix)
{
return SplitOn(false, pattern, s, out prefix, out postfix);
}
private bool SplitBetween(string patternStart, string patternEnd, string s, out string prefix, out string postfix)
{
string afterstart;
string fragment;
if (SplitBefore(patternStart, s, out prefix, out afterstart))
{
if (SplitAfter(patternEnd, afterstart, out fragment, out postfix))
{
return true;
}
}
prefix = s;
postfix = "";
return false;
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using NLog.Internal;
/// <summary>
/// Provides context for install/uninstall operations.
/// </summary>
public sealed class InstallationContext : IDisposable
{
#if !SILVERLIGHT && !NETSTANDARD1_3
/// <summary>
/// Mapping between log levels and console output colors.
/// </summary>
private static readonly Dictionary<LogLevel, ConsoleColor> logLevel2ConsoleColor = new Dictionary<LogLevel, ConsoleColor>()
{
{ LogLevel.Trace, ConsoleColor.DarkGray },
{ LogLevel.Debug, ConsoleColor.Gray },
{ LogLevel.Info, ConsoleColor.White },
{ LogLevel.Warn, ConsoleColor.Yellow },
{ LogLevel.Error, ConsoleColor.Red },
{ LogLevel.Fatal, ConsoleColor.DarkRed },
};
#endif
/// <summary>
/// Initializes a new instance of the <see cref="InstallationContext"/> class.
/// </summary>
public InstallationContext()
: this(TextWriter.Null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InstallationContext"/> class.
/// </summary>
/// <param name="logOutput">The log output.</param>
public InstallationContext(TextWriter logOutput)
{
LogOutput = logOutput;
Parameters = new Dictionary<string, string>();
LogLevel = LogLevel.Info;
ThrowExceptions = false;
}
/// <summary>
/// Gets or sets the installation log level.
/// </summary>
public LogLevel LogLevel { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore failures during installation.
/// </summary>
public bool IgnoreFailures { get; set; }
/// <summary>
/// Whether installation exceptions should be rethrown. If IgnoreFailures is set to true,
/// this property has no effect (there are no exceptions to rethrow).
/// </summary>
public bool ThrowExceptions { get; set; }
/// <summary>
/// Gets the installation parameters.
/// </summary>
public IDictionary<string, string> Parameters { get; private set; }
/// <summary>
/// Gets or sets the log output.
/// </summary>
public TextWriter LogOutput { get; set; }
/// <summary>
/// Logs the specified trace message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Trace([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Trace, message, arguments);
}
/// <summary>
/// Logs the specified debug message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Debug([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Debug, message, arguments);
}
/// <summary>
/// Logs the specified informational message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Info([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Info, message, arguments);
}
/// <summary>
/// Logs the specified warning message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Warning([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Warn, message, arguments);
}
/// <summary>
/// Logs the specified error message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Error([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Error, message, arguments);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (LogOutput != null)
{
LogOutput.Close();
LogOutput = null;
}
}
/// <summary>
/// Creates the log event which can be used to render layouts during installation/uninstallations.
/// </summary>
/// <returns>Log event info object.</returns>
public LogEventInfo CreateLogEvent()
{
var eventInfo = LogEventInfo.CreateNullEvent();
// set properties on the event
foreach (var kvp in Parameters)
{
eventInfo.Properties.Add(kvp.Key, kvp.Value);
}
return eventInfo;
}
private void Log(LogLevel logLevel, [Localizable(false)] string message, object[] arguments)
{
if (logLevel >= LogLevel)
{
if (arguments != null && arguments.Length > 0)
{
message = string.Format(CultureInfo.InvariantCulture, message, arguments);
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = logLevel2ConsoleColor[logLevel];
try
{
LogOutput.WriteLine(message);
}
finally
{
Console.ForegroundColor = oldColor;
}
#else
this.LogOutput.WriteLine(message);
#endif
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.ML.Train;
using Encog.Util.Concurrency;
using Encog.ML.EA.Train;
using Encog.ML.EA.Population;
using Encog.Neural.Networks.Training;
using Encog.ML.EA.Sort;
using Encog.ML.EA.Species;
using Encog.ML.Genetic.Mutate;
using Encog.ML.Genetic.Crossover;
using Encog.ML.EA.Genome;
using Encog.Util.Logging;
using Encog.Neural.Networks.Training.Propagation;
namespace Encog.ML.Genetic
{
/// <summary>
/// Implements a genetic algorithm that allows an MLMethod that is encodable
/// (MLEncodable) to be trained. It works well with both BasicNetwork and
/// FreeformNetwork class, as well as any MLEncodable class.
///
/// There are essentially two ways you can make use of this class.
///
/// Either way, you will need a score object. The score object tells the genetic
/// algorithm how well suited a neural network is.
///
/// If you would like to use genetic algorithms with a training set you should
/// make use TrainingSetScore class. This score object uses a training set to
/// score your neural network.
///
/// If you would like to be more abstract, and not use a training set, you can
/// create your own implementation of the CalculateScore method. This class can
/// then score the networks any way that you like.
/// </summary>
public class MLMethodGeneticAlgorithm : BasicTraining, IMultiThreadable
{
/// <summary>
/// Very simple class that implements a genetic algorithm.
/// </summary>
public class MLMethodGeneticAlgorithmHelper : TrainEA
{
/// <summary>
/// Construct the helper.
/// </summary>
/// <param name="thePopulation">The population.</param>
/// <param name="theScoreFunction">The score function.</param>
public MLMethodGeneticAlgorithmHelper(IPopulation thePopulation,
ICalculateScore theScoreFunction)
: base(thePopulation, theScoreFunction)
{
}
}
/// <summary>
/// Simple helper class that implements the required methods to implement a
/// genetic algorithm.
/// </summary>
private MLMethodGeneticAlgorithmHelper genetic;
/// <summary>
/// Construct a method genetic algorithm.
/// </summary>
/// <param name="phenotypeFactory">The phenotype factory.</param>
/// <param name="calculateScore">The score calculation object.</param>
/// <param name="populationSize">The population size.</param>
public MLMethodGeneticAlgorithm(MLMethodGenomeFactory.CreateMethod phenotypeFactory,
ICalculateScore calculateScore, int populationSize)
: base(TrainingImplementationType.Iterative)
{
// create the population
IPopulation population = new BasicPopulation(populationSize, null);
population.GenomeFactory = new MLMethodGenomeFactory(phenotypeFactory,
population);
ISpecies defaultSpecies = population.CreateSpecies();
for (int i = 0; i < population.PopulationSize; i++)
{
IMLEncodable chromosomeNetwork = (IMLEncodable)phenotypeFactory();
MLMethodGenome genome = new MLMethodGenome(chromosomeNetwork);
defaultSpecies.Add(genome);
}
defaultSpecies.Leader = defaultSpecies.Members[0];
// create the trainer
this.genetic = new MLMethodGeneticAlgorithmHelper(population,
calculateScore);
this.genetic.CODEC = new MLEncodableCODEC();
IGenomeComparer comp = null;
if (calculateScore.ShouldMinimize)
{
comp = new MinimizeScoreComp();
}
else
{
comp = new MaximizeScoreComp();
}
this.genetic.BestComparer = comp;
this.genetic.SelectionComparer = comp;
// create the operators
int s = Math
.Max(defaultSpecies.Members[0].Size / 5, 1);
Genetic.Population = population;
this.genetic.AddOperation(0.9, new Splice(s));
this.genetic.AddOperation(0.1, new MutatePerturb(1.0));
}
/// <inheritdoc/>
public override bool CanContinue
{
get
{
return false;
}
}
/// <summary>
/// The genetic algorithm implementation.
/// </summary>
public MLMethodGeneticAlgorithmHelper Genetic
{
get
{
return this.genetic;
}
}
/// <inheritdoc/>
public override IMLMethod Method
{
get
{
IGenome best = this.genetic.BestGenome;
return this.genetic.CODEC.Decode(best);
}
}
/// <inheritdoc/>
public int ThreadCount
{
get
{
return this.genetic.ThreadCount;
}
set
{
this.genetic.ThreadCount = value;
}
}
/// <inheritdoc/>
public override void Iteration()
{
EncogLogging.Log(EncogLogging.LevelInfo,
"Performing Genetic iteration.");
PreIteration();
Error = Genetic.Error;
Genetic.Iteration();
Error = Genetic.Error;
PostIteration();
}
/// <inheritdoc/>
public override TrainingContinuation Pause()
{
return null;
}
/// <inheritdoc/>
public override void Resume(TrainingContinuation state)
{
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Ixq.Core.DependencyInjection.Extensions
{
/// <summary>
/// Extension methods for adding services to an <see cref="IServiceCollection" />.
/// </summary>
public static class ServiceCollectionServiceExtensions
{
/// <summary>
/// Adds a transient service of the type specified in <paramref name="serviceType" /> with an
/// implementation of the type specified in <paramref name="implementationType" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient" />
public static IServiceCollection AddTransient(
this IServiceCollection services,
Type serviceType,
Type implementationType,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (implementationType == null)
throw new ArgumentNullException(nameof(implementationType));
return Add(services, serviceType, implementationType, ServiceLifetime.Transient, alias);
}
/// <summary>
/// Adds a transient service of the type specified in <paramref name="serviceType" /> with a
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient" />
public static IServiceCollection AddTransient(
this IServiceCollection services,
Type serviceType,
Func<IServiceProvider, object> implementationFactory,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient, alias);
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService" /> with an
/// implementation type specified in <typeparamref name="TImplementation" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient" />
public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services,
string alias = null)
where TService : class
where TImplementation : class, TService
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return services.AddTransient(typeof(TService), typeof(TImplementation), alias);
}
/// <summary>
/// Adds a transient service of the type specified in <paramref name="serviceType" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register and the implementation to use.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient" />
public static IServiceCollection AddTransient(
this IServiceCollection services,
Type serviceType,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
return services.AddTransient(serviceType, serviceType, alias);
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient" />
public static IServiceCollection AddTransient<TService>(this IServiceCollection services, string alias = null)
where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return services.AddTransient(typeof(TService), alias);
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService" /> with a
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient" />
public static IServiceCollection AddTransient<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> implementationFactory,
string alias = null)
where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return services.AddTransient(typeof(TService), implementationFactory, alias);
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService" /> with an
/// implementation type specified in <typeparamref name="TImplementation" /> using the
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient" />
public static IServiceCollection AddTransient<TService, TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> implementationFactory,
string alias = null)
where TService : class
where TImplementation : class, TService
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return services.AddTransient(typeof(TService), implementationFactory, alias);
}
/// <summary>
/// Adds a scoped service of the type specified in <paramref name="serviceType" /> with an
/// implementation of the type specified in <paramref name="implementationType" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped" />
public static IServiceCollection AddScoped(
this IServiceCollection services,
Type serviceType,
Type implementationType,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (implementationType == null)
throw new ArgumentNullException(nameof(implementationType));
return Add(services, serviceType, implementationType, ServiceLifetime.Scoped, alias);
}
/// <summary>
/// Adds a scoped service of the type specified in <paramref name="serviceType" /> with a
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped" />
public static IServiceCollection AddScoped(
this IServiceCollection services,
Type serviceType,
Func<IServiceProvider, object> implementationFactory,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped, alias);
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService" /> with an
/// implementation type specified in <typeparamref name="TImplementation" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped" />
public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services,
string alias = null)
where TService : class
where TImplementation : class, TService
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return services.AddScoped(typeof(TService), typeof(TImplementation), alias);
}
/// <summary>
/// Adds a scoped service of the type specified in <paramref name="serviceType" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register and the implementation to use.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped" />
public static IServiceCollection AddScoped(
this IServiceCollection services,
Type serviceType,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
return services.AddScoped(serviceType, serviceType, alias);
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped" />
public static IServiceCollection AddScoped<TService>(this IServiceCollection services, string alias = null)
where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return services.AddScoped(typeof(TService), alias);
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService" /> with a
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped" />
public static IServiceCollection AddScoped<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> implementationFactory,
string alias = null)
where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return services.AddScoped(typeof(TService), implementationFactory, alias);
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService" /> with an
/// implementation type specified in <typeparamref name="TImplementation" /> using the
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped" />
public static IServiceCollection AddScoped<TService, TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> implementationFactory,
string alias = null)
where TService : class
where TImplementation : class, TService
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return services.AddScoped(typeof(TService), implementationFactory, alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType" /> with an
/// implementation of the type specified in <paramref name="implementationType" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
Type implementationType,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (implementationType == null)
throw new ArgumentNullException(nameof(implementationType));
return Add(services, serviceType, implementationType, ServiceLifetime.Singleton, alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType" /> with a
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
Func<IServiceProvider, object> implementationFactory,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton, alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService" /> with an
/// implementation type specified in <typeparamref name="TImplementation" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services,
string alias = null)
where TService : class
where TImplementation : class, TService
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return services.AddSingleton(typeof(TService), typeof(TImplementation), alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register and the implementation to use.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
return services.AddSingleton(serviceType, serviceType, alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, string alias = null)
where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return services.AddSingleton(typeof(TService), alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService" /> with a
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> implementationFactory,
string alias = null)
where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return services.AddSingleton(typeof(TService), implementationFactory, alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService" /> with an
/// implementation type specified in <typeparamref name="TImplementation" /> using the
/// factory specified in <paramref name="implementationFactory" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton<TService, TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> implementationFactory,
string alias = null)
where TService : class
where TImplementation : class, TService
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (implementationFactory == null)
throw new ArgumentNullException(nameof(implementationFactory));
return services.AddSingleton(typeof(TService), implementationFactory, alias);
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType" /> with an
/// instance specified in <paramref name="implementationInstance" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationInstance">The instance of the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
object implementationInstance,
string alias = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (implementationInstance == null)
throw new ArgumentNullException(nameof(implementationInstance));
var serviceDescriptor = new ServiceDescriptor(serviceType, implementationInstance, alias);
services.Add(serviceDescriptor);
return services;
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService" /> with an
/// instance specified in <paramref name="implementationInstance" /> to the
/// specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="implementationInstance">The instance of the service.</param>
/// <param name="alias"></param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton" />
public static IServiceCollection AddSingleton<TService>(
this IServiceCollection services,
TService implementationInstance,
string alias = null)
where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (implementationInstance == null)
throw new ArgumentNullException(nameof(implementationInstance));
return services.AddSingleton(typeof(TService), implementationInstance, alias);
}
private static IServiceCollection Add(
IServiceCollection collection,
Type serviceType,
Type implementationType,
ServiceLifetime lifetime,
string alias = null)
{
var descriptor = new ServiceDescriptor(serviceType, implementationType, lifetime, alias);
collection.Add(descriptor);
return collection;
}
private static IServiceCollection Add(
IServiceCollection collection,
Type serviceType,
Func<IServiceProvider, object> implementationFactory,
ServiceLifetime lifetime,
string alias = null)
{
var descriptor = new ServiceDescriptor(serviceType, implementationFactory, lifetime, alias);
collection.Add(descriptor);
return collection;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudioTools;
namespace Microsoft.NodejsTools.Debugger.DebugEngine
{
// This class represents a pending breakpoint which is an abstract representation of a breakpoint before it is bound.
// When a user creates a new breakpoint, the pending breakpoint is created and is later bound. The bound breakpoints
// become children of the pending breakpoint.
internal class AD7PendingBreakpoint : IDebugPendingBreakpoint2
{
// The breakpoint request that resulted in this pending breakpoint being created.
private readonly BreakpointManager _bpManager;
private readonly IDebugBreakpointRequest2 _bpRequest;
private readonly List<AD7BreakpointErrorEvent> _breakpointErrors = new List<AD7BreakpointErrorEvent>();
private readonly AD7Engine _engine;
private BP_REQUEST_INFO _bpRequestInfo;
private NodeBreakpoint _breakpoint;
private string _documentName;
private bool _enabled, _deleted;
public AD7PendingBreakpoint(IDebugBreakpointRequest2 pBpRequest, AD7Engine engine, BreakpointManager bpManager)
{
this._bpRequest = pBpRequest;
var requestInfo = new BP_REQUEST_INFO[1];
EngineUtils.CheckOk(this._bpRequest.GetRequestInfo(enum_BPREQI_FIELDS.BPREQI_BPLOCATION | enum_BPREQI_FIELDS.BPREQI_CONDITION | enum_BPREQI_FIELDS.BPREQI_ALLFIELDS, requestInfo));
this._bpRequestInfo = requestInfo[0];
this._engine = engine;
this._bpManager = bpManager;
this._enabled = true;
this._deleted = false;
}
public BP_PASSCOUNT PassCount => this._bpRequestInfo.bpPassCount;
public string DocumentName
{
get
{
if (this._documentName == null)
{
var docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(this._bpRequestInfo.bpLocation.unionmember2));
EngineUtils.CheckOk(docPosition.GetFileName(out this._documentName));
}
return this._documentName;
}
}
#region IDebugPendingBreakpoint2 Members
// Binds this pending breakpoint to one or more code locations.
int IDebugPendingBreakpoint2.Bind()
{
if (CanBind())
{
// Get the location in the document that the breakpoint is in.
var startPosition = new TEXT_POSITION[1];
var endPosition = new TEXT_POSITION[1];
string fileName;
var docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(this._bpRequestInfo.bpLocation.unionmember2));
EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));
EngineUtils.CheckOk(docPosition.GetFileName(out fileName));
this._breakpoint = this._engine.Process.AddBreakpoint(
fileName,
(int)startPosition[0].dwLine,
(int)startPosition[0].dwColumn,
this._enabled,
AD7BoundBreakpoint.GetBreakOnForPassCount(this._bpRequestInfo.bpPassCount),
this._bpRequestInfo.bpCondition.bstrCondition);
this._bpManager.AddPendingBreakpoint(this._breakpoint, this);
this._breakpoint.BindAsync().WaitAsync(TimeSpan.FromSeconds(2)).Wait();
return VSConstants.S_OK;
}
// The breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc...
// The sample engine does not support this, but a real world engine will want to send an instance of IDebugBreakpointErrorEvent2 to the
// UI and return a valid instance of IDebugErrorBreakpoint2 from IDebugPendingBreakpoint2::EnumErrorBreakpoints. The debugger will then
// display information about why the breakpoint did not bind to the user.
return VSConstants.S_FALSE;
}
// Determines whether this pending breakpoint can bind to a code location.
int IDebugPendingBreakpoint2.CanBind(out IEnumDebugErrorBreakpoints2 ppErrorEnum)
{
ppErrorEnum = null;
if (!CanBind())
{
// Called to determine if a pending breakpoint can be bound.
// The breakpoint may not be bound for many reasons such as an invalid location, an invalid expression, etc...
// The sample engine does not support this, but a real world engine will want to return a valid enumeration of IDebugErrorBreakpoint2.
// The debugger will then display information about why the breakpoint did not bind to the user.
return VSConstants.S_FALSE;
}
return VSConstants.S_OK;
}
// Deletes this pending breakpoint and all breakpoints bound from it.
int IDebugPendingBreakpoint2.Delete()
{
ClearBreakpointBindingResults();
this._deleted = true;
return VSConstants.S_OK;
}
// Toggles the enabled state of this pending breakpoint.
int IDebugPendingBreakpoint2.Enable(int fEnable)
{
this._enabled = fEnable != 0;
if (this._breakpoint != null)
{
lock (this._breakpoint)
{
foreach (var binding in this._breakpoint.GetBindings())
{
var boundBreakpoint = (IDebugBoundBreakpoint2)this._bpManager.GetBoundBreakpoint(binding);
boundBreakpoint.Enable(fEnable);
}
}
}
return VSConstants.S_OK;
}
// Enumerates all breakpoints bound from this pending breakpoint
int IDebugPendingBreakpoint2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
ppEnum = null;
if (this._breakpoint != null)
{
lock (this._breakpoint)
{
var boundBreakpoints = this._breakpoint.GetBindings()
.Select(binding => this._bpManager.GetBoundBreakpoint(binding))
.Cast<IDebugBoundBreakpoint2>().ToArray();
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
}
}
return VSConstants.S_OK;
}
// Enumerates all error breakpoints that resulted from this pending breakpoint.
int IDebugPendingBreakpoint2.EnumErrorBreakpoints(enum_BP_ERROR_TYPE bpErrorType, out IEnumDebugErrorBreakpoints2 ppEnum)
{
// Called when a pending breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc...
// Return a valid enumeration of IDebugErrorBreakpoint2 from IDebugPendingBreakpoint2::EnumErrorBreakpoints, allowing the debugger to
// display information about why the breakpoint did not bind to the user.
lock (this._breakpointErrors)
{
var breakpointErrors = this._breakpointErrors.Cast<IDebugErrorBreakpoint2>().ToArray();
ppEnum = new AD7ErrorBreakpointsEnum(breakpointErrors);
}
return VSConstants.S_OK;
}
// Gets the breakpoint request that was used to create this pending breakpoint
int IDebugPendingBreakpoint2.GetBreakpointRequest(out IDebugBreakpointRequest2 ppBpRequest)
{
ppBpRequest = this._bpRequest;
return VSConstants.S_OK;
}
// Gets the state of this pending breakpoint.
int IDebugPendingBreakpoint2.GetState(PENDING_BP_STATE_INFO[] pState)
{
if (this._deleted)
{
pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DELETED;
}
else if (this._enabled)
{
pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_ENABLED;
}
else
{
pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DISABLED;
}
return VSConstants.S_OK;
}
int IDebugPendingBreakpoint2.SetCondition(BP_CONDITION bpCondition)
{
if (bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_CHANGED)
{
return VSConstants.E_NOTIMPL;
}
this._bpRequestInfo.bpCondition = bpCondition;
return VSConstants.S_OK;
}
int IDebugPendingBreakpoint2.SetPassCount(BP_PASSCOUNT bpPassCount)
{
this._bpRequestInfo.bpPassCount = bpPassCount;
return VSConstants.S_OK;
}
// Toggles the virtualized state of this pending breakpoint. When a pending breakpoint is virtualized,
// the debug engine will attempt to bind it every time new code loads into the program.
// The sample engine will does not support this.
int IDebugPendingBreakpoint2.Virtualize(int fVirtualize)
{
return VSConstants.S_OK;
}
#endregion
private bool CanBind()
{
// Reject binding breakpoints which are deleted, not code file line, and on condition changed
if (this._deleted ||
this._bpRequestInfo.bpLocation.bpLocationType != (uint)enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE ||
this._bpRequestInfo.bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_CHANGED)
{
return false;
}
return true;
}
public void AddBreakpointError(AD7BreakpointErrorEvent breakpointError)
{
this._breakpointErrors.Add(breakpointError);
}
// Remove all of the bound breakpoints for this pending breakpoint
public void ClearBreakpointBindingResults()
{
if (this._breakpoint != null)
{
lock (this._breakpoint)
{
foreach (var binding in this._breakpoint.GetBindings())
{
var boundBreakpoint = (IDebugBoundBreakpoint2)this._bpManager.GetBoundBreakpoint(binding);
if (boundBreakpoint != null)
{
boundBreakpoint.Delete();
binding.Remove().WaitAndUnwrapExceptions();
}
}
}
this._bpManager.RemovePendingBreakpoint(this._breakpoint);
this._breakpoint.Deleted = true;
this._breakpoint = null;
}
this._breakpointErrors.Clear();
}
}
}
| |
//
// CFProxySupport.cs: Implements the managed binding for CFProxySupport.h
//
// Authors: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (C) 2011 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.CoreFoundation {
public enum CFProxyType {
None,
AutoConfigurationUrl,
AutoConfigurationJavaScript,
FTP,
HTTP,
HTTPS,
SOCKS
}
public class CFProxy {
NSDictionary settings;
internal CFProxy (NSDictionary settings)
{
this.settings = settings;
}
#region Property Keys
static NSString kCFProxyAutoConfigurationHTTPResponseKey;
static NSString AutoConfigurationHTTPResponseKey {
get {
if (kCFProxyAutoConfigurationHTTPResponseKey == null)
kCFProxyAutoConfigurationHTTPResponseKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyAutoConfigurationHTTPResponseKey");
return kCFProxyAutoConfigurationHTTPResponseKey;
}
}
static NSString kCFProxyAutoConfigurationJavaScriptKey;
static NSString AutoConfigurationJavaScriptKey {
get {
if (kCFProxyAutoConfigurationJavaScriptKey == null)
kCFProxyAutoConfigurationJavaScriptKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyAutoConfigurationJavaScriptKey");
return kCFProxyAutoConfigurationJavaScriptKey;
}
}
static NSString kCFProxyAutoConfigurationURLKey;
static NSString AutoConfigurationURLKey {
get {
if (kCFProxyAutoConfigurationURLKey == null)
kCFProxyAutoConfigurationURLKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyAutoConfigurationURLKey");
return kCFProxyAutoConfigurationURLKey;
}
}
static NSString kCFProxyHostNameKey;
static NSString HostNameKey {
get {
if (kCFProxyHostNameKey == null)
kCFProxyHostNameKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyHostNameKey");
return kCFProxyHostNameKey;
}
}
static NSString kCFProxyPasswordKey;
static NSString PasswordKey {
get {
if (kCFProxyPasswordKey == null)
kCFProxyPasswordKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyPasswordKey");
return kCFProxyPasswordKey;
}
}
static NSString kCFProxyPortNumberKey;
static NSString PortNumberKey {
get {
if (kCFProxyPortNumberKey == null)
kCFProxyPortNumberKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyPortNumberKey");
return kCFProxyPortNumberKey;
}
}
static NSString kCFProxyTypeKey;
static NSString ProxyTypeKey {
get {
if (kCFProxyTypeKey == null)
kCFProxyTypeKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeKey");
return kCFProxyTypeKey;
}
}
static NSString kCFProxyUsernameKey;
static NSString UsernameKey {
get {
if (kCFProxyUsernameKey == null)
kCFProxyUsernameKey = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyUsernameKey");
return kCFProxyUsernameKey;
}
}
#endregion Property Keys
#region Proxy Types
static NSString kCFProxyTypeNone;
static NSString CFProxyTypeNone {
get {
if (kCFProxyTypeNone == null)
kCFProxyTypeNone = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeNone");
return kCFProxyTypeNone;
}
}
static NSString kCFProxyTypeAutoConfigurationURL;
static NSString CFProxyTypeAutoConfigurationURL {
get {
if (kCFProxyTypeAutoConfigurationURL == null)
kCFProxyTypeAutoConfigurationURL = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeAutoConfigurationURL");
return kCFProxyTypeAutoConfigurationURL;
}
}
static NSString kCFProxyTypeAutoConfigurationJavaScript;
static NSString CFProxyTypeAutoConfigurationJavaScript {
get {
if (kCFProxyTypeAutoConfigurationJavaScript == null)
kCFProxyTypeAutoConfigurationJavaScript = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeAutoConfigurationJavaScript");
return kCFProxyTypeAutoConfigurationJavaScript;
}
}
static NSString kCFProxyTypeFTP;
static NSString CFProxyTypeFTP {
get {
if (kCFProxyTypeFTP == null)
kCFProxyTypeFTP = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeFTP");
return kCFProxyTypeFTP;
}
}
static NSString kCFProxyTypeHTTP;
static NSString CFProxyTypeHTTP {
get {
if (kCFProxyTypeHTTP == null)
kCFProxyTypeHTTP = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeHTTP");
return kCFProxyTypeHTTP;
}
}
static NSString kCFProxyTypeHTTPS;
static NSString CFProxyTypeHTTPS {
get {
if (kCFProxyTypeHTTPS == null)
kCFProxyTypeHTTPS = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeHTTPS");
return kCFProxyTypeHTTPS;
}
}
static NSString kCFProxyTypeSOCKS;
static NSString CFProxyTypeSOCKS {
get {
if (kCFProxyTypeSOCKS == null)
kCFProxyTypeSOCKS = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFProxyTypeSOCKS");
return kCFProxyTypeSOCKS;
}
}
#endregion Proxy Types
static CFProxyType CFProxyTypeToEnum (NSString type)
{
if (CFProxyTypeAutoConfigurationJavaScript != null) {
if (type.Handle == CFProxyTypeAutoConfigurationJavaScript.Handle)
return CFProxyType.AutoConfigurationJavaScript;
}
if (CFProxyTypeAutoConfigurationURL != null) {
if (type.Handle == CFProxyTypeAutoConfigurationURL.Handle)
return CFProxyType.AutoConfigurationUrl;
}
if (CFProxyTypeFTP != null) {
if (type.Handle == CFProxyTypeFTP.Handle)
return CFProxyType.FTP;
}
if (CFProxyTypeHTTP != null) {
if (type.Handle == CFProxyTypeHTTP.Handle)
return CFProxyType.HTTP;
}
if (CFProxyTypeHTTP != null) {
if (type.Handle == CFProxyTypeHTTPS.Handle)
return CFProxyType.HTTPS;
}
if (CFProxyTypeSOCKS != null) {
if (type.Handle == CFProxyTypeSOCKS.Handle)
return CFProxyType.SOCKS;
}
return CFProxyType.None;
}
#if false
// AFAICT these get used with CFNetworkExecuteProxyAutoConfiguration*()
// TODO: bind CFHTTPMessage so we can return the proper type here.
public NSObject AutoConfigurationHTTPResponse {
get { return settings[AutoConfigurationHTTPResponseKey]; }
}
#endif
[Since (4, 0)][Lion]
public NSString AutoConfigurationJavaScript {
get {
if (AutoConfigurationJavaScriptKey == null)
return null;
return (NSString) settings[AutoConfigurationJavaScriptKey];
}
}
public NSUrl AutoConfigurationUrl {
get {
if (AutoConfigurationURLKey == null)
return null;
return (NSUrl) settings[AutoConfigurationURLKey];
}
}
public string HostName {
get {
if (HostNameKey == null)
return null;
NSString v = (NSString) settings[HostNameKey];
return v != null ? v.ToString () : null;
}
}
public string Password {
get {
if (PasswordKey == null)
return null;
NSString v = (NSString) settings[PasswordKey];
return v != null ? v.ToString () : null;
}
}
public int Port {
get {
if (PortNumberKey == null)
return 0;
NSNumber v = (NSNumber) settings[PortNumberKey];
return v != null ? v.Int32Value : 0;
}
}
public CFProxyType ProxyType {
get {
if (ProxyTypeKey == null)
return CFProxyType.None;
return CFProxyTypeToEnum ((NSString) settings[ProxyTypeKey]);
}
}
public string Username {
get {
if (UsernameKey == null)
return null;
NSString v = (NSString) settings[UsernameKey];
return v != null ? v.ToString () : null;
}
}
}
public class CFProxySettings {
NSDictionary settings;
internal CFProxySettings (NSDictionary settings)
{
this.settings = settings;
}
public NSDictionary Dictionary {
get { return settings; }
}
#region Global Proxy Setting Constants
static NSString kCFNetworkProxiesHTTPEnable;
static NSString CFNetworkProxiesHTTPEnable {
get {
if (kCFNetworkProxiesHTTPEnable == null)
kCFNetworkProxiesHTTPEnable = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFNetworkProxiesHTTPEnable");
return kCFNetworkProxiesHTTPEnable;
}
}
static NSString kCFNetworkProxiesHTTPPort;
static NSString CFNetworkProxiesHTTPPort {
get {
if (kCFNetworkProxiesHTTPPort == null)
kCFNetworkProxiesHTTPPort = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFNetworkProxiesHTTPPort");
return kCFNetworkProxiesHTTPPort;
}
}
static NSString kCFNetworkProxiesHTTPProxy;
static NSString CFNetworkProxiesHTTPProxy {
get {
if (kCFNetworkProxiesHTTPProxy == null)
kCFNetworkProxiesHTTPProxy = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFNetworkProxiesHTTPProxy");
return kCFNetworkProxiesHTTPProxy;
}
}
static NSString kCFNetworkProxiesProxyAutoConfigEnable;
static NSString CFNetworkProxiesProxyAutoConfigEnable {
get {
if (kCFNetworkProxiesProxyAutoConfigEnable == null)
kCFNetworkProxiesProxyAutoConfigEnable = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFNetworkProxiesProxyAutoConfigEnable");
return kCFNetworkProxiesProxyAutoConfigEnable;
}
}
static NSString kCFNetworkProxiesProxyAutoConfigJavaScript;
static NSString CFNetworkProxiesProxyAutoConfigJavaScript {
get {
if (kCFNetworkProxiesProxyAutoConfigJavaScript == null)
kCFNetworkProxiesProxyAutoConfigJavaScript = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFNetworkProxiesProxyAutoConfigJavaScript");
return kCFNetworkProxiesProxyAutoConfigJavaScript;
}
}
static NSString kCFNetworkProxiesProxyAutoConfigURLString;
static NSString CFNetworkProxiesProxyAutoConfigURLString {
get {
if (kCFNetworkProxiesProxyAutoConfigURLString == null)
kCFNetworkProxiesProxyAutoConfigURLString = Dlfcn.GetStringConstant (CFNetwork.CFNetworkLibraryHandle, "kCFNetworkProxiesProxyAutoConfigURLString");
return kCFNetworkProxiesProxyAutoConfigURLString;
}
}
#endregion Global Proxy Setting Constants
public bool HTTPEnable {
get {
if (CFNetworkProxiesHTTPEnable == null)
return false;
NSNumber v = (NSNumber) settings[CFNetworkProxiesHTTPEnable];
return v != null ? v.BoolValue : false;
}
}
public int HTTPPort {
get {
if (CFNetworkProxiesHTTPPort == null)
return 0;
NSNumber v = (NSNumber) settings[CFNetworkProxiesHTTPPort];
return v != null ? v.Int32Value : 0;
}
}
public string HTTPProxy {
get {
if (CFNetworkProxiesHTTPProxy == null)
return null;
NSString v = (NSString) settings[CFNetworkProxiesHTTPProxy];
return v != null ? v.ToString () : null;
}
}
public bool ProxyAutoConfigEnable {
get {
if (CFNetworkProxiesProxyAutoConfigEnable == null)
return false;
NSNumber v = (NSNumber) settings[CFNetworkProxiesProxyAutoConfigEnable];
return v != null ? v.BoolValue : false;
}
}
public string ProxyAutoConfigJavaScript {
get {
if (CFNetworkProxiesProxyAutoConfigJavaScript == null)
return null;
NSString v = (NSString) settings[CFNetworkProxiesProxyAutoConfigJavaScript];
return v != null ? v.ToString () : null;
}
}
public string ProxyAutoConfigURLString {
get {
if (CFNetworkProxiesProxyAutoConfigURLString == null)
return null;
NSString v = (NSString) settings[CFNetworkProxiesProxyAutoConfigURLString];
return v != null ? v.ToString () : null;
}
}
}
public static class CFNetwork {
internal static IntPtr CFNetworkLibraryHandle = Dlfcn.dlopen (Constants.CFNetworkLibrary, 0);
[DllImport (Constants.CFNetworkLibrary)]
// CFArrayRef CFNetworkCopyProxiesForAutoConfigurationScript (CFStringRef proxyAutoConfigurationScript, CFURLRef targetURL);
extern static IntPtr CFNetworkCopyProxiesForAutoConfigurationScript (IntPtr proxyAutoConfigurationScript, IntPtr targetURL);
static NSArray CopyProxiesForAutoConfigurationScript (NSString proxyAutoConfigurationScript, NSUrl targetURL)
{
IntPtr native = CFNetworkCopyProxiesForAutoConfigurationScript (proxyAutoConfigurationScript.Handle, targetURL.Handle);
if (native == IntPtr.Zero)
return null;
return new NSArray (native);
}
public static CFProxy[] GetProxiesForAutoConfigurationScript (NSString proxyAutoConfigurationScript, NSUrl targetURL)
{
if (proxyAutoConfigurationScript == null)
throw new ArgumentNullException ("proxyAutoConfigurationScript");
if (targetURL == null)
throw new ArgumentNullException ("targetURL");
NSArray array = CopyProxiesForAutoConfigurationScript (proxyAutoConfigurationScript, targetURL);
if (array == null)
return null;
NSDictionary[] dictionaries = NSArray.ArrayFromHandle<NSDictionary> (array.Handle);
array.Dispose ();
if (dictionaries == null)
return null;
CFProxy[] proxies = new CFProxy [dictionaries.Length];
for (int i = 0; i < dictionaries.Length; i++)
proxies[i] = new CFProxy (dictionaries[i]);
return proxies;
}
public static CFProxy[] GetProxiesForAutoConfigurationScript (NSString proxyAutoConfigurationScript, Uri targetUri)
{
if (proxyAutoConfigurationScript == null)
throw new ArgumentNullException ("proxyAutoConfigurationScript");
if (targetUri == null)
throw new ArgumentNullException ("targetUri");
NSUrl targetURL = new NSUrl (targetUri.AbsoluteUri);
CFProxy[] proxies = GetProxiesForAutoConfigurationScript (proxyAutoConfigurationScript, targetURL);
targetURL.Dispose ();
return proxies;
}
[DllImport (Constants.CFNetworkLibrary)]
// CFArrayRef CFNetworkCopyProxiesForURL (CFURLRef url, CFDictionaryRef proxySettings);
extern static IntPtr CFNetworkCopyProxiesForURL (IntPtr url, IntPtr proxySettings);
static NSArray CopyProxiesForURL (NSUrl url, NSDictionary proxySettings)
{
IntPtr native = CFNetworkCopyProxiesForURL (url.Handle, proxySettings != null ? proxySettings.Handle : IntPtr.Zero);
if (native == IntPtr.Zero)
return null;
return new NSArray (native);
}
public static CFProxy[] GetProxiesForURL (NSUrl url, CFProxySettings proxySettings)
{
if (url == null || (url.Handle == IntPtr.Zero))
throw new ArgumentNullException ("url");
if (proxySettings == null)
proxySettings = GetSystemProxySettings ();
NSArray array = CopyProxiesForURL (url, proxySettings.Dictionary);
if (array == null)
return null;
NSDictionary[] dictionaries = NSArray.ArrayFromHandle<NSDictionary> (array.Handle);
array.Dispose ();
if (dictionaries == null)
return null;
CFProxy[] proxies = new CFProxy [dictionaries.Length];
for (int i = 0; i < dictionaries.Length; i++)
proxies[i] = new CFProxy (dictionaries[i]);
return proxies;
}
public static CFProxy[] GetProxiesForUri (Uri uri, CFProxySettings proxySettings)
{
if (uri == null)
throw new ArgumentNullException ("uri");
NSUrl url = NSUrl.FromString (uri.AbsoluteUri);
if (url == null)
return null;
CFProxy[] proxies = GetProxiesForURL (url, proxySettings);
url.Dispose ();
return proxies;
}
[DllImport (Constants.CFNetworkLibrary)]
// CFDictionaryRef CFNetworkCopySystemProxySettings (void);
extern static IntPtr CFNetworkCopySystemProxySettings ();
public static CFProxySettings GetSystemProxySettings ()
{
IntPtr native = CFNetworkCopySystemProxySettings ();
if (native == IntPtr.Zero)
return null;
var dict = new NSDictionary (native);
// Must release since the IntPtr constructor calls Retain and
// CFNetworkCopySystemProxySettings return value is already retained
dict.Release ();
return new CFProxySettings (dict);
}
#if notyet
// FIXME: These require bindings for CFRunLoopSource and CFStreamClientContext
public delegate void CFProxyAutoConfigurationResultCallback (IntPtr client, NSArray proxyList, NSError error);
[DllImport (Constants.CFNetworkLibrary)]
// CFRunLoopSourceRef CFNetworkExecuteProxyAutoConfigurationScript (CFStringRef proxyAutoConfigurationScript, CFURLRef targetURL, CFProxyAutoConfigurationResultCallback cb, CFStreamClientContext *clientContext);
extern static IntPtr CFNetworkExecuteProxyAutoConfigurationScript (IntPtr proxyAutoConfigurationScript, IntPtr targetURL, IntPtr cb, IntPtr clientContext);
public static CFRunLoopSource ExecuteProxyAutoConfigurationScript (NSString proxyAutoConfigurationScript, NSUrl targetURL, CFProxyAutoConfigurationResultCallback resultCallback, CFStreamClientContext clientContext)
{
if (proxyAutoConfigurationScript == null)
throw new ArgumentNullException ("proxyAutoConfigurationScript");
if (targetURL == null)
throw new ArgumentNullException ("targetURL");
if (resultCallback == null)
throw new ArgumentNullException ("resultCallback");
if (clientContext == null)
throw new ArgumentNullException ("clientContext");
IntPtr source = CFNetworkExecuteProxyAutoConfigurationScript (proxyAutoConfigurationScript.Handle, targetURL.Handle, resultCallback, clientContext);
if (source != IntPtr.Zero)
return new CFRunLoopSource (source);
return null;
}
[DllImport (Constants.CFNetworkLibrary)]
// CFRunLoopSourceRef CFNetworkExecuteProxyAutoConfigurationURL (CFURLRef proxyAutoConfigurationURL, CFURLRef targetURL, CFProxyAutoConfigurationResultCallback cb, CFStreamClientContext *clientContext);
extern static IntPtr CFNetworkExecuteProxyAutoConfigurationURL (IntPtr proxyAutoConfigurationURL, IntPtr targetURL, IntPtr cb, IntPtr clientContext);
public static CFRunLoopSource ExecuteProxyAutoConfigurationURL (NSUrl proxyAutoConfigurationURL, NSUrl targetURL, CFProxyAutoConfigurationResultCallback resultCallback, CFStreamClientContext clientContext)
{
if (proxyAutoConfigurationURL == null)
throw new ArgumentNullException ("proxyAutoConfigurationURL");
if (targetURL == null)
throw new ArgumentNullException ("targetURL");
if (resultCallback == null)
throw new ArgumentNullException ("resultCallback");
if (clientContext == null)
throw new ArgumentNullException ("clientContext");
IntPtr source = CFNetworkExecuteProxyAutoConfigurationURL (proxyAutoConfigurationURL.Handle, targetURL.Handle, resultCallback, clientContext);
if (source != IntPtr.Zero)
return new CFRunLoopSource (source);
return null;
}
#endif
class CFWebProxy : IWebProxy {
ICredentials credentials;
bool userSpecified;
public CFWebProxy ()
{
}
public ICredentials Credentials {
get { return credentials; }
set {
userSpecified = true;
credentials = value;
}
}
static Uri GetProxyUri (CFProxy proxy, out NetworkCredential credentials)
{
string protocol;
switch (proxy.ProxyType) {
case CFProxyType.FTP:
protocol = "ftp://";
break;
case CFProxyType.HTTP:
case CFProxyType.HTTPS:
protocol = "http://";
break;
default:
credentials = null;
return null;
}
string username = proxy.Username;
string password = proxy.Password;
string hostname = proxy.HostName;
int port = proxy.Port;
string uri;
if (username != null)
credentials = new NetworkCredential (username, password);
else
credentials = null;
uri = protocol + hostname + (port != 0 ? ':' + port.ToString () : string.Empty);
return new Uri (uri, UriKind.Absolute);
}
static Uri GetProxyUriFromScript (NSString script, Uri targetUri, out NetworkCredential credentials)
{
CFProxy[] proxies = CFNetwork.GetProxiesForAutoConfigurationScript (script, targetUri);
if (proxies == null) {
credentials = null;
return targetUri;
}
for (int i = 0; i < proxies.Length; i++) {
switch (proxies[i].ProxyType) {
case CFProxyType.HTTPS:
case CFProxyType.HTTP:
case CFProxyType.FTP:
// create a Uri based on the hostname/port/etc info
return GetProxyUri (proxies[i], out credentials);
case CFProxyType.SOCKS:
default:
// unsupported proxy type, try the next one
break;
case CFProxyType.None:
// no proxy should be used
credentials = null;
return targetUri;
}
}
credentials = null;
return null;
}
public Uri GetProxy (Uri targetUri)
{
NetworkCredential credentials = null;
Uri proxy = null;
if (targetUri == null)
throw new ArgumentNullException ("targetUri");
try {
CFProxySettings settings = CFNetwork.GetSystemProxySettings ();
CFProxy[] proxies = CFNetwork.GetProxiesForUri (targetUri, settings);
if (proxies != null) {
for (int i = 0; i < proxies.Length && proxy == null; i++) {
switch (proxies[i].ProxyType) {
case CFProxyType.AutoConfigurationJavaScript:
proxy = GetProxyUriFromScript (proxies[i].AutoConfigurationJavaScript, targetUri, out credentials);
break;
case CFProxyType.AutoConfigurationUrl:
// unsupported proxy type (requires fetching script from remote url)
break;
case CFProxyType.HTTPS:
case CFProxyType.HTTP:
case CFProxyType.FTP:
// create a Uri based on the hostname/port/etc info
proxy = GetProxyUri (proxies[i], out credentials);
break;
case CFProxyType.SOCKS:
// unsupported proxy type, try the next one
break;
case CFProxyType.None:
// no proxy should be used
proxy = targetUri;
break;
}
}
if (proxy == null) {
// no supported proxies for this Uri, fall back to trying to connect to targetUri directly
proxy = targetUri;
}
} else {
proxy = targetUri;
}
} catch {
// ignore errors while retrieving proxy data
proxy = targetUri;
}
if (!userSpecified)
this.credentials = credentials;
return proxy;
}
public bool IsBypassed (Uri targetUri)
{
if (targetUri == null)
throw new ArgumentNullException ("targetUri");
return GetProxy (targetUri) == targetUri;
}
}
public static IWebProxy GetDefaultProxy ()
{
return new CFWebProxy ();
}
}
}
| |
using System.Diagnostics;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Lucene.Net.Util;
using System;
//Used to hold non-generic nested types
public static class FieldValueHitQueue
{
// had to change from internal to public, due to public accessability of FieldValueHitQueue
public class Entry : ScoreDoc
{
internal int Slot;
internal Entry(int slot, int doc, float score)
: base(doc, score)
{
this.Slot = slot;
}
public override string ToString()
{
return "slot:" + Slot + " " + base.ToString();
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is just one comparator.
/// </summary>
internal sealed class OneComparatorFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
private int oneReverseMul;
public OneComparatorFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
if (fields.Length == 0)
{
throw new System.ArgumentException("Sort must contain at least one field");
}
SortField field = fields[0];
SetComparator(0, field.GetComparator(size, 0));
oneReverseMul = field.reverse ? -1 : 1;
ReverseMul[0] = oneReverseMul;
}
/// <summary> Returns whether <c>a</c> is less relevant than <c>b</c>.</summary>
/// <param name="hitA">ScoreDoc</param>
/// <param name="hitB">ScoreDoc</param>
/// <returns><c>true</c> if document <c>a</c> should be sorted after document <c>b</c>.</returns>
public override bool LessThan(T hitA, T hitB)
{
Debug.Assert(hitA != hitB);
Debug.Assert(hitA.Slot != hitB.Slot);
int c = oneReverseMul * FirstComparator.Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
return c > 0;
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
public override bool LessThan(Entry a, Entry b)
{
return LessThan(a, b);
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is more than one comparator.
/// </summary>
internal sealed class MultiComparatorsFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
public MultiComparatorsFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
int numComparators = comparators.Length;
for (int i = 0; i < numComparators; ++i)
{
SortField field = fields[i];
ReverseMul[i] = field.reverse ? -1 : 1;
SetComparator(i, field.GetComparator(size, i));
}
}
public override bool LessThan(T hitA, T hitB)
{
Debug.Assert(hitA != hitB);
Debug.Assert(hitA.Slot != hitB.Slot);
int numComparators = comparators.Length;
for (int i = 0; i < numComparators; ++i)
{
int c = ReverseMul[i] * comparators[i].Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
// Short circuit
return c > 0;
}
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
public override bool LessThan(Entry a, Entry b)
{
return LessThan(a, b);
}
}
/// <summary> Creates a hit queue sorted by the given list of fields.
///
/// <p/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length <c>numHits</c>.
///
/// </summary>
/// <param name="fields">SortField array we are sorting by in priority order (highest
/// priority first); cannot be <c>null</c> or empty
/// </param>
/// <param name="size">The number of hits to retain. Must be greater than zero.
/// </param>
/// <throws> IOException </throws>
public static FieldValueHitQueue<T> Create<T>(SortField[] fields, int size)
where T : FieldValueHitQueue.Entry
{
if (fields.Length == 0)
{
throw new ArgumentException("Sort must contain at least one field");
}
if (fields.Length == 1)
{
return new FieldValueHitQueue.OneComparatorFieldValueHitQueue<T>(fields, size);
}
else
{
return new FieldValueHitQueue.MultiComparatorsFieldValueHitQueue<T>(fields, size);
}
}
}
/// <summary>
/// Expert: A hit queue for sorting by hits by terms in more than one field.
/// Uses <code>FieldCache.DEFAULT</code> for maintaining
/// internal term lookup tables.
///
/// @lucene.experimental
/// @since 2.9 </summary>
/// <seealso cref= IndexSearcher#search(Query,Filter,int,Sort) </seealso>
/// <seealso cref= FieldCache </seealso>
public abstract class FieldValueHitQueue<T> : PriorityQueue<T>
where T : FieldValueHitQueue.Entry
{
// prevent instantiation and extension.
internal FieldValueHitQueue(SortField[] fields, int size)
: base(size)
{
// When we get here, fields.length is guaranteed to be > 0, therefore no
// need to check it again.
// All these are required by this class's API - need to return arrays.
// Therefore even in the case of a single comparator, create an array
// anyway.
this.fields = fields;
int numComparators = fields.Length;
comparators = new FieldComparator[numComparators];
reverseMul = new int[numComparators];
}
public virtual FieldComparator[] Comparators
{
get
{
return comparators;
}
}
public virtual int[] ReverseMul
{
get
{
return reverseMul;
}
}
public virtual void SetComparator(int pos, FieldComparator comparator)
{
if (pos == 0)
{
FirstComparator = comparator;
}
comparators[pos] = comparator;
}
/// <summary>
/// Stores the sort criteria being used. </summary>
protected internal readonly SortField[] fields;
protected internal readonly FieldComparator[] comparators; // use setComparator to change this array
protected internal FieldComparator FirstComparator; // this must always be equal to comparators[0]
protected internal readonly int[] reverseMul;
public abstract bool LessThan(FieldValueHitQueue.Entry a, FieldValueHitQueue.Entry b);
/// <summary>
/// Given a queue Entry, creates a corresponding FieldDoc
/// that contains the values used to sort the given document.
/// These values are not the raw values out of the index, but the internal
/// representation of them. this is so the given search hit can be collated by
/// a MultiSearcher with other search hits.
/// </summary>
/// <param name="entry"> The Entry used to create a FieldDoc </param>
/// <returns> The newly created FieldDoc </returns>
/// <seealso cref= IndexSearcher#search(Query,Filter,int,Sort) </seealso>
internal virtual FieldDoc FillFields(FieldValueHitQueue.Entry entry)
{
int n = Comparators.Length;
IComparable[] fields = new IComparable[n];
for (int i = 0; i < n; ++i)
{
fields[i] = Comparators[i].Value(entry.Slot);
}
//if (maxscore > 1.0f) doc.score /= maxscore; // normalize scores
return new FieldDoc(entry.Doc, entry.Score, fields);
}
/// <summary>
/// Returns the SortFields being used by this hit queue. </summary>
internal virtual SortField[] Fields
{
get
{
return fields;
}
}
}
}
| |
//
// MultipartReader.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Couchbase.Lite.Support;
using Sharpen;
using System.Collections.ObjectModel;
namespace Couchbase.Lite.Support
{
public class MultipartReader
{
private enum MultipartReaderState
{
kUninitialized,
kAtStart,
kInPrologue,
kInBody,
kInHeaders,
kAtEnd,
kFailed
}
private static readonly Encoding utf8 = Extensions.GetEncoding("UTF-8");
private static readonly Byte[] kCRLFCRLF;
static MultipartReader()
{
kCRLFCRLF = utf8.GetBytes("\r\n\r\n");
}
private MultipartReader.MultipartReaderState state;
private List<Byte> buffer;
private readonly String contentType;
private byte[] boundary;
private IMultipartReaderDelegate readerDelegate;
public IDictionary<String, String> headers;
public MultipartReader(string contentType, IMultipartReaderDelegate readerDelegate)
{
this.contentType = contentType;
this.readerDelegate = readerDelegate;
this.buffer = new List<Byte>(1024);
this.state = MultipartReader.MultipartReaderState.kAtStart;
ParseContentType();
}
public byte[] GetBoundary()
{
return boundary;
}
public byte[] GetBoundaryWithoutLeadingCRLF()
{
var rawBoundary = GetBoundary();
var result = new ArraySegment<Byte>(rawBoundary, 2, rawBoundary.Length);
return result.Array;
}
public bool Finished()
{
return state == MultipartReader.MultipartReaderState.kAtEnd;
}
private static Byte[] EOMBytes()
{
return Encoding.UTF8.GetBytes("--");
}
private bool Memcmp(byte[] array1, byte[] array2, int len)
{
bool equals = true;
for (int i = 0; i < len; i++)
{
if (array1[i] != array2[i])
{
equals = false;
}
}
return equals;
}
public Range SearchFor(byte[] pattern, int start)
{
var searcher = new KMPMatch();
var matchIndex = searcher.IndexOf(buffer.ToArray(), pattern, start);
return matchIndex != -1
? new Range (matchIndex, pattern.Length)
: new Range (matchIndex, 0);
}
public void ParseHeaders(string headersStr)
{
headers = new Dictionary<String, String>();
if (!string.IsNullOrEmpty (headersStr)) {
headersStr = headersStr.Trim ();
var tokenizer = headersStr.Split(new[] { "\r\n" }, StringSplitOptions.None);
foreach (var header in tokenizer) {
if (!header.Contains (":")) {
throw new ArgumentException ("Missing ':' in header line: " + header);
}
var headerTokenizer = header.Split(':');
var key = headerTokenizer[0].Trim ();
var value = headerTokenizer[1].Trim ();
headers.Put (key, value);
}
}
}
private void DeleteUpThrough(int location)
{
// int start = location + 1; // start at the first byte after the location
var newBuffer = new ArraySegment<Byte>(buffer.ToArray(), location, buffer.Count);
buffer.Clear();
buffer.AddRange(newBuffer);
}
private void TrimBuffer()
{
int bufLen = buffer.Count;
int boundaryLen = GetBoundary().Length;
if (bufLen > boundaryLen)
{
// Leave enough bytes in _buffer that we can find an incomplete boundary string
var dataToAppend = new ArraySegment<Byte>(buffer.ToArray(), 0, bufLen - boundaryLen).Array;
buffer.Clear();
readerDelegate.AppendToPart(dataToAppend);
DeleteUpThrough(bufLen - boundaryLen);
}
}
public void AppendData(byte[] data)
{
if (buffer == null)
{
return;
}
if (data.Length == 0)
{
return;
}
buffer.AddRange(data);
MultipartReader.MultipartReaderState nextState;
do
{
nextState = MultipartReader.MultipartReaderState.kUninitialized;
var bufLen = buffer.Count;
switch (state)
{
case MultipartReader.MultipartReaderState.kAtStart:
{
// Log.d(Database.TAG, "appendData. bufLen: " + bufLen);
// The entire message might start with a boundary without a leading CRLF.
var boundaryWithoutLeadingCRLF = GetBoundaryWithoutLeadingCRLF();
if (bufLen >= boundaryWithoutLeadingCRLF.Length)
{
// if (Arrays.equals(buffer.toByteArray(), boundaryWithoutLeadingCRLF)) {
if (Memcmp(buffer.ToArray(), boundaryWithoutLeadingCRLF, boundaryWithoutLeadingCRLF.Length))
{
DeleteUpThrough(boundaryWithoutLeadingCRLF.Length);
nextState = MultipartReader.MultipartReaderState.kInHeaders;
}
else
{
nextState = MultipartReader.MultipartReaderState.kInPrologue;
}
}
break;
}
case MultipartReader.MultipartReaderState.kInPrologue:
case MultipartReader.MultipartReaderState.kInBody:
{
// Look for the next part boundary in the data we just added and the ending bytes of
// the previous data (in case the boundary string is split across calls)
if (bufLen < boundary.Length)
{
break;
}
var start = Math.Max(0, bufLen - data.Length - boundary.Length);
var r = SearchFor(boundary, start);
if (r.GetLength() > 0)
{
if (state == MultipartReader.MultipartReaderState.kInBody)
{
var dataToAppend = new ArraySegment<Byte>(buffer.ToArray(), 0, r.GetLocation());
readerDelegate.AppendToPart(dataToAppend);
readerDelegate.FinishedPart();
}
DeleteUpThrough(r.GetLocation() + r.GetLength());
nextState = MultipartReader.MultipartReaderState.kInHeaders;
}
else
{
TrimBuffer();
}
break;
}
case MultipartReader.MultipartReaderState.kInHeaders:
{
// First check for the end-of-message string ("--" after separator):
if (bufLen >= 2 && Memcmp(buffer.ToArray(), EOMBytes(), 2))
{
state = MultipartReader.MultipartReaderState.kAtEnd;
Close();
return;
}
// Otherwise look for two CRLFs that delimit the end of the headers:
var r = SearchFor(kCRLFCRLF, 0);
if (r.GetLength() > 0)
{
var headersBytes = Arrays.CopyTo(buffer.ToArray(), r.GetLocation()); //
// var headersBytes = new ArraySegment<Byte>(buffer.ToArray(), 0, r.GetLocation()); // <-- better?
var headersString = utf8.GetString(headersBytes);
ParseHeaders(headersString);
DeleteUpThrough(r.GetLocation() + r.GetLength());
readerDelegate.StartedPart(headers);
nextState = MultipartReader.MultipartReaderState.kInBody;
}
break;
}
default:
{
throw new InvalidOperationException("Unexpected data after end of MIME body");
}
}
if (nextState != MultipartReader.MultipartReaderState.kUninitialized)
{
state = nextState;
}
}
while (nextState != MultipartReader.MultipartReaderState.kUninitialized && buffer.Count > 0);
}
private void Close()
{
buffer = null;
boundary = null;
}
private void ParseContentType()
{
var tokenizer = contentType.Split(';');
bool first = true;
foreach (var token in tokenizer)
{
string param = token.Trim();
if (first)
{
if (!param.StartsWith("multipart/", StringComparison.InvariantCultureIgnoreCase))
{
throw new ArgumentException(contentType + " does not start with multipart/");
}
first = false;
}
else
{
if (param.StartsWith("boundary=", StringComparison.InvariantCultureIgnoreCase))
{
var tempBoundary = param.Substring(9);
if (tempBoundary.StartsWith ("\"", StringComparison.InvariantCultureIgnoreCase))
{
if (tempBoundary.Length < 2 || !tempBoundary.EndsWith ("\"", StringComparison.InvariantCultureIgnoreCase)) {
throw new ArgumentException (contentType + " is not valid");
}
tempBoundary = tempBoundary.Substring(1, tempBoundary.Length - 1);
}
if (tempBoundary.Length < 1)
{
throw new ArgumentException(contentType + " has zero-length boundary");
}
tempBoundary = string.Format("\r\n--{0}", tempBoundary);
boundary = Encoding.UTF8.GetBytes(tempBoundary);
break;
}
}
}
}
}
/// <summary>Knuth-Morris-Pratt Algorithm for Pattern Matching</summary>
internal class KMPMatch
{
/// <summary>Finds the first occurrence of the pattern in the text.</summary>
/// <remarks>Finds the first occurrence of the pattern in the text.</remarks>
public int IndexOf(byte[] data, byte[] pattern, int dataOffset)
{
int[] failure = ComputeFailure(pattern);
int j = 0;
if (data.Length == 0)
{
return -1;
}
int dataLength = data.Length;
int patternLength = pattern.Length;
for (int i = dataOffset; i < dataLength; i++)
{
while (j > 0 && pattern[j] != data[i])
{
j = failure[j - 1];
}
if (pattern[j] == data[i])
{
j++;
}
if (j == patternLength)
{
return i - patternLength + 1;
}
}
return -1;
}
/// <summary>
/// Computes the failure function using a boot-strapping process,
/// where the pattern is matched against itself.
/// </summary>
/// <remarks>
/// Computes the failure function using a boot-strapping process,
/// where the pattern is matched against itself.
/// </remarks>
private int[] ComputeFailure(byte[] pattern)
{
int[] failure = new int[pattern.Length];
int j = 0;
for (int i = 1; i < pattern.Length; i++)
{
while (j > 0 && pattern[j] != pattern[i])
{
j = failure[j - 1];
}
if (pattern[j] == pattern[i])
{
j++;
}
failure[i] = j;
}
return failure;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Globalization.Tests
{
public class CharUnicodeInfoGetUnicodeCategoryTests
{
[Fact]
public void GetUnicodeCategory()
{
foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases)
{
if (testCase.Utf32CodeValue.Length == 1)
{
// Test the char overload for a single char
GetUnicodeCategory(testCase.Utf32CodeValue[0], testCase.GeneralCategory);
}
// Test the string overload for a surrogate pair or a single char
GetUnicodeCategory(testCase.Utf32CodeValue, new UnicodeCategory[] { testCase.GeneralCategory });
#if NETCOREAPP
Assert.Equal(testCase.GeneralCategory, CharUnicodeInfo.GetUnicodeCategory(testCase.CodePoint));
#endif
}
}
[Theory]
[InlineData('\uFFFF', UnicodeCategory.OtherNotAssigned)]
public void GetUnicodeCategory(char ch, UnicodeCategory expected)
{
UnicodeCategory actual = CharUnicodeInfo.GetUnicodeCategory(ch);
Assert.True(actual == expected, ErrorMessage(ch, expected, actual));
}
[Theory]
[InlineData("aA1!", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation })]
[InlineData("\uD808\uDF6C", new UnicodeCategory[] { UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate })]
[InlineData("a\uD808\uDF6Ca", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate, UnicodeCategory.LowercaseLetter })]
public void GetUnicodeCategory(string s, UnicodeCategory[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], CharUnicodeInfo.GetUnicodeCategory(s, i));
}
}
[Fact]
public void GetUnicodeCategory_String_InvalidSurrogatePairs()
{
// High, high surrogate pair
GetUnicodeCategory("\uD808\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate });
// Low, low surrogate pair
GetUnicodeCategory("\uDF6C\uDF6C", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate });
// Low, high surrogate pair
GetUnicodeCategory("\uDF6C\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate });
}
[Fact]
public void GetUnicodeCategory_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetUnicodeCategory(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("", 0));
}
[Fact]
public void GetNumericValue()
{
foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases)
{
if (testCase.Utf32CodeValue.Length == 1)
{
// Test the char overload for a single char
GetNumericValue(testCase.Utf32CodeValue[0], testCase.NumericValue);
}
// Test the string overload for a surrogate pair
GetNumericValue(testCase.Utf32CodeValue, new double[] { testCase.NumericValue });
}
}
[Theory]
[InlineData('\uFFFF', -1)]
public void GetNumericValue(char ch, double expected)
{
double actual = CharUnicodeInfo.GetNumericValue(ch);
Assert.True(expected == actual, ErrorMessage(ch, expected, actual));
}
[Theory]
[MemberData(nameof(s_GetNumericValueData))]
public void GetNumericValue(string s, double[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], CharUnicodeInfo.GetNumericValue(s, i));
}
}
public static readonly object[][] s_GetNumericValueData =
{
new object[] {"aA1!", new double[] { -1, -1, 1, -1 }},
// Numeric surrogate (CUNEIFORM NUMERIC SIGN FIVE BAN2 VARIANT FORM)
new object[] {"\uD809\uDC55", new double[] { 5, -1 }},
new object[] {"a\uD809\uDC55a", new double[] { -1, 5, -1 , -1 }},
// Numeric surrogate (CUNEIFORM NUMERIC SIGN FIVE BAN2 VARIANT FORM)
new object[] {"\uD808\uDF6C", new double[] { -1, -1 }},
new object[] {"a\uD808\uDF6Ca", new double[] { -1, -1, -1, -1 }},
};
[Fact]
public void GetNumericValue_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetNumericValue(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("", 0));
}
private static string ErrorMessage(char ch, object expected, object actual)
{
return $"CodeValue: {((int)ch).ToString("X")}; Expected: {expected}; Actual: {actual}";
}
public static string s_numericsCodepoints =
"\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039" +
"\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669" +
"\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9" +
"\u07c0\u07c1\u07c2\u07c3\u07c4\u07c5\u07c6\u07c7\u07c8\u07c9" +
"\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f" +
"\u09e6\u09e7\u09e8\u09e9\u09ea\u09eb\u09ec\u09ed\u09ee\u09ef" +
"\u0a66\u0a67\u0a68\u0a69\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f" +
"\u0ae6\u0ae7\u0ae8\u0ae9\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef" +
"\u0b66\u0b67\u0b68\u0b69\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f" +
"\u0be6\u0be7\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef" +
"\u0c66\u0c67\u0c68\u0c69\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f" +
"\u0ce6\u0ce7\u0ce8\u0ce9\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef" +
"\u0d66\u0d67\u0d68\u0d69\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f" +
"\u0e50\u0e51\u0e52\u0e53\u0e54\u0e55\u0e56\u0e57\u0e58\u0e59" +
"\u0ed0\u0ed1\u0ed2\u0ed3\u0ed4\u0ed5\u0ed6\u0ed7\u0ed8\u0ed9" +
"\u0f20\u0f21\u0f22\u0f23\u0f24\u0f25\u0f26\u0f27\u0f28\u0f29" +
"\u1040\u1041\u1042\u1043\u1044\u1045\u1046\u1047\u1048\u1049" +
"\u1090\u1091\u1092\u1093\u1094\u1095\u1096\u1097\u1098\u1099" +
"\u17e0\u17e1\u17e2\u17e3\u17e4\u17e5\u17e6\u17e7\u17e8\u17e9" +
"\u1810\u1811\u1812\u1813\u1814\u1815\u1816\u1817\u1818\u1819" +
"\u1946\u1947\u1948\u1949\u194a\u194b\u194c\u194d\u194e\u194f" +
"\u19d0\u19d1\u19d2\u19d3\u19d4\u19d5\u19d6\u19d7\u19d8\u19d9" +
"\u1a80\u1a81\u1a82\u1a83\u1a84\u1a85\u1a86\u1a87\u1a88\u1a89" +
"\u1a90\u1a91\u1a92\u1a93\u1a94\u1a95\u1a96\u1a97\u1a98\u1a99" +
"\u1b50\u1b51\u1b52\u1b53\u1b54\u1b55\u1b56\u1b57\u1b58\u1b59" +
"\u1bb0\u1bb1\u1bb2\u1bb3\u1bb4\u1bb5\u1bb6\u1bb7\u1bb8\u1bb9" +
"\u1c40\u1c41\u1c42\u1c43\u1c44\u1c45\u1c46\u1c47\u1c48\u1c49" +
"\u1c50\u1c51\u1c52\u1c53\u1c54\u1c55\u1c56\u1c57\u1c58\u1c59" +
"\ua620\ua621\ua622\ua623\ua624\ua625\ua626\ua627\ua628\ua629" +
"\ua8d0\ua8d1\ua8d2\ua8d3\ua8d4\ua8d5\ua8d6\ua8d7\ua8d8\ua8d9" +
"\ua900\ua901\ua902\ua903\ua904\ua905\ua906\ua907\ua908\ua909" +
"\ua9d0\ua9d1\ua9d2\ua9d3\ua9d4\ua9d5\ua9d6\ua9d7\ua9d8\ua9d9" +
"\uaa50\uaa51\uaa52\uaa53\uaa54\uaa55\uaa56\uaa57\uaa58\uaa59" +
"\uabf0\uabf1\uabf2\uabf3\uabf4\uabf5\uabf6\uabf7\uabf8\uabf9" +
"\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19";
public static string s_nonNumericsCodepoints =
"abcdefghijklmnopqrstuvwxyz" +
"\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370\u1371\u1372\u1373" +
"\u1374\u1375\u1376\u1377\u1378\u1379\u137a\u137b\u137c\u137d";
public static string s_numericNonDecimalCodepoints =
"\u00b2\u00b3\u00b9\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370" +
"\u1371\u19da\u2070\u2074\u2075\u2076\u2077\u2078\u2079\u2080\u2081" +
"\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u2460\u2461\u2462" +
"\u2463\u2464\u2465\u2466\u2467\u2468\u2474\u2475\u2476\u2477\u2478" +
"\u2479\u247a\u247b\u247c\u2488\u2489\u248a\u248b\u248c\u248d\u248e" +
"\u248f\u2490\u24ea\u24f5\u24f6\u24f7\u24f8\u24f9\u24fa\u24fb\u24fc" +
"\u24fd\u24ff\u2776\u2777\u2778\u2779\u277a\u277b\u277c\u277d\u277e" +
"\u2780\u2781\u2782\u2783\u2784\u2785\u2786\u2787\u2788\u278a\u278b" +
"\u278c\u278d\u278e\u278f\u2790\u2791\u2792";
public static int [] s_numericNonDecimalValues = new int []
{
2, 3, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 4, 5, 6, 7, 8, 9, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7,
8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6,
7, 8, 9
};
[Fact]
public static void DigitsDecimalTest()
{
Assert.Equal(0, s_numericsCodepoints.Length % 10);
for (int i=0; i < s_numericsCodepoints.Length; i+= 10)
{
for (int j=0; j < 10; j++)
{
Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints[i + j]));
Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints, i + j));
}
}
}
[Fact]
public static void NegativeDigitsTest()
{
for (int i=0; i < s_nonNumericsCodepoints.Length; i++)
{
Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints[i]));
Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints, i));
}
}
[Fact]
public static void DigitsTest()
{
Assert.Equal(s_numericNonDecimalCodepoints.Length, s_numericNonDecimalValues.Length);
for (int i=0; i < s_numericNonDecimalCodepoints.Length; i++)
{
Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints[i]));
Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints, i));
}
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.GroupsModels;
using PlayFab.Internal;
using PlayFab.SharedModels;
namespace PlayFab
{
/// <summary>
/// The Groups API is designed for any permanent or semi-permanent collections of Entities (players, or non-players). If you
/// want to make Guilds/Clans/Corporations/etc., then you should use groups. Groups can also be used to make chatrooms,
/// parties, or any other persistent collection of entities.
/// </summary>
public class PlayFabGroupsInstanceAPI : IPlayFabInstanceApi
{
public readonly PlayFabApiSettings apiSettings = null;
public readonly PlayFabAuthenticationContext authenticationContext = null;
public PlayFabGroupsInstanceAPI(PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or call <PlayFabClientInstanceAPI>.GetAuthenticationContext()");
authenticationContext = context;
}
public PlayFabGroupsInstanceAPI(PlayFabApiSettings settings, PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or call <PlayFabClientInstanceAPI>.GetAuthenticationContext()");
apiSettings = settings;
authenticationContext = context;
}
/// <summary>
/// Verify entity login.
/// </summary>
public bool IsEntityLoggedIn()
{
return authenticationContext == null ? false : authenticationContext.IsEntityLoggedIn();
}
/// <summary>
/// Clear the Client SessionToken which allows this Client to call API calls requiring login.
/// A new/fresh login will be required after calling this.
/// </summary>
public void ForgetAllCredentials()
{
if (authenticationContext != null)
{
authenticationContext.ForgetAllCredentials();
}
}
/// <summary>
/// Accepts an outstanding invitation to to join a group
/// </summary>
public void AcceptGroupApplication(AcceptGroupApplicationRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/AcceptGroupApplication", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Accepts an invitation to join a group
/// </summary>
public void AcceptGroupInvitation(AcceptGroupInvitationRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/AcceptGroupInvitation", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Adds members to a group or role.
/// </summary>
public void AddMembers(AddMembersRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/AddMembers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Applies to join a group
/// </summary>
public void ApplyToGroup(ApplyToGroupRequest request, Action<ApplyToGroupResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ApplyToGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Blocks a list of entities from joining a group.
/// </summary>
public void BlockEntity(BlockEntityRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/BlockEntity", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Changes the role membership of a list of entities from one role to another.
/// </summary>
public void ChangeMemberRole(ChangeMemberRoleRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ChangeMemberRole", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Creates a new group.
/// </summary>
public void CreateGroup(CreateGroupRequest request, Action<CreateGroupResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/CreateGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Creates a new group role.
/// </summary>
public void CreateRole(CreateGroupRoleRequest request, Action<CreateGroupRoleResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/CreateRole", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Deletes a group and all roles, invitations, join requests, and blocks associated with it.
/// </summary>
public void DeleteGroup(DeleteGroupRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/DeleteGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Deletes an existing role in a group.
/// </summary>
public void DeleteRole(DeleteRoleRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/DeleteRole", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Gets information about a group and its roles
/// </summary>
public void GetGroup(GetGroupRequest request, Action<GetGroupResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/GetGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Invites a player to join a group
/// </summary>
public void InviteToGroup(InviteToGroupRequest request, Action<InviteToGroupResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/InviteToGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Checks to see if an entity is a member of a group or role within the group
/// </summary>
public void IsMember(IsMemberRequest request, Action<IsMemberResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/IsMember", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Lists all outstanding requests to join a group
/// </summary>
public void ListGroupApplications(ListGroupApplicationsRequest request, Action<ListGroupApplicationsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ListGroupApplications", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Lists all entities blocked from joining a group
/// </summary>
public void ListGroupBlocks(ListGroupBlocksRequest request, Action<ListGroupBlocksResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ListGroupBlocks", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Lists all outstanding invitations for a group
/// </summary>
public void ListGroupInvitations(ListGroupInvitationsRequest request, Action<ListGroupInvitationsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ListGroupInvitations", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Lists all members for a group
/// </summary>
public void ListGroupMembers(ListGroupMembersRequest request, Action<ListGroupMembersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ListGroupMembers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Lists all groups and roles for an entity
/// </summary>
public void ListMembership(ListMembershipRequest request, Action<ListMembershipResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ListMembership", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Lists all outstanding invitations and group applications for an entity
/// </summary>
public void ListMembershipOpportunities(ListMembershipOpportunitiesRequest request, Action<ListMembershipOpportunitiesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/ListMembershipOpportunities", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Removes an application to join a group
/// </summary>
public void RemoveGroupApplication(RemoveGroupApplicationRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/RemoveGroupApplication", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Removes an invitation join a group
/// </summary>
public void RemoveGroupInvitation(RemoveGroupInvitationRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/RemoveGroupInvitation", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Removes members from a group.
/// </summary>
public void RemoveMembers(RemoveMembersRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/RemoveMembers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Unblocks a list of entities from joining a group
/// </summary>
public void UnblockEntity(UnblockEntityRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/UnblockEntity", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Updates non-membership data about a group.
/// </summary>
public void UpdateGroup(UpdateGroupRequest request, Action<UpdateGroupResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/UpdateGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Updates metadata about a role.
/// </summary>
public void UpdateRole(UpdateGroupRoleRequest request, Action<UpdateGroupRoleResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Group/UpdateRole", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Malware.MDKServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Malware.MDKAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ScriptAnalyzer : DiagnosticAnalyzer
{
const string DefaultNamespaceName = "IngameScript";
internal static readonly DiagnosticDescriptor NoWhitelistCacheRule
= new DiagnosticDescriptor("MissingWhitelistRule", "Missing Or Corrupted Whitelist Cache", "The whitelist cache could not be loaded. Please run Tools | MDK | Refresh Whitelist Cache to attempt repair.", "Whitelist", DiagnosticSeverity.Error, true);
internal static readonly DiagnosticDescriptor NoOptionsRule
= new DiagnosticDescriptor("MissingOptionsRule", "Missing Or Corrupted Options", "The MDK.options.props could not be loaded.", "Whitelist", DiagnosticSeverity.Error, true);
internal static readonly DiagnosticDescriptor ProhibitedMemberRule
= new DiagnosticDescriptor("ProhibitedMemberRule", "Prohibited Type Or Member", "The type or member '{0}' is prohibited in Space Engineers", "Whitelist", DiagnosticSeverity.Error, true);
internal static readonly DiagnosticDescriptor ProhibitedLanguageElementRule
= new DiagnosticDescriptor("ProhibitedLanguageElement", "Prohibited Language Element", "The language element '{0}' is prohibited in Space Engineers", "Whitelist", DiagnosticSeverity.Error, true);
internal static readonly DiagnosticDescriptor InconsistentNamespaceDeclarationRule
= new DiagnosticDescriptor("InconsistentNamespaceDeclaration", "Inconsistent Namespace Declaration", "All ingame script code should be within the {0} namespace in order to avoid problems.", "Whitelist", DiagnosticSeverity.Warning, true);
Whitelist _whitelist = new Whitelist();
List<Uri> _ignoredFolders = new List<Uri>();
List<Uri> _ignoredFiles = new List<Uri>();
Uri _basePath;
string _namespaceName;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
= ImmutableArray.Create(
ProhibitedMemberRule,
ProhibitedLanguageElementRule,
NoWhitelistCacheRule,
NoOptionsRule,
InconsistentNamespaceDeclarationRule);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(LoadWhitelist);
}
void LoadWhitelist(CompilationStartAnalysisContext context)
{
var mdkOptions = context.Options.AdditionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("mdk.options.props", StringComparison.CurrentCultureIgnoreCase));
if (mdkOptions == null || !LoadOptions(context, mdkOptions))
{
context.RegisterSemanticModelAction(c =>
{
var diagnostic = Diagnostic.Create(NoOptionsRule, c.SemanticModel.SyntaxTree.GetRoot().GetLocation());
c.ReportDiagnostic(diagnostic);
});
_whitelist.IsEnabled = false;
return;
}
var whitelistCache = context.Options.AdditionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("whitelist.cache", StringComparison.CurrentCultureIgnoreCase));
if (whitelistCache != null)
{
var content = whitelistCache.GetText(context.CancellationToken);
_whitelist.IsEnabled = true;
_whitelist.Load(content.Lines.Select(l => l.ToString()).ToArray());
}
else
{
context.RegisterSemanticModelAction(c =>
{
var diagnostic = Diagnostic.Create(NoWhitelistCacheRule, c.SemanticModel.SyntaxTree.GetRoot().GetLocation());
c.ReportDiagnostic(diagnostic);
});
_whitelist.IsEnabled = false;
return;
}
context.RegisterSyntaxNodeAction(Analyze,
SyntaxKind.AliasQualifiedName,
SyntaxKind.QualifiedName,
SyntaxKind.GenericName,
SyntaxKind.IdentifierName,
SyntaxKind.DestructorDeclaration);
context.RegisterSyntaxNodeAction(AnalyzeDeclaration,
SyntaxKind.PropertyDeclaration,
SyntaxKind.VariableDeclaration,
SyntaxKind.Parameter);
context.RegisterSyntaxNodeAction(AnalyzeNamespace,
SyntaxKind.ClassDeclaration);
}
void AnalyzeNamespace(SyntaxNodeAnalysisContext context)
{
if (IsIgnorableNode(context))
return;
var classDeclaration = (ClassDeclarationSyntax)context.Node;
if (classDeclaration.Parent is TypeDeclarationSyntax)
return;
var namespaceDeclaration = classDeclaration.Parent as NamespaceDeclarationSyntax;
var namespaceName = namespaceDeclaration?.Name.ToString();
if (!_namespaceName.Equals(namespaceName, StringComparison.Ordinal))
{
var diagnostic = Diagnostic.Create(InconsistentNamespaceDeclarationRule,
namespaceDeclaration?.Name.GetLocation() ?? classDeclaration.Identifier.GetLocation(), _namespaceName);
context.ReportDiagnostic(diagnostic);
}
}
#pragma warning disable RS1012 // Start action has no registered actions.
bool LoadOptions(CompilationStartAnalysisContext context, AdditionalText mdkOptions)
#pragma warning restore RS1012 // Start action has no registered actions.
{
try
{
var content = mdkOptions.GetText(context.CancellationToken);
var properties = MDKProjectOptions.Parse(content.ToString(), mdkOptions.Path);
var basePath = Path.GetFullPath(Path.GetDirectoryName(mdkOptions.Path) ?? ".").TrimEnd('\\') + "\\..\\";
if (!basePath.EndsWith("\\"))
basePath += "\\";
_basePath = new Uri(basePath);
_namespaceName = properties.Namespace ?? DefaultNamespaceName;
lock (_ignoredFolders)
lock (_ignoredFiles)
{
_ignoredFolders.Clear();
_ignoredFiles.Clear();
foreach (var folder in properties.IgnoredFolders)
{
if (!folder.EndsWith("\\"))
_ignoredFolders.Add(new Uri(_basePath, new Uri(folder + "\\", UriKind.RelativeOrAbsolute)));
else
_ignoredFolders.Add(new Uri(_basePath, new Uri(folder, UriKind.RelativeOrAbsolute)));
}
foreach (var file in properties.IgnoredFiles)
_ignoredFiles.Add(new Uri(_basePath, new Uri(file, UriKind.RelativeOrAbsolute)));
}
return true;
}
catch (Exception)
{
return false;
}
}
void AnalyzeDeclaration(SyntaxNodeAnalysisContext context)
{
var node = context.Node;
if (IsIgnorableNode(context))
return;
if (!_whitelist.IsEnabled)
{
var diagnostic = Diagnostic.Create(NoOptionsRule, context.SemanticModel.SyntaxTree.GetRoot().GetLocation());
context.ReportDiagnostic(diagnostic);
return;
}
IdentifierNameSyntax identifier;
switch (node.Kind())
{
case SyntaxKind.PropertyDeclaration:
identifier = ((PropertyDeclarationSyntax)node).Type as IdentifierNameSyntax;
break;
case SyntaxKind.VariableDeclaration:
identifier = ((VariableDeclarationSyntax)node).Type as IdentifierNameSyntax;
break;
case SyntaxKind.Parameter:
identifier = ((ParameterSyntax)node).Type as IdentifierNameSyntax;
break;
default:
identifier = null;
break;
}
if (identifier == null)
return;
var name = identifier.Identifier.ToString();
if (name == "dynamic")
{
var diagnostic = Diagnostic.Create(ProhibitedLanguageElementRule, identifier.Identifier.GetLocation(), name);
context.ReportDiagnostic(diagnostic);
}
}
void Analyze(SyntaxNodeAnalysisContext context)
{
var node = context.Node;
if (IsIgnorableNode(context))
return;
if (!_whitelist.IsEnabled)
{
var diagnostic = Diagnostic.Create(NoOptionsRule, context.SemanticModel.SyntaxTree.GetRoot().GetLocation());
context.ReportDiagnostic(diagnostic);
return;
}
// Destructors are unpredictable so they cannot be allowed
if (node.Kind() == SyntaxKind.DestructorDeclaration)
{
var kw = ((DestructorDeclarationSyntax)node).Identifier;
var diagnostic = Diagnostic.Create(ProhibitedLanguageElementRule, kw.GetLocation(), kw.ToString());
context.ReportDiagnostic(diagnostic);
return;
}
// We'll check the qualified names on their own.
if (IsQualifiedName(node.Parent))
{
//if (node.Ancestors().Any(IsQualifiedName))
return;
}
var info = context.SemanticModel.GetSymbolInfo(node);
if (info.Symbol == null)
{
return;
}
// If they wrote it, they can have it.
if (info.Symbol.IsInSource())
{
return;
}
if (!_whitelist.IsWhitelisted(info.Symbol))
{
var diagnostic = Diagnostic.Create(ProhibitedMemberRule, node.GetLocation(), info.Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
context.ReportDiagnostic(diagnostic);
}
}
bool IsIgnorableNode(SyntaxNodeAnalysisContext context)
{
if (!_whitelist.IsEnabled || _whitelist.IsEmpty())
return true;
var fileName = Path.GetFileName(context.Node.SyntaxTree.FilePath);
if (string.IsNullOrWhiteSpace(fileName))
return true;
if (fileName.Contains(".NETFramework,Version="))
return true;
if (fileName.EndsWith(".debug", StringComparison.CurrentCultureIgnoreCase))
return true;
if (fileName.IndexOf(".debug.", StringComparison.CurrentCultureIgnoreCase) >= 0)
return true;
if (_basePath == null)
return false;
var uri = new Uri(_basePath, new Uri(context.Node.SyntaxTree.FilePath, UriKind.RelativeOrAbsolute));
lock (_ignoredFiles)
{
foreach (var ignoredUri in _ignoredFiles)
{
if (string.Equals(uri.AbsolutePath, ignoredUri.AbsolutePath, StringComparison.CurrentCultureIgnoreCase))
return true;
}
}
lock (_ignoredFolders)
{
foreach (var ignoredUri in _ignoredFolders)
{
if (uri.AbsolutePath.StartsWith(ignoredUri.AbsolutePath, StringComparison.CurrentCultureIgnoreCase))
return true;
}
}
return false;
}
bool IsQualifiedName(SyntaxNode arg)
{
switch (arg.Kind())
{
case SyntaxKind.QualifiedName:
case SyntaxKind.AliasQualifiedName:
return true;
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Linq;
using System.Net;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Test;
using Xunit;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Azure.Management.ResourceManager.Models;
using System.Collections.Generic;
using FluentAssertions;
using System.Threading;
namespace ResourceGroups.Tests
{
public class LiveTagsTests : TestBase
{
const string DefaultLocation = "South Central US";
public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
{
handler.IsPassThrough = true;
var client = this.GetResourceManagementClientWithHandler(context, handler);
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
[Fact]
public void CreateListAndDeleteSubscriptionTag()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
string tagName = TestUtilities.GenerateName("csmtg");
var client = GetResourceManagementClient(context, handler);
var createResult = client.Tags.CreateOrUpdate(tagName);
Assert.Equal(tagName, createResult.TagName);
var listResult = client.Tags.List();
Assert.True(listResult.Count() > 0);
client.Tags.Delete(tagName);
}
}
[Fact]
public void CreateListAndDeleteSubscriptionTagValue()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
string tagName = TestUtilities.GenerateName("csmtg");
string tagValue = TestUtilities.GenerateName("csmtgv");
var client = GetResourceManagementClient(context, handler);
var createNameResult = client.Tags.CreateOrUpdate(tagName);
var createValueResult = client.Tags.CreateOrUpdateValue(tagName, tagValue);
Assert.Equal(tagName, createNameResult.TagName);
Assert.Equal(tagValue, createValueResult.TagValueProperty);
var listResult = client.Tags.List();
Assert.True(listResult.Count() > 0);
client.Tags.DeleteValue(tagName, tagValue);
client.Tags.Delete(tagName);
}
}
[Fact]
public void CreateTagValueWithoutCreatingTag()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
string tagName = TestUtilities.GenerateName("csmtg");
string tagValue = TestUtilities.GenerateName("csmtgv");
var client = GetResourceManagementClient(context, handler);
Assert.Throws<CloudException>(() => client.Tags.CreateOrUpdateValue(tagName, tagValue));
}
}
/// <summary>
/// Utility method to test Put request for Tags Operation within tracked resources and proxy resources
/// </summary>
private void CreateOrUpdateTagsTest(MockContext context, string resourceScope = "")
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
var tagsResource = new TagsResource(new Tags(
new Dictionary<string, string> {
{ "tagKey1", "tagValue1" },
{ "tagKey2", "tagValue2" }
}
));
var client = GetResourceManagementClient(context, handler);
var subscriptionScope = "/subscriptions/" + client.SubscriptionId;
resourceScope = subscriptionScope + resourceScope;
// test creating tags for resources
var putResponse = client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource);
putResponse.Properties.TagsProperty.Should().HaveCount(tagsResource.Properties.TagsProperty.Count);
this.CompareTagsResource(tagsResource, putResponse).Should().BeTrue();
}
/// <summary>
/// Put request for Tags Operation within tracked resources
/// </summary>
[Fact]
public void CreateTagsWithTrackedResourcesTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for tracked resources
string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM";
this.CreateOrUpdateTagsTest(context:context, resourceScope:resourceScope);
}
}
/// <summary>
/// Put request for Tags Operation within subscription test
/// </summary>
[Fact]
public void CreateTagsWithSubscriptionTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for subscription
this.CreateOrUpdateTagsTest(context: context);
}
}
/// <summary>
/// Utility method to test Patch request for Tags Operation within tracked resources and proxy resources, including Replace|Merge|Delete operations
/// </summary>
private void UpdateTagsTest(MockContext context, string resourceScope = "")
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(context, handler);
var subscriptionScope = "/subscriptions/" + client.SubscriptionId;
resourceScope = subscriptionScope + resourceScope;
// using Tags.CreateOrUpdateAtScope to create two tags initially
var tagsResource = new TagsResource(new Tags(
new Dictionary<string, string> {
{ "tagKey1", "tagValue1" },
{ "tagKey2", "tagValue2" }
}
));
client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource);
Thread.Sleep(3000);
var putTags = new Tags(
new Dictionary<string, string> {
{ "tagKey1", "tagValue3" },
{ "tagKey3", "tagValue3" }
});
{ // test for Merge operation
var tagPatchRequest = new TagsPatchResource("Merge", putTags);
var patchResponse = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest);
var expectedResponse = new TagsResource(new Tags(
new Dictionary<string, string> {
{ "tagKey1", "tagValue3" },
{ "tagKey2", "tagValue2" },
{ "tagKey3", "tagValue3" }
}
));
patchResponse.Properties.TagsProperty.Should().HaveCount(expectedResponse.Properties.TagsProperty.Count);
this.CompareTagsResource(expectedResponse, patchResponse).Should().BeTrue();
}
{ // test for Replace operation
var tagPatchRequest = new TagsPatchResource("Replace", putTags);
var patchResponse = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest);
var expectedResponse = new TagsResource(putTags);
patchResponse.Properties.TagsProperty.Should().HaveCount(expectedResponse.Properties.TagsProperty.Count);
this.CompareTagsResource(expectedResponse, patchResponse).Should().BeTrue();
}
{ // test for Delete operation
var tagPatchRequest = new TagsPatchResource("Delete", putTags);
var patchResponse = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest);
patchResponse.Properties.TagsProperty.Should().BeEmpty();
}
}
/// <summary>
/// Patch request for Tags Operation within tracked resources test, including Replace|Merge|Delete operations
/// </summary>
[Fact]
public void UpdateTagsWithTrackedResourcesTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for tracked resources
string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM";
this.UpdateTagsTest(context:context, resourceScope: resourceScope);
}
}
/// <summary>
/// Patch request for Tags Operation within subscription test, including Replace|Merge|Delete operations
/// </summary>
[Fact]
public void UpdateTagsWithSubscriptionTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for subscription
this.UpdateTagsTest(context: context);
}
}
/// <summary>
/// Utility method to test Get request for Tags Operation within tracked resources and proxy resources
/// </summary>
private void GetTagsTest(MockContext context, string resourceScope = "")
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(context, handler);
var subscriptionScope = "/subscriptions/" + client.SubscriptionId;
resourceScope = subscriptionScope + resourceScope;
// using Tags.CreateOrUpdateAtScope to create two tags initially
var tagsResource = new TagsResource(new Tags(
new Dictionary<string, string> {
{ "tagKey1", "tagValue1" },
{ "tagKey2", "tagValue2" }
}
));
client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource);
Thread.Sleep(3000);
// get request should return created TagsResource
var getResponse = client.Tags.GetAtScope(resourceScope);
getResponse.Properties.TagsProperty.Should().HaveCount(tagsResource.Properties.TagsProperty.Count);
this.CompareTagsResource(tagsResource, getResponse).Should().BeTrue();
}
/// <summary>
/// Get request for Tags Operation within tracked resources test
/// </summary>
[Fact]
public void GetTagsWithTrackedResourcesTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for tracked resources
string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM";
this.GetTagsTest(context: context, resourceScope: resourceScope);
}
}
/// <summary>
/// Get request for Tags Operation within subscription test
/// </summary>
[Fact]
public void GetTagsWithSubscriptionTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for subscription
this.GetTagsTest(context: context);
}
}
/// <summary>
/// Utility method to test Delete request for Tags Operation within tracked resources and proxy resources
/// </summary>
private TagsResource DeleteTagsTest(MockContext context, string resourceScope = "")
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(context, handler);
var subscriptionScope = "/subscriptions/" + client.SubscriptionId;
resourceScope = subscriptionScope + resourceScope;
// using Tags.CreateOrUpdateAtScope to create two tags initially
var tagsResource = new TagsResource(new Tags(
new Dictionary<string, string> {
{ "tagKey1", "tagValue1" },
{ "tagKey2", "tagValue2" }
}
));
client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource);
Thread.Sleep(3000);
// try to delete existing tags
client.Tags.DeleteAtScope(resourceScope);
Thread.Sleep(3000);
// after deletion, Get request should get 0 tags back
return client.Tags.GetAtScope(resourceScope);
}
/// <summary>
/// Get request for Tags Operation within tracked resources test
/// </summary>
[Fact]
public void DeleteTagsWithTrackedResourcesTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for tracked resources
string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM";
this.DeleteTagsTest(context: context, resourceScope: resourceScope).Properties.TagsProperty.Should().BeEmpty();
}
}
/// <summary>
/// Get request for Tags Operation within subscription test
/// </summary>
[Fact]
public void DeleteTagsWithSubscriptionTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
// test tags for subscription
this.DeleteTagsTest(context: context).Properties.TagsProperty.Should().BeEmpty();
}
}
/// <summary>
/// utility method to compare two TagsResource object to see if they are the same
/// </summary>
/// <param name="tag1">first TagsResource object</param>
/// <param name="tag2">second TagsResource object</param>
/// <returns> boolean to show whether two objects are the same</returns>
private bool CompareTagsResource(TagsResource tag1, TagsResource tag2)
{
if ((tag1 == null && tag2 == null) || (tag1.Properties.TagsProperty.Count == 0 && tag2.Properties.TagsProperty.Count == 0))
{
return true;
}
if ((tag1 == null || tag2 == null) || (tag1.Properties.TagsProperty.Count == 0 || tag2.Properties.TagsProperty.Count == 0))
{
return false;
}
foreach (var pair in tag1.Properties.TagsProperty)
{
if (!tag2.Properties.TagsProperty.ContainsKey(pair.Key) || tag2.Properties.TagsProperty[pair.Key] != pair.Value)
{
return false;
}
}
return true;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="OutGridView.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// PowerShell Graphical Out-GridView WPF support
//</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Management.UI.Internal
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
/// <summary>
/// OutGridViewWindow definition for PowerShell command out-gridview.
/// </summary>
internal class OutGridViewWindow
{
#region private Fields
/// <summary>
/// Zoom Increments
/// </summary>
private const double ZOOM_INCREMENT = 0.2;
/// <summary>
/// Max ZoomLevel
/// </summary>
private const double ZOOM_MAX = 3.0;
/// <summary>
/// Min ZoomLevel
/// </summary>
private const double ZOOM_MIN = 0.5;
/// <summary>
/// Window for gridView.
/// </summary>
private Window gridViewWindow;
/// <summary>
/// Local ManagementList.
/// </summary>
private ManagementList managementList;
/// <summary>
/// A collection of PSObjects to be data bound to the local Management List.
/// </summary>
private ObservableCollection<PSObject> listItems;
/// <summary>
/// Event used for the thread gridViewWindows signaling main thread after Windows loaded
/// </summary>
private AutoResetEvent gridViewWindowLoaded;
/// <summary> Is used to store any Management list calls exceptions. </summary>
private Exception exception = null;
/// <summary>
/// Is used to block thread of the pipeline.
/// </summary>
private AutoResetEvent closedEvent;
/// <summary>
/// OK Button's content.
/// </summary>
private static readonly string OKButtonContent = XamlLocalizableResources.OutGridView_Button_OK;
/// <summary>
/// Cancel Button's content.
/// </summary>
private static readonly string CancelButtonContent = XamlLocalizableResources.OutGridView_Button_Cancel;
/// <summary>
/// Used to store selected items in the ok processing
/// </summary>
private List<PSObject> selectedItems;
/// <summary>
/// The GUI thread of Out-GridView
/// </summary>
private Thread guiThread;
/// <summary>
/// private constants for ZoomLevel
/// </summary>
private double zoomLevel = 1.0;
#endregion private Fields
#region internal Constructors
/// <summary>
/// Constructor for OutGridView.
/// </summary>
internal OutGridViewWindow()
{
// Initialize the data source collection.
this.listItems = new ObservableCollection<PSObject>();
}
#endregion internal Constructors
#region private delegates
/// <summary>
/// ThreadDelegate definition.
/// </summary>
/// <param name="arg">Start GridView Window delegate.</param>
private delegate void ThreadDelegate(object arg);
#endregion private delegates
#region Private method that are intended to be called by the Out-GridView cmdlet.
/// <summary>
/// Start a new thread as STA for gridView Window.
/// </summary>
/// <param name="invocation">commands of the PowerShell.</param>
/// <param name="outputModeOptions">selection mode of the list</param>
/// <param name="closedEvent">closedEvent</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")]
private void StartWindow(string invocation, string outputModeOptions, AutoResetEvent closedEvent)
{
this.closedEvent = closedEvent;
this.gridViewWindowLoaded = new AutoResetEvent(false);
ParameterizedThreadStart threadStart = new ParameterizedThreadStart(
new ThreadDelegate(delegate
{
try
{
this.gridViewWindow = new Window();
this.managementList = CreateManagementList(outputModeOptions);
this.gridViewWindow.Loaded += new RoutedEventHandler(this.GridViewWindowLoaded);
this.gridViewWindow.Content = CreateMainGrid(outputModeOptions);
this.gridViewWindow.Title = invocation;
this.gridViewWindow.Closed += new EventHandler(this.GridViewWindowClosed);
RoutedCommand plusSettings = new RoutedCommand();
KeyGestureConverter keyGestureConverter = new KeyGestureConverter();
try
{
plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn1Shortcut));
plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn2Shortcut));
plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn3Shortcut));
plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn4Shortcut));
this.gridViewWindow.CommandBindings.Add(new CommandBinding(plusSettings, ZoomEventHandlerPlus));
}
catch (NotSupportedException)
{
//localized has a problematic string - going to default
plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Add"));
plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Plus"));
this.gridViewWindow.CommandBindings.Add(new CommandBinding(plusSettings, ZoomEventHandlerPlus));
};
RoutedCommand minusSettings = new RoutedCommand();
try
{
minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut1Shortcut));
minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut2Shortcut));
minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut3Shortcut));
minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut4Shortcut));
this.gridViewWindow.CommandBindings.Add(new CommandBinding(minusSettings, ZoomEventHandlerMinus));
}
catch (NotSupportedException)
{
//localized has a problematic string - going to default
minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Subtract"));
minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Minus"));
this.gridViewWindow.CommandBindings.Add(new CommandBinding(minusSettings, ZoomEventHandlerMinus));
}
this.gridViewWindow.ShowDialog();
}
catch (Exception e)
{
// Store the exception in a local variable that will be checked later.
if (e.InnerException != null)
{
this.exception = e.InnerException;
}
else
{
this.exception = e;
}
}
}));
guiThread = new Thread(threadStart);
guiThread.SetApartmentState(ApartmentState.STA);
guiThread.Start();
}
/// <summary>
/// Implements ZoomIn
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ZoomEventHandlerPlus(object sender, ExecutedRoutedEventArgs e)
{
if (this.zoomLevel == 0)
{
this.zoomLevel = 1;
}
if (this.zoomLevel < ZOOM_MAX)
{
this.zoomLevel = this.zoomLevel + ZOOM_INCREMENT;
Grid g = this.gridViewWindow.Content as Grid;
if (g != null)
{
g.LayoutTransform = new ScaleTransform(this.zoomLevel, this.zoomLevel, 0, 0);
}
}
}
/// <summary>
/// Implements ZoomOut
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ZoomEventHandlerMinus(object sender, ExecutedRoutedEventArgs e)
{
if (this.zoomLevel >= ZOOM_MIN)
{
this.zoomLevel = this.zoomLevel - ZOOM_INCREMENT;
Grid g = this.gridViewWindow.Content as Grid;
if (g != null)
{
g.LayoutTransform = new ScaleTransform(this.zoomLevel, this.zoomLevel, 0, 0);
}
}
}
/// <summary>
/// Creates a new ManagementList.
/// </summary>
/// <param name="outputMode">Output mode of the out-gridview</param>
/// <returns>A new ManagementList</returns>
private ManagementList CreateManagementList(string outputMode)
{
ManagementList newList = new ManagementList();
newList.ViewSaverUserActionState = UserActionState.Hidden;
newList.ViewManagerUserActionState = UserActionState.Hidden;
newList.List.VerticalAlignment = VerticalAlignment.Stretch;
newList.List.SetValue(Grid.RowProperty, 0);
newList.List.SelectionMode = (outputMode == "Single") ? SelectionMode.Single : SelectionMode.Extended;
return newList;
}
/// <summary>
/// Creates a new main grid for window.
/// </summary>
/// <param name="outputMode">Output mode of the out-gridview</param>
/// <returns>A new mainGrid</returns>
private Grid CreateMainGrid(string outputMode)
{
Grid mainGrid = new Grid();
mainGrid.RowDefinitions.Add(new RowDefinition());
mainGrid.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
mainGrid.Children.Add(managementList);
if (outputMode == "None")
{
return mainGrid;
}
// OK and Cancel button should only be displayed if OutputMode is not None.
mainGrid.RowDefinitions.Add(new RowDefinition());
mainGrid.RowDefinitions[1].Height = GridLength.Auto;
mainGrid.Children.Add(CreateButtonGrid());
return mainGrid;
}
/// <summary>
/// Creates a OK button.
/// </summary>
/// <returns>A new buttonGrid</returns>
private Grid CreateButtonGrid()
{
Grid buttonGrid = new Grid();
//// This will allow OK and Cancel to have the same width
buttonGrid.SetValue(Grid.IsSharedSizeScopeProperty, true);
buttonGrid.ColumnDefinitions.Add(new ColumnDefinition());
buttonGrid.ColumnDefinitions.Add(new ColumnDefinition());
buttonGrid.ColumnDefinitions[0].Width = GridLength.Auto;
buttonGrid.ColumnDefinitions[0].SharedSizeGroup = "okCancel";
buttonGrid.ColumnDefinitions[1].Width = GridLength.Auto;
buttonGrid.ColumnDefinitions[1].SharedSizeGroup = "okCancel";
buttonGrid.HorizontalAlignment = HorizontalAlignment.Right;
buttonGrid.SetValue(Grid.RowProperty, 1);
//// This will add OK and Cancel button to buttonGrid.
buttonGrid.Children.Add(CreateOKButton());
buttonGrid.Children.Add(CreateCancelButton());
return buttonGrid;
}
/// <summary>
/// Creates a OK button.
/// </summary>
/// <returns>A new OK button</returns>
private Button CreateOKButton()
{
Button ok = new Button();
ok.Content = OKButtonContent;
ok.Margin = new Thickness(5);
ok.Padding = new Thickness(2);
ok.SetValue(Grid.ColumnProperty, 0);
ok.IsDefault = true;
ok.SetValue(AutomationProperties.AutomationIdProperty, "OGVOK");
ok.Click += new RoutedEventHandler(OK_Click);
return ok;
}
/// <summary>
/// Creates a Cancel button.
/// </summary>
/// <returns>A new Cancel button</returns>
private Button CreateCancelButton()
{
Button cancel = new Button();
cancel.Content = CancelButtonContent;
cancel.Margin = new Thickness(5);
cancel.Padding = new Thickness(2);
cancel.SetValue(Grid.ColumnProperty, 1);
cancel.IsCancel = true;
cancel.SetValue(AutomationProperties.AutomationIdProperty, "OGVCancel");
cancel.Click += new RoutedEventHandler(Cancel_Click);
return cancel;
}
/// <summary>
/// Store the selected items for use in EndProcessing
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void OK_Click(object sender, RoutedEventArgs e)
{
if (this.managementList.List.SelectedItems.Count != 0)
{
this.selectedItems = new List<PSObject>();
foreach(PSObject obj in this.managementList.List.SelectedItems)
{
this.selectedItems.Add(obj);
}
}
this.gridViewWindow.Close();
}
/// <summary>
/// Closes the window
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.gridViewWindow.Close();
}
/// <summary>
/// Gets selected items from List.
/// </summary>
/// <returns>Selected items of the list</returns>
private List<PSObject> SelectedItems()
{
return this.selectedItems;
}
/// <summary>
/// Closes the window
/// </summary>
public void CloseWindow()
{
this.gridViewWindow.Dispatcher.Invoke(new ThreadStart(delegate { this.gridViewWindow.Close(); }));
}
/// <summary>
/// Add column definitions to the underlying management list.
/// </summary>
/// <param name="propertyNames">An array of property names to add.</param>
/// <param name="displayNames">An array of display names to add.</param>
/// <param name="types">An array of types to add.</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")]
private void AddColumns(string[] propertyNames, string[] displayNames, Type[] types)
{
// Wait for the gridViewWindow thread to signal that loading of Window is done
if (this.gridViewWindowLoaded != null)
{
this.gridViewWindowLoaded.WaitOne();
this.gridViewWindowLoaded = null;
}
this.managementList.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
// Pick the length of the shortest incoming arrays. Normally all incoming arrays should be of the same length.
int length = propertyNames.Length;
if (length > displayNames.Length)
{
length = displayNames.Length;
}
if (length > types.Length)
{
length = types.Length;
}
try
{
// Clear all columns in case the view is changed.
this.managementList.List.Columns.Clear();
// Clear column filter rules.
this.managementList.AddFilterRulePicker.ColumnFilterRules.Clear();
// Add columns with provided names and Types.
for (int i = 0; i < propertyNames.Length; ++i)
{
DataTemplate dataTemplate;
bool haveTemplate = this.managementList.FilterRulePanel.TryGetContentTemplate(types[i], out dataTemplate);
InnerListColumn column = null;
if(haveTemplate)
{
column = new InnerListColumn(new UIPropertyGroupDescription(propertyNames[i], displayNames[i], types[i]));
}
else
{
column = new InnerListColumn(new UIPropertyGroupDescription(propertyNames[i], displayNames[i], typeof(string)));
}
this.managementList.AddColumn(column);
}
this.managementList.List.SetColumnHeaderActions();
if(this.managementList.List.ItemsSource == null)
{
// Setting ItemsSource implicitly regenerates all columns.
this.managementList.List.ItemsSource = this.listItems;
}
// Set focus on ListView
this.managementList.List.SelectedIndex = 0;
this.managementList.List.Focus();
}
catch (Exception e)
{
// Store the exception in a local variable that will be checked later.
if(e.InnerException != null)
{
this.exception = e.InnerException;
}
else
{
this.exception = e;
}
}
}));
}
/// <summary>
/// Add an item to ObservableCollection.
/// </summary>
/// <param name="value">PSObject of comlet data.</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")]
private void AddItem(PSObject value)
{
if (this.GetWindowClosedStatus())
{
return;
}
this.managementList.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
try
{
this.listItems.Add(value);
}
catch (Exception e)
{
// Store the exception in a local variable that will be checked later.
if(e.InnerException != null)
{
this.exception = e.InnerException;
}
else
{
this.exception = e;
}
}
}));
}
/// <summary>
/// Returns the state of GridView Window.
/// </summary>
/// <returns>The status of GridView Window close or not.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")]
private bool GetWindowClosedStatus()
{
if (this.closedEvent == null)
{
return false;
}
return this.closedEvent.WaitOne(0);
}
/// <summary>
/// Returns any exception that has been thrown by previous method calls.
/// </summary>
/// <returns>The thrown and caught exception. It returns null if no exceptions were thrown by any previous method calls.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")]
private Exception GetLastException()
{
Exception local = this.exception;
if(local != null)
{
// Clear the caught exception.
this.exception = null;
return local;
}
return this.exception;
}
#endregion Private method that are intended to be called by the Out-GridView cmdlet.
#region Private methods
/// <summary>
/// GridView Window is closing callback process.
/// </summary>
/// <param name="sender">The sender object.</param>
/// <param name="e">Event Args.</param>
private void GridViewWindowClosed(object sender, EventArgs e)
{
if (this.closedEvent != null && !this.closedEvent.SafeWaitHandle.IsClosed)
{
try
{
this.closedEvent.Set();
}
catch(ObjectDisposedException)
{
// we tried to avoid this exception with "&& !this.closedEvent.SafeWaitHandle.IsClosed"
// but since this runs in a different thread the if condition could be evaluated and after that
// the handle disposed
}
}
}
/// <summary>
/// Set loaded as true when this method invoked.
/// </summary>
/// <param name="sender">The sender object.</param>
/// <param name="e">RoutedEvent Args.</param>
private void GridViewWindowLoaded(object sender, RoutedEventArgs e)
{
// signal the main thread
this.gridViewWindowLoaded.Set();
// Make gridview window as active window
this.gridViewWindow.Activate();
// Set up AutomationId and Name
AutomationProperties.SetName(this.gridViewWindow, GraphicalHostResources.OutGridViewWindowObjectName);
AutomationProperties.SetAutomationId(this.gridViewWindow, "OutGridViewWindow");
}
#endregion Private methods
}
}
| |
using System;
using System.Text;
/// <summary>
/// GetBytes(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32) [v-jianq]
/// </summary>
public class UTF8EncodingGetBytes1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetBytes(Char[],Int32,Int32,Byte[],Int32) with non-null chars");
try
{
Byte[] bytes;
Char[] chars = new Char[] {
'\u0023',
'\u0025',
'\u03a0',
'\u03a3' };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 1, 2);
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetBytes(Char[],Int32,Int32,Byte[],Int32) with null chars");
try
{
Byte[] bytes;
Char[] chars = new Char[] { };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 0, 0);
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, 0, 0, bytes, 0);
if (bytesEncodedCount != 0)
{
TestLibrary.TestFramework.LogError("002.1", "Method GetBytes Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when chars is a null reference ");
try
{
Byte[] bytes;
Char[] chars = null;
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = 10;
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0);
TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when chars is a null reference ");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentNullException is not thrown when bytes is a null reference ");
try
{
Byte[] bytes;
Char[] chars = new Char[] {
'\u0023',
'\u0025',
'\u03a0',
'\u03a3' };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 1, 2);
bytes = null;
int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0);
TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown when bytes is a null reference ");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown when charIndex is less than zero ");
try
{
Byte[] bytes;
Char[] chars = new Char[] {
'\u0023',
'\u0025',
'\u03a0',
'\u03a3' };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 1, 2);
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, -1, 2, bytes, 0);
TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown when charIndex is less than zero.");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown when charCount is less than zero ");
try
{
Byte[] bytes;
Char[] chars = new Char[] {
'\u0023',
'\u0025',
'\u03a0',
'\u03a3' };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 1, 2);
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, 1, -2, bytes, 0);
TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown when charIndex is less than zero.");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException is not thrown when byteIndex is less than zero. ");
try
{
Byte[] bytes;
Char[] chars = new Char[] {
'\u0023',
'\u0025',
'\u03a0',
'\u03a3' };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 1, 2);
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, -1);
TestLibrary.TestFramework.LogError("105.1", "ArgumentOutOfRangeException is not thrown whenchar byteIndex is less than zero..");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException is not thrown when charIndex and charCount do not denote a valid range in chars. ");
try
{
Byte[] bytes;
Char[] chars = new Char[] {
'\u0023',
'\u0025',
'\u03a0',
'\u03a3' };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 1, 2);
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, 1, chars.Length, bytes, 1);
TestLibrary.TestFramework.LogError("106.1", "ArgumentOutOfRangeException is not thrown when charIndex and charCount do not denote a valid range in chars.");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentException is not thrown when bytes does not have enough capacity from byteIndex to the end of the array to accommodate the resulting bytes.");
try
{
Byte[] bytes;
Char[] chars = new Char[] {
'\u0023',
'\u0025',
'\u03a0',
'\u03a3' };
UTF8Encoding utf8 = new UTF8Encoding();
int byteCount = utf8.GetByteCount(chars, 1, 2);
bytes = new Byte[byteCount];
int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, bytes.Length);
TestLibrary.TestFramework.LogError("107.1", "ArgumentException is not thrown when byteIndex is not a valid index in bytes.");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
UTF8EncodingGetBytes1 test = new UTF8EncodingGetBytes1();
TestLibrary.TestFramework.BeginTestCase("UTF8EncodingGetBytes1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Vfs
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
/// <summary>
/// Base class for VFS file systems.
/// </summary>
/// <typeparam name="TDirEntry">The concrete type representing directory entries</typeparam>
/// <typeparam name="TFile">The concrete type representing files</typeparam>
/// <typeparam name="TDirectory">The concrete type representing directories</typeparam>
/// <typeparam name="TContext">The concrete type holding global state</typeparam>
public abstract class VfsFileSystem<TDirEntry, TFile, TDirectory, TContext> : DiscFileSystem
where TDirEntry : VfsDirEntry
where TFile : IVfsFile
where TDirectory : class, IVfsDirectory<TDirEntry, TFile>, TFile
where TContext : VfsContext
{
private TContext _context;
private TDirectory _rootDir;
private ObjectCache<long, TFile> _fileCache;
/// <summary>
/// Initializes a new instance of the VfsFileSystem class.
/// </summary>
/// <param name="defaultOptions">The default file system options</param>
protected VfsFileSystem(DiscFileSystemOptions defaultOptions)
: base(defaultOptions)
{
_fileCache = new ObjectCache<long, TFile>();
}
/// <summary>
/// Delegate for processing directory entries.
/// </summary>
/// <param name="path">Full path to the directory entry</param>
/// <param name="dirEntry">The directory entry itself</param>
protected delegate void DirEntryHandler(string path, TDirEntry dirEntry);
/// <summary>
/// Gets the volume label.
/// </summary>
public override abstract string VolumeLabel
{
get;
}
/// <summary>
/// Gets or sets the global shared state.
/// </summary>
protected TContext Context
{
get { return _context; }
set { _context = value; }
}
/// <summary>
/// Gets or sets the object representing the root directory.
/// </summary>
protected TDirectory RootDirectory
{
get { return _rootDir; }
set { _rootDir = value; }
}
/// <summary>
/// Copies a file - not supported on read-only file systems.
/// </summary>
/// <param name="sourceFile">The source file</param>
/// <param name="destinationFile">The destination file</param>
/// <param name="overwrite">Whether to permit over-writing of an existing file.</param>
public override void CopyFile(string sourceFile, string destinationFile, bool overwrite)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a directory - not supported on read-only file systems.
/// </summary>
/// <param name="path">The path of the new directory</param>
public override void CreateDirectory(string path)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes a directory - not supported on read-only file systems.
/// </summary>
/// <param name="path">The path of the directory to delete.</param>
public override void DeleteDirectory(string path)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes a file - not supported on read-only file systems.
/// </summary>
/// <param name="path">The path of the file to delete.</param>
public override void DeleteFile(string path)
{
throw new NotImplementedException();
}
/// <summary>
/// Indicates if a directory exists.
/// </summary>
/// <param name="path">The path to test</param>
/// <returns>true if the directory exists</returns>
public override bool DirectoryExists(string path)
{
if (IsRoot(path))
{
return true;
}
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry != null)
{
return dirEntry.IsDirectory;
}
return false;
}
/// <summary>
/// Indicates if a file exists.
/// </summary>
/// <param name="path">The path to test</param>
/// <returns>true if the file exists</returns>
public override bool FileExists(string path)
{
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry != null)
{
return !dirEntry.IsDirectory;
}
return false;
}
/// <summary>
/// Gets the names of subdirectories in a specified directory matching a specified
/// search pattern, using a value to determine whether to search subdirectories.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <param name="searchOption">Indicates whether to search subdirectories.</param>
/// <returns>Array of directories matching the search pattern.</returns>
public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption)
{
Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern);
List<string> dirs = new List<string>();
DoSearch(dirs, path, re, searchOption == SearchOption.AllDirectories, true, false);
return dirs.ToArray();
}
/// <summary>
/// Gets the names of files in a specified directory matching a specified
/// search pattern, using a value to determine whether to search subdirectories.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <param name="searchOption">Indicates whether to search subdirectories.</param>
/// <returns>Array of files matching the search pattern.</returns>
public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern);
List<string> results = new List<string>();
DoSearch(results, path, re, searchOption == SearchOption.AllDirectories, false, true);
return results.ToArray();
}
/// <summary>
/// Gets the names of all files and subdirectories in a specified directory.
/// </summary>
/// <param name="path">The path to search.</param>
/// <returns>Array of files and subdirectories matching the search pattern.</returns>
public override string[] GetFileSystemEntries(string path)
{
string fullPath = path;
if (!fullPath.StartsWith(@"\", StringComparison.OrdinalIgnoreCase))
{
fullPath = @"\" + fullPath;
}
TDirectory parentDir = GetDirectory(fullPath);
return Utilities.Map<TDirEntry, string>(parentDir.AllEntries, (m) => Utilities.CombinePaths(fullPath, FormatFileName(m.FileName)));
}
/// <summary>
/// Gets the names of files and subdirectories in a specified directory matching a specified
/// search pattern.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <returns>Array of files and subdirectories matching the search pattern.</returns>
public override string[] GetFileSystemEntries(string path, string searchPattern)
{
Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern);
TDirectory parentDir = GetDirectory(path);
List<string> result = new List<string>();
foreach (TDirEntry dirEntry in parentDir.AllEntries)
{
if (re.IsMatch(dirEntry.SearchName))
{
result.Add(Utilities.CombinePaths(path, dirEntry.FileName));
}
}
return result.ToArray();
}
/// <summary>
/// Moves a directory.
/// </summary>
/// <param name="sourceDirectoryName">The directory to move.</param>
/// <param name="destinationDirectoryName">The target directory name.</param>
public override void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName)
{
throw new NotImplementedException();
}
/// <summary>
/// Moves a file.
/// </summary>
/// <param name="sourceName">The file to move.</param>
/// <param name="destinationName">The target file name.</param>
/// <param name="overwrite">Overwrite any existing file.</param>
public override void MoveFile(string sourceName, string destinationName, bool overwrite)
{
throw new NotImplementedException();
}
/// <summary>
/// Opens the specified file.
/// </summary>
/// <param name="path">The full path of the file to open.</param>
/// <param name="mode">The file mode for the created stream.</param>
/// <param name="access">The access permissions for the created stream.</param>
/// <returns>The new stream.</returns>
public override SparseStream OpenFile(string path, FileMode mode, FileAccess access)
{
if (!CanWrite)
{
if (mode != FileMode.Open)
{
throw new NotSupportedException("Only existing files can be opened");
}
if (access != FileAccess.Read)
{
throw new NotSupportedException("Files cannot be opened for write");
}
}
string fileName = Utilities.GetFileFromPath(path);
string attributeName = null;
int streamSepPos = fileName.IndexOf(':');
if (streamSepPos >= 0)
{
attributeName = fileName.Substring(streamSepPos + 1);
}
string dirName;
try
{
dirName = Utilities.GetDirectoryFromPath(path);
}
catch (ArgumentException)
{
throw new IOException("Invalid path: " + path);
}
string entryPath = Utilities.CombinePaths(dirName, fileName);
TDirEntry entry = GetDirectoryEntry(entryPath);
if (entry == null)
{
if (mode == FileMode.Open)
{
throw new FileNotFoundException("No such file", path);
}
else
{
TDirectory parentDir = GetDirectory(Utilities.GetDirectoryFromPath(path));
entry = parentDir.CreateNewFile(Utilities.GetFileFromPath(path));
}
}
else if (mode == FileMode.CreateNew)
{
throw new IOException("File already exists");
}
if (entry.IsSymlink)
{
entry = ResolveSymlink(entry, entryPath);
}
if (entry.IsDirectory)
{
throw new IOException("Attempt to open directory as a file");
}
else
{
TFile file = GetFile(entry);
SparseStream stream = null;
if (string.IsNullOrEmpty(attributeName))
{
stream = new BufferStream(file.FileContent, access);
}
else
{
IVfsFileWithStreams fileStreams = file as IVfsFileWithStreams;
if (fileStreams != null)
{
stream = fileStreams.OpenExistingStream(attributeName);
if (stream == null)
{
if (mode == FileMode.Create || mode == FileMode.OpenOrCreate)
{
stream = fileStreams.CreateStream(attributeName);
}
else
{
throw new FileNotFoundException("No such attribute on file", path);
}
}
}
else
{
throw new NotSupportedException("Attempt to open a file stream on a file system that doesn't support them");
}
}
if (mode == FileMode.Create || mode == FileMode.Truncate)
{
stream.SetLength(0);
}
return stream;
}
}
/// <summary>
/// Gets the attributes of a file or directory.
/// </summary>
/// <param name="path">The file or directory to inspect</param>
/// <returns>The attributes of the file or directory</returns>
public override FileAttributes GetAttributes(string path)
{
if (IsRoot(path))
{
return _rootDir.FileAttributes;
}
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry == null)
{
throw new FileNotFoundException("File not found", path);
}
if (dirEntry.HasVfsFileAttributes)
{
return dirEntry.FileAttributes;
}
else
{
return GetFile(dirEntry).FileAttributes;
}
}
/// <summary>
/// Sets the attributes of a file or directory.
/// </summary>
/// <param name="path">The file or directory to change</param>
/// <param name="newValue">The new attributes of the file or directory</param>
public override void SetAttributes(string path, FileAttributes newValue)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the creation time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <returns>The creation time.</returns>
public override DateTime GetCreationTimeUtc(string path)
{
if (IsRoot(path))
{
return _rootDir.CreationTimeUtc;
}
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry == null)
{
throw new FileNotFoundException("No such file or directory", path);
}
if (dirEntry.HasVfsTimeInfo)
{
return dirEntry.CreationTimeUtc;
}
else
{
return GetFile(dirEntry).CreationTimeUtc;
}
}
/// <summary>
/// Sets the creation time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetCreationTimeUtc(string path, DateTime newTime)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the last access time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory</param>
/// <returns>The last access time</returns>
public override DateTime GetLastAccessTimeUtc(string path)
{
if (IsRoot(path))
{
return _rootDir.LastAccessTimeUtc;
}
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry == null)
{
throw new FileNotFoundException("No such file or directory", path);
}
if (dirEntry.HasVfsTimeInfo)
{
return dirEntry.LastAccessTimeUtc;
}
else
{
return GetFile(dirEntry).LastAccessTimeUtc;
}
}
/// <summary>
/// Sets the last access time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetLastAccessTimeUtc(string path, DateTime newTime)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the last modification time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory</param>
/// <returns>The last write time</returns>
public override DateTime GetLastWriteTimeUtc(string path)
{
if (IsRoot(path))
{
return _rootDir.LastWriteTimeUtc;
}
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry == null)
{
throw new FileNotFoundException("No such file or directory", path);
}
if (dirEntry.HasVfsTimeInfo)
{
return dirEntry.LastWriteTimeUtc;
}
else
{
return GetFile(dirEntry).LastWriteTimeUtc;
}
}
/// <summary>
/// Sets the last modification time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetLastWriteTimeUtc(string path, DateTime newTime)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the length of a file.
/// </summary>
/// <param name="path">The path to the file</param>
/// <returns>The length in bytes</returns>
public override long GetFileLength(string path)
{
TFile file = GetFile(path);
if (file == null || (file.FileAttributes & FileAttributes.Directory) != 0)
{
throw new FileNotFoundException("No such file", path);
}
return file.FileLength;
}
internal TFile GetFile(TDirEntry dirEntry)
{
long cacheKey = dirEntry.UniqueCacheId;
TFile file = _fileCache[cacheKey];
if (file == null)
{
file = ConvertDirEntryToFile(dirEntry);
_fileCache[cacheKey] = file;
}
return file;
}
internal TDirectory GetDirectory(string path)
{
if (IsRoot(path))
{
return _rootDir;
}
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry.IsSymlink)
{
dirEntry = ResolveSymlink(dirEntry, path);
}
if (dirEntry == null || !dirEntry.IsDirectory)
{
throw new DirectoryNotFoundException("No such directory: " + path);
}
return (TDirectory)GetFile(dirEntry);
}
internal TDirEntry GetDirectoryEntry(string path)
{
return GetDirectoryEntry(_rootDir, path);
}
/// <summary>
/// Gets all directory entries in the specified directory and sub-directories.
/// </summary>
/// <param name="path">The path to inspect</param>
/// <param name="handler">Delegate invoked for each directory entry</param>
protected void ForAllDirEntries(string path, DirEntryHandler handler)
{
TDirectory dir = null;
TDirEntry self = GetDirectoryEntry(path);
if (self != null)
{
handler(path, self);
if (self.IsDirectory)
{
dir = GetFile(self) as TDirectory;
}
}
else
{
dir = GetFile(path) as TDirectory;
}
if (dir != null)
{
foreach (var subentry in dir.AllEntries)
{
ForAllDirEntries(Utilities.CombinePaths(path, subentry.FileName), handler);
}
}
}
/// <summary>
/// Gets the file object for a given path.
/// </summary>
/// <param name="path">The path to query.</param>
/// <returns>The file object corresponding to the path</returns>
protected TFile GetFile(string path)
{
if (IsRoot(path))
{
return _rootDir;
}
else if (path == null)
{
return default(TFile);
}
TDirEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry == null)
{
throw new FileNotFoundException("No such file or directory", path);
}
return GetFile(dirEntry);
}
/// <summary>
/// Converts a directory entry to an object representing a file.
/// </summary>
/// <param name="dirEntry">The directory entry to convert</param>
/// <returns>The corresponding file object</returns>
protected abstract TFile ConvertDirEntryToFile(TDirEntry dirEntry);
/// <summary>
/// Converts an internal directory entry name into an external one.
/// </summary>
/// <param name="name">The name to convert</param>
/// <returns>The external name</returns>
/// <remarks>
/// This method is called on a single path element (i.e. name contains no path
/// separators).
/// </remarks>
protected virtual string FormatFileName(string name)
{
return name;
}
private static bool IsRoot(string path)
{
return string.IsNullOrEmpty(path) || path == @"\";
}
private TDirEntry GetDirectoryEntry(TDirectory dir, string path)
{
string[] pathElements = path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
return GetDirectoryEntry(dir, pathElements, 0);
}
private TDirEntry GetDirectoryEntry(TDirectory dir, string[] pathEntries, int pathOffset)
{
TDirEntry entry;
if (pathEntries.Length == 0)
{
return dir.Self;
}
else
{
entry = dir.GetEntryByName(pathEntries[pathOffset]);
if (entry != null)
{
if (pathOffset == pathEntries.Length - 1)
{
return entry;
}
else if (entry.IsDirectory)
{
return GetDirectoryEntry((TDirectory)ConvertDirEntryToFile(entry), pathEntries, pathOffset + 1);
}
else
{
throw new IOException(string.Format(CultureInfo.InvariantCulture, "{0} is a file, not a directory", pathEntries[pathOffset]));
}
}
else
{
return null;
}
}
}
private void DoSearch(List<string> results, string path, Regex regex, bool subFolders, bool dirs, bool files)
{
TDirectory parentDir = GetDirectory(path);
if (parentDir == null)
{
throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "The directory '{0}' was not found", path));
}
string resultPrefixPath = path;
if (IsRoot(path))
{
resultPrefixPath = @"\";
}
foreach (TDirEntry de in parentDir.AllEntries)
{
bool isDir = de.IsDirectory;
if ((isDir && dirs) || (!isDir && files))
{
if (regex.IsMatch(de.SearchName))
{
results.Add(Utilities.CombinePaths(resultPrefixPath, FormatFileName(de.FileName)));
}
}
if (subFolders && isDir)
{
DoSearch(results, Utilities.CombinePaths(resultPrefixPath, FormatFileName(de.FileName)), regex, subFolders, dirs, files);
}
}
}
private TDirEntry ResolveSymlink(TDirEntry entry, string path)
{
TDirEntry currentEntry = entry;
string currentPath = path;
int resolvesLeft = 20;
while (currentEntry.IsSymlink && resolvesLeft > 0)
{
IVfsSymlink<TDirEntry, TFile> symlink = GetFile(currentEntry) as IVfsSymlink<TDirEntry, TFile>;
if (symlink == null)
{
throw new FileNotFoundException("Unable to resolve symlink", path);
}
currentPath = Utilities.ResolvePath(currentPath.TrimEnd('\\'), symlink.TargetPath);
currentEntry = GetDirectoryEntry(currentPath);
if (currentEntry == null)
{
throw new FileNotFoundException("Unable to resolve symlink", path);
}
--resolvesLeft;
}
if (currentEntry.IsSymlink)
{
throw new FileNotFoundException("Unable to resolve symlink - too many links", path);
}
return currentEntry;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Reflection.PortableExecutable;
using System.Reflection.Metadata;
namespace Microsoft.DotNet.Build.Tasks
{
/// <summary>
/// Resolves the assets out of packages in the project.lock.json
/// </summary>
public sealed class PrereleaseResolveNuGetPackageAssets : Task
{
internal const string NuGetPackageIdMetadata = "NuGetPackageId";
internal const string NuGetPackageVersionMetadata = "NuGetPackageVersion";
internal const string NuGetIsFrameworkReference = "NuGetIsFrameworkReference";
internal const string NuGetSourceType = "NuGetSourceType";
internal const string NuGetSourceType_Project = "Project";
internal const string NuGetSourceType_Package = "Package";
internal const string ReferenceImplementationMetadata = "Implementation";
internal const string ReferenceImageRuntimeMetadata = "ImageRuntime";
internal const string ReferenceWinMDFileMetadata = "WinMDFile";
internal const string ReferenceWinMDFileTypeMetadata = "WinMDFileType";
internal const string WinMDFileTypeManaged = "Managed";
internal const string WinMDFileTypeNative = "Native";
internal const string NuGetAssetTypeCompile = "compile";
internal const string NuGetAssetTypeNative = "native";
internal const string NuGetAssetTypeRuntime = "runtime";
internal const string NuGetAssetTypeResource = "resource";
private readonly List<ITaskItem> _analyzers = new List<ITaskItem>();
private readonly List<ITaskItem> _copyLocalItems = new List<ITaskItem>();
private readonly List<ITaskItem> _references = new List<ITaskItem>();
private readonly List<ITaskItem> _referencedPackages = new List<ITaskItem>();
private readonly List<ITaskItem> _contentItems = new List<ITaskItem>();
private readonly List<ITaskItem> _fileWrites = new List<ITaskItem>();
private readonly List<string> _packageFolders = new List<string>();
private readonly Dictionary<string, string> _projectReferencesToOutputBasePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
#region UnitTestSupport
private readonly DirectoryExists _directoryExists = new DirectoryExists(Directory.Exists);
private readonly FileExists _fileExists = new FileExists(File.Exists);
private readonly TryGetRuntimeVersion _tryGetRuntimeVersion = new TryGetRuntimeVersion(TryGetRuntimeVersion);
private readonly bool _reportExceptionsToMSBuildLogger = true;
internal PrereleaseResolveNuGetPackageAssets(DirectoryExists directoryExists, FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
: this()
{
if (directoryExists != null)
{
_directoryExists = directoryExists;
}
if (fileExists != null)
{
_fileExists = fileExists;
}
if (tryGetRuntimeVersion != null)
{
_tryGetRuntimeVersion = tryGetRuntimeVersion;
}
_reportExceptionsToMSBuildLogger = false;
}
// For unit testing.
internal IEnumerable<string> GetPackageFolders()
{
return _packageFolders;
}
#endregion
/// <summary>
/// Creates a new <see cref="PrereleaseResolveNuGetPackageAssets"/>.
/// </summary>
public PrereleaseResolveNuGetPackageAssets()
{
Log.TaskResources = Strings.ResourceManager;
}
/// <summary>
/// The full paths to resolved analyzers.
/// </summary>
[Output]
public ITaskItem[] ResolvedAnalyzers
{
get { return _analyzers.ToArray(); }
}
/// <summary>
/// The full paths to resolved run-time resources.
/// </summary>
[Output]
public ITaskItem[] ResolvedCopyLocalItems
{
get { return _copyLocalItems.ToArray(); }
}
/// <summary>
/// The full paths to resolved build-time dependencies. Contains standard metadata for Reference items.
/// </summary>
[Output]
public ITaskItem[] ResolvedReferences
{
get { return _references.ToArray(); }
}
/// <summary>
/// The names of NuGet packages directly referenced by this project.
/// </summary>
[Output]
public ITaskItem[] ReferencedPackages
{
get { return _referencedPackages.ToArray(); }
}
/// <summary>
/// Additional content items provided from NuGet packages.
/// </summary>
[Output]
public ITaskItem[] ContentItems => _contentItems.ToArray();
/// <summary>
/// Files written to during the generation process.
/// </summary>
[Output]
public ITaskItem[] FileWrites => _fileWrites.ToArray();
/// <summary>
/// Items specifying the tokens that can be substituted into preprocessed content files. The ItemSpec of each item is
/// the name of the token, without the surrounding $$, and the Value metadata should specify the replacement value.
/// </summary>
public ITaskItem[] ContentPreprocessorValues
{
get; set;
}
/// <summary>
/// A list of project references that are creating packages as listed in the lock file. The OutputPath metadata should
/// set on each of these items, which is used by the task to construct full output paths to assets.
/// </summary>
public ITaskItem[] ProjectReferencesCreatingPackages
{
get; set;
}
/// <summary>
/// The base output directory where the temporary, preprocessed files should be written to.
/// </summary>
public string ContentPreprocessorOutputDirectory
{
get; set;
}
/// <summary>
/// The target monikers to use when selecting assets from packages. The first one found in the lock file is used.
/// </summary>
[Required]
public ITaskItem[] TargetMonikers
{
get; set;
}
[Required]
public string ProjectLockFile
{
get; set;
}
public string NuGetPackagesDirectory
{
get; set;
}
public string RuntimeIdentifier
{
get; set;
}
public bool AllowFallbackOnTargetSelection
{
get; set;
}
public string ProjectLanguage
{
get; set;
}
public bool IncludeFrameworkReferences
{
get; set;
}
/// <summary>
/// Performs the NuGet package resolution.
/// </summary>
public override bool Execute()
{
try
{
ExecuteCore();
return true;
}
catch (ExceptionFromResource e) when (_reportExceptionsToMSBuildLogger)
{
Log.LogErrorFromResources(e.ResourceName, e.MessageArgs);
return false;
}
catch (Exception e) when (_reportExceptionsToMSBuildLogger)
{
// Any user-visible exceptions we throw should be ExceptionFromResource, so here we should dump stacks because
// something went very wrong.
Log.LogErrorFromException(e, showStackTrace: true);
return false;
}
}
private void ExecuteCore()
{
if (!_fileExists(ProjectLockFile))
{
throw new ExceptionFromResource(nameof(Strings.LockFileNotFound), ProjectLockFile);
}
JObject lockFile;
using (var streamReader = new StreamReader(new FileStream(ProjectLockFile, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
lockFile = JObject.Load(new JsonTextReader(streamReader));
}
PopulatePackageFolders(lockFile);
PopulateProjectReferenceMaps();
GetReferences(lockFile);
GetCopyLocalItems(lockFile);
GetAnalyzers(lockFile);
GetReferencedPackages(lockFile);
ProduceContentAssets(lockFile);
}
private void PopulatePackageFolders(JObject lockFile)
{
// If we explicitly were given a path, let's use that
if (!string.IsNullOrEmpty(NuGetPackagesDirectory))
{
_packageFolders.Add(NuGetPackagesDirectory);
}
// Newer versions of NuGet can now specify the final list of locations in the lock file
var packageFolders = lockFile["packageFolders"] as JObject;
if (packageFolders != null)
{
foreach (var packageFolder in packageFolders.Properties())
{
_packageFolders.Add(packageFolder.Name);
}
}
}
private void PopulateProjectReferenceMaps()
{
foreach (var projectReference in ProjectReferencesCreatingPackages ?? new ITaskItem[] { })
{
var fullPath = GetAbsolutePathFromProjectRelativePath(projectReference.ItemSpec);
if (_projectReferencesToOutputBasePaths.ContainsKey(fullPath))
{
Log.LogWarningFromResources(nameof(Strings.DuplicateProjectReference), fullPath, nameof(ProjectReferencesCreatingPackages));
}
else
{
var outputPath = projectReference.GetMetadata("OutputBasePath");
_projectReferencesToOutputBasePaths.Add(fullPath, outputPath);
}
}
}
private void GetReferences(JObject lockFile)
{
var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false);
var frameworkReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var fileNamesOfRegularReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var package in GetPackagesFromTarget(lockFile, target))
{
foreach (var referenceItem in CreateItems(package, NuGetAssetTypeCompile, includePdbs: false))
{
_references.Add(referenceItem);
fileNamesOfRegularReferences.Add(Path.GetFileNameWithoutExtension(referenceItem.ItemSpec));
}
if (IncludeFrameworkReferences)
{
var frameworkAssembliesArray = package.TargetObject["frameworkAssemblies"] as JArray;
if (frameworkAssembliesArray != null)
{
foreach (var frameworkAssembly in frameworkAssembliesArray.OfType<JToken>())
{
frameworkReferences.Add((string)frameworkAssembly);
}
}
}
}
foreach (var frameworkReference in frameworkReferences.Except(fileNamesOfRegularReferences, StringComparer.OrdinalIgnoreCase))
{
var item = new TaskItem(frameworkReference);
item.SetMetadata(NuGetIsFrameworkReference, "true");
item.SetMetadata(NuGetSourceType, NuGetSourceType_Package);
_references.Add(item);
}
}
private void GetCopyLocalItems(JObject lockFile)
{
// If we have no runtime identifier, we're not copying implementations
if (string.IsNullOrEmpty(RuntimeIdentifier))
{
return;
}
// We'll use as a fallback just the target moniker if the user didn't have the right runtime identifier in their lock file.
var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: true);
HashSet<string> candidateNativeImplementations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
List<ITaskItem> runtimeWinMDItems = new List<ITaskItem>();
foreach (var package in GetPackagesFromTarget(lockFile, target))
{
foreach (var nativeItem in CreateItems(package, NuGetAssetTypeNative))
{
if (Path.GetExtension(nativeItem.ItemSpec).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
candidateNativeImplementations.Add(Path.GetFileNameWithoutExtension(nativeItem.ItemSpec));
}
_copyLocalItems.Add(nativeItem);
}
foreach (var runtimeItem in CreateItems(package, NuGetAssetTypeRuntime))
{
if (Path.GetExtension(runtimeItem.ItemSpec).Equals(".winmd", StringComparison.OrdinalIgnoreCase))
{
runtimeWinMDItems.Add(runtimeItem);
}
_copyLocalItems.Add(runtimeItem);
}
foreach (var resourceItem in CreateItems(package, NuGetAssetTypeResource))
{
_copyLocalItems.Add(resourceItem);
}
}
SetWinMDMetadata(runtimeWinMDItems, candidateNativeImplementations);
}
private void GetAnalyzers(JObject lockFile)
{
// For analyzers, analyzers could be provided in runtime implementation packages. This might be reasonable -- imagine a gatekeeper
// scenario where somebody has a library but on .NET Native might have some specific restrictions that need to be enforced.
var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: !string.IsNullOrEmpty(RuntimeIdentifier));
foreach (var package in GetPackagesFromTarget(lockFile, target))
{
var files = package.LibraryObject["files"];
if (files != null)
{
foreach (var file in files.Children()
.Select(x => x.ToString())
.Where(x => x.StartsWith("analyzers")))
{
if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
string path;
if (TryGetFile(package.Id, package.Version, file, out path))
{
var analyzer = new TaskItem(path);
analyzer.SetMetadata(NuGetPackageIdMetadata, package.Id);
analyzer.SetMetadata(NuGetPackageVersionMetadata, package.Version);
_analyzers.Add(analyzer);
}
}
}
}
}
}
private void SetWinMDMetadata(IEnumerable<ITaskItem> runtimeWinMDs, ICollection<string> candidateImplementations)
{
foreach (var winMD in runtimeWinMDs.Where(w => _fileExists(w.ItemSpec)))
{
string imageRuntimeVersion = _tryGetRuntimeVersion(winMD.ItemSpec);
if (String.IsNullOrEmpty(imageRuntimeVersion))
continue;
// RAR sets ImageRuntime for everything but the only dependencies we're aware of are
// for WinMDs
winMD.SetMetadata(ReferenceImageRuntimeMetadata, imageRuntimeVersion);
bool isWinMD, isManaged;
TryParseRuntimeVersion(imageRuntimeVersion, out isWinMD, out isManaged);
if (isWinMD)
{
winMD.SetMetadata(ReferenceWinMDFileMetadata, "true");
if (isManaged)
{
winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeManaged);
}
else
{
winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeNative);
// Normally RAR will expect the native DLL to be next to the WinMD, but that doesn't
// work well for nuget packages since compile time assets cannot be architecture specific.
// We also explicitly set all compile time assets to not copy local so we need to
// make sure that this metadata is set on the runtime asset.
// Examine all runtime assets that are native winmds and add Implementation metadata
// We intentionally permit this to cross package boundaries to support cases where
// folks want to split their architecture specific implementations into runtime
// specific packages.
// Sample layout
// lib\netcore50\Contoso.Controls.winmd
// lib\netcore50\Contoso.Controls.xml
// runtimes\win10-arm\native\Contoso.Controls.dll
// runtimes\win10-x64\native\Contoso.Controls.dll
// runtimes\win10-x86\native\Contoso.Controls.dll
string fileName = Path.GetFileNameWithoutExtension(winMD.ItemSpec);
// determine if we have a Native WinMD that could be satisfied by this native dll.
if (candidateImplementations.Contains(fileName))
{
winMD.SetMetadata(ReferenceImplementationMetadata, fileName + ".dll");
}
}
}
}
}
private bool TryGetFile(string packageName, string packageVersion, string file, out string path)
{
if (IsFileValid(file, "C#", "VB"))
{
path = GetPath(packageName, packageVersion, file);
return true;
}
else if (IsFileValid(file, "VB", "C#"))
{
path = GetPath(packageName, packageVersion, file);
return true;
}
path = null;
return false;
}
private bool IsFileValid(string file, string expectedLanguage, string unExpectedLanguage)
{
var expectedProjectLanguage = expectedLanguage;
expectedLanguage = expectedLanguage == "C#" ? "cs" : expectedLanguage;
unExpectedLanguage = unExpectedLanguage == "C#" ? "cs" : unExpectedLanguage;
return (ProjectLanguage.Equals(expectedProjectLanguage, StringComparison.OrdinalIgnoreCase)) &&
(file.Split('/').Any(x => x.Equals(ProjectLanguage, StringComparison.OrdinalIgnoreCase)) ||
!file.Split('/').Any(x => x.Equals(unExpectedLanguage, StringComparison.OrdinalIgnoreCase)));
}
private string GetPath(string packageName, string packageVersion, string file)
{
return Path.Combine(GetNuGetPackagePath(packageName, packageVersion), file.Replace('/', '\\'));
}
/// <summary>
/// Produces a string hash of the key/values in the dictionary. This hash is used to put all the
/// preprocessed files into a folder with the name so we know to regenerate when any of the
/// inputs change.
/// </summary>
private string BuildPreprocessedContentHash(IReadOnlyDictionary<string, string> values)
{
using (var stream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096, leaveOpen: true))
{
foreach (var pair in values.OrderBy(v => v.Key))
{
streamWriter.Write(pair.Key);
streamWriter.Write('\0');
streamWriter.Write(pair.Value);
streamWriter.Write('\0');
}
}
stream.Position = 0;
return SHA1.Create().ComputeHash(stream).Aggregate("", (s, b) => s + b.ToString("x2"));
}
}
private void ProduceContentAssets(JObject lockFile)
{
string valueSpecificPreprocessedOutputDirectory = null;
var preprocessorValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// If a preprocessor directory isn't set, then we won't have a place to generate.
if (!string.IsNullOrEmpty(ContentPreprocessorOutputDirectory))
{
// Assemble the preprocessor values up-front
var duplicatedPreprocessorKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var preprocessorValueItem in ContentPreprocessorValues ?? Enumerable.Empty<ITaskItem>())
{
if (preprocessorValues.ContainsKey(preprocessorValueItem.ItemSpec))
{
duplicatedPreprocessorKeys.Add(preprocessorValueItem.ItemSpec);
}
preprocessorValues[preprocessorValueItem.ItemSpec] = preprocessorValueItem.GetMetadata("Value");
}
foreach (var duplicatedPreprocessorKey in duplicatedPreprocessorKeys)
{
Log.LogWarningFromResources(nameof(Strings.DuplicatePreprocessorToken), duplicatedPreprocessorKey, preprocessorValues[duplicatedPreprocessorKey]);
}
valueSpecificPreprocessedOutputDirectory = Path.Combine(ContentPreprocessorOutputDirectory, BuildPreprocessedContentHash(preprocessorValues));
}
// For shared content, it does not depend upon the RID so we should ignore it
var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false);
foreach (var package in GetPackagesFromTarget(lockFile, target))
{
var contentFiles = package.TargetObject["contentFiles"] as JObject;
if (contentFiles != null)
{
// Is there an asset with our exact language? If so, we use that. Otherwise we'll simply collect "any" assets.
string codeLanguageToSelect;
if (string.IsNullOrEmpty(ProjectLanguage))
{
codeLanguageToSelect = "any";
}
else
{
string nuGetLanguageName = GetNuGetLanguageName(ProjectLanguage);
if (contentFiles.Properties().Any(a => (string)a.Value["codeLanguage"] == nuGetLanguageName))
{
codeLanguageToSelect = nuGetLanguageName;
}
else
{
codeLanguageToSelect = "any";
}
}
foreach (var contentFile in contentFiles.Properties())
{
// Ignore magic _._ placeholder files. We couldn't ignore them during the project language
// selection, since you could imagine somebody might have a package that puts assets under
// "any" but then uses _._ to opt some languages out of it
if (Path.GetFileName(contentFile.Name) != "_._")
{
if ((string)contentFile.Value["codeLanguage"] == codeLanguageToSelect)
{
ProduceContentAsset(package, contentFile, preprocessorValues, valueSpecificPreprocessedOutputDirectory);
}
}
}
}
}
}
private static string GetNuGetLanguageName(string projectLanguage)
{
switch (projectLanguage)
{
case "C#": return "cs";
case "F#": return "fs";
default: return projectLanguage.ToLowerInvariant();
}
}
/// <summary>
/// Produces the asset for a single shared asset. All applicablility checks have already been completed.
/// </summary>
private void ProduceContentAsset(NuGetPackageObject package, JProperty sharedAsset, IReadOnlyDictionary<string, string> preprocessorValues, string preprocessedOutputDirectory)
{
string pathToFinalAsset = package.GetFullPathToFile(sharedAsset.Name);
if (sharedAsset.Value["ppOutputPath"] != null)
{
if (preprocessedOutputDirectory == null)
{
throw new ExceptionFromResource(nameof(Strings.PreprocessedDirectoryNotSet), nameof(ContentPreprocessorOutputDirectory));
}
// We need the preprocessed output, so let's run the preprocessor here
pathToFinalAsset = Path.Combine(preprocessedOutputDirectory, package.Id, package.Version, (string)sharedAsset.Value["ppOutputPath"]);
if (!File.Exists(pathToFinalAsset))
{
Directory.CreateDirectory(Path.GetDirectoryName(pathToFinalAsset));
using (var input = new StreamReader(new FileStream(package.GetFullPathToFile(sharedAsset.Name), FileMode.Open, FileAccess.Read, FileShare.Read), detectEncodingFromByteOrderMarks: true))
using (var output = new StreamWriter(new FileStream(pathToFinalAsset, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write), encoding: input.CurrentEncoding))
{
Preprocessor.Preprocess(input, output, preprocessorValues);
}
_fileWrites.Add(new TaskItem(pathToFinalAsset));
}
}
if ((bool)sharedAsset.Value["copyToOutput"])
{
string outputPath = (string)sharedAsset.Value["outputPath"] ?? (string)sharedAsset.Value["ppOutputPath"];
if (outputPath != null)
{
var item = CreateItem(package, pathToFinalAsset, targetPath: outputPath);
_copyLocalItems.Add(item);
}
}
string buildAction = (string)sharedAsset.Value["buildAction"];
if (!string.Equals(buildAction, "none", StringComparison.OrdinalIgnoreCase))
{
var item = CreateItem(package, pathToFinalAsset);
// We'll put additional metadata on the item so we can convert it back to the real item group in our targets
item.SetMetadata("NuGetItemType", buildAction);
// If this is XAML, the build targets expect Link metadata to construct the relative path
if (string.Equals(buildAction, "Page", StringComparison.OrdinalIgnoreCase))
{
item.SetMetadata("Link", Path.Combine("NuGet", package.Id, package.Version, Path.GetFileName(sharedAsset.Name)));
}
_contentItems.Add(item);
}
}
/// <summary>
/// Fetches the right target from the targets section in a lock file, or attempts to find a "best match" if allowed. The "best match" logic
/// is there to allow a design time build for the IDE to generally work even if something isn't quite right. Throws an exception
/// if either the preferred isn't there and fallbacks aren't allowed, or fallbacks are allowed but nothing at all could be found.
/// </summary>
/// <param name="lockFile">The lock file JSON.</param>
/// <param name="needsRuntimeIdentifier">Whether we must find targets that include the runtime identifier or one without the runtime identifier.</param>
private JObject GetTargetOrAttemptFallback(JObject lockFile, bool needsRuntimeIdentifier)
{
var targets = (JObject)lockFile["targets"];
foreach (var preferredTargetMoniker in TargetMonikers)
{
var preferredTargetMonikerWithOptionalRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(preferredTargetMoniker, needsRuntimeIdentifier);
var target = (JObject)targets[preferredTargetMonikerWithOptionalRuntimeIdentifier];
if (target != null)
{
return target;
}
}
// If we need a runtime identifier, let's see if we have the framework targeted. If we do,
// then we can give a better error message.
bool onlyNeedsRuntimeInProjectJson = false;
if (needsRuntimeIdentifier)
{
foreach (var targetMoniker in TargetMonikers)
{
var targetMonikerWithoutRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(targetMoniker, needsRuntimeIdentifier: false);
if (targets[targetMonikerWithoutRuntimeIdentifier] != null)
{
// We do have a TXM being targeted, so we just are missing the runtime
onlyNeedsRuntimeInProjectJson = true;
break;
}
}
}
if (onlyNeedsRuntimeInProjectJson)
{
GiveErrorForMissingRuntimeIdentifier();
}
else
{
ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingFramework), TargetMonikers.First().ItemSpec);
}
// If we're still here, that means we're allowing fallback, so let's try
foreach (var fallback in TargetMonikers)
{
var target = (JObject)targets[GetTargetMonikerWithOptionalRuntimeIdentifier(fallback, needsRuntimeIdentifier: false)];
if (target != null)
{
return target;
}
}
// Anything goes
var enumerableTargets = targets.Cast<KeyValuePair<string, JToken>>();
var firstTarget = (JObject)enumerableTargets.FirstOrDefault().Value;
if (firstTarget == null)
{
throw new ExceptionFromResource(nameof(Strings.NoTargetsInLockFile));
}
return firstTarget;
}
private void GiveErrorForMissingRuntimeIdentifier()
{
string runtimePiece = '"' + RuntimeIdentifier + "\": { }";
bool hasRuntimesSection;
try
{
using (var streamReader = new StreamReader(new FileStream(ProjectLockFile.Replace(".lock.json", ".json"), FileMode.Open, FileAccess.Read, FileShare.Read)))
{
var jsonFile = JObject.Load(new JsonTextReader(streamReader));
hasRuntimesSection = jsonFile["runtimes"] != null;
}
}
catch
{
// User has a bad file, locked file, no file at all, etc. We'll just assume they have one.
hasRuntimesSection = true;
}
if (hasRuntimesSection)
{
ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingRuntimeInRuntimesSection), RuntimeIdentifier, runtimePiece);
}
else
{
var runtimesSection = "\"runtimes\": { " + runtimePiece + " }";
ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingRuntimesSection), runtimesSection);
}
}
private void ThrowExceptionIfNotAllowingFallback(string resourceName, params string[] messageArgs)
{
if (!AllowFallbackOnTargetSelection)
{
throw new ExceptionFromResource(resourceName, messageArgs);
}
else
{
// We are allowing fallback, so we'll still give a warning but allow us to continue
Log.LogWarningFromResources(resourceName, messageArgs);
}
}
private string GetTargetMonikerWithOptionalRuntimeIdentifier(ITaskItem preferredTargetMoniker, bool needsRuntimeIdentifier)
{
return needsRuntimeIdentifier ? preferredTargetMoniker.ItemSpec + "/" + RuntimeIdentifier : preferredTargetMoniker.ItemSpec;
}
private IEnumerable<ITaskItem> CreateItems(NuGetPackageObject package, string key, bool includePdbs = true)
{
var values = package.TargetObject[key] as JObject;
var items = new List<ITaskItem>();
if (values == null)
{
return items;
}
foreach (var file in values.Properties())
{
if (Path.GetFileName(file.Name) == "_._")
{
continue;
}
string targetPath = null;
string culture = file.Value["locale"]?.ToString();
if (culture != null)
{
targetPath = Path.Combine(culture, Path.GetFileName(file.Name));
}
var item = CreateItem(package, package.GetFullPathToFile(file.Name), targetPath);
item.SetMetadata("Private", "false");
item.SetMetadata(NuGetIsFrameworkReference, "false");
item.SetMetadata(NuGetSourceType, package.IsProject ? NuGetSourceType_Project : NuGetSourceType_Package);
items.Add(item);
// If there's a PDB alongside the implementation, we should copy that as well
if (includePdbs)
{
var pdbFileName = Path.ChangeExtension(item.ItemSpec, ".pdb");
if (_fileExists(pdbFileName))
{
var pdbItem = new TaskItem(pdbFileName);
// CopyMetadataTo also includes an OriginalItemSpec that will point to our original item, as we want
item.CopyMetadataTo(pdbItem);
items.Add(pdbItem);
}
}
}
return items;
}
private static ITaskItem CreateItem(NuGetPackageObject package, string itemSpec, string targetPath = null)
{
var item = new TaskItem(itemSpec);
item.SetMetadata(NuGetPackageIdMetadata, package.Id);
item.SetMetadata(NuGetPackageVersionMetadata, package.Version);
if (targetPath != null)
{
item.SetMetadata("TargetPath", targetPath);
var destinationSubDirectory = Path.GetDirectoryName(targetPath);
if (!string.IsNullOrEmpty(destinationSubDirectory))
{
item.SetMetadata("DestinationSubDirectory", destinationSubDirectory + "\\");
}
}
return item;
}
private void GetReferencedPackages(JObject lockFile)
{
var projectFileDependencyGroups = (JObject)lockFile["projectFileDependencyGroups"];
// find whichever target we will have selected
var actualTarget = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false)?.Parent as JProperty;
string targetMoniker = null;
if (actualTarget != null)
{
targetMoniker = actualTarget.Name.Split('/').FirstOrDefault();
}
foreach (var dependencyGroup in projectFileDependencyGroups.Values<JProperty>())
{
if (dependencyGroup.Name.Length == 0 || dependencyGroup.Name == targetMoniker)
{
foreach (var packageDependency in dependencyGroup.Value.Values<string>())
{
int firstSpace = packageDependency.IndexOf(' ');
if (firstSpace > -1)
{
_referencedPackages.Add(new TaskItem(packageDependency.Substring(0, firstSpace)));
}
}
}
}
}
private string GetNuGetPackagePath(string packageId, string packageVersion)
{
foreach (var packagesFolder in _packageFolders)
{
string packagePath = Path.Combine(packagesFolder, packageId, packageVersion);
if (_directoryExists(packagePath))
{
return packagePath;
}
}
throw new ExceptionFromResource(nameof(Strings.PackageFolderNotFound), packageId, packageVersion,
string.Join(", ", _packageFolders));
}
private string GetNuGetPackagesPath()
{
if (!string.IsNullOrEmpty(NuGetPackagesDirectory))
{
return NuGetPackagesDirectory;
}
string packagesFolder = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
if (!string.IsNullOrEmpty(packagesFolder))
{
return packagesFolder;
}
return string.Empty;
}
private IEnumerable<NuGetPackageObject> GetPackagesFromTarget(JObject lockFile, JObject target)
{
foreach (var package in target)
{
var nameParts = package.Key.Split('/');
var id = nameParts[0];
var version = nameParts[1];
bool isProject = false;
var libraryObject = (JObject)lockFile["libraries"][package.Key];
Func<string> fullPackagePathGenerator;
// If this is a project then we need to figure out it's relative output path
if ((string)libraryObject["type"] == "project")
{
isProject = true;
fullPackagePathGenerator = () =>
{
var relativeMSBuildProjectPath = (string)libraryObject["msbuildProject"];
if (string.IsNullOrEmpty(relativeMSBuildProjectPath))
{
throw new ExceptionFromResource(nameof(Strings.MissingMSBuildPathInProjectPackage), id);
}
var absoluteMSBuildProjectPath = GetAbsolutePathFromProjectRelativePath(relativeMSBuildProjectPath);
string fullPackagePath;
if (!_projectReferencesToOutputBasePaths.TryGetValue(absoluteMSBuildProjectPath, out fullPackagePath))
{
throw new ExceptionFromResource(nameof(Strings.MissingProjectReference), absoluteMSBuildProjectPath, nameof(ProjectReferencesCreatingPackages));
}
return fullPackagePath;
};
}
else
{
fullPackagePathGenerator = () => GetNuGetPackagePath(id, version);
}
yield return new NuGetPackageObject(id, version, isProject, fullPackagePathGenerator, (JObject)package.Value, libraryObject);
}
}
private string GetAbsolutePathFromProjectRelativePath(string path)
{
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(ProjectLockFile)), path));
}
/// <summary>
/// Parse the imageRuntimeVersion from COR header
/// </summary>
private void TryParseRuntimeVersion(string imageRuntimeVersion, out bool isWinMD, out bool isManaged)
{
if (!String.IsNullOrEmpty(imageRuntimeVersion))
{
isWinMD = imageRuntimeVersion.IndexOf("WindowsRuntime", StringComparison.OrdinalIgnoreCase) >= 0;
isManaged = imageRuntimeVersion.IndexOf("CLR", StringComparison.OrdinalIgnoreCase) >= 0;
}
else
{
isWinMD = isManaged = false;
}
}
/// <summary>
/// Given a path get the CLR runtime version of the file
/// </summary>
/// <param name="path">path to the file</param>
/// <returns>The CLR runtime version or empty if the path does not exist.</returns>
private static string TryGetRuntimeVersion(string path)
{
try
{
using (FileStream stream = File.OpenRead(path))
using (PEReader peReader = new PEReader(stream))
{
return peReader.GetMetadataReader().MetadataVersion;
}
}
catch (Exception)
{
return string.Empty;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using System.IO;
using Version = Lucene.Net.Util.Version;
/*
* Analyzer for Brazilian language. Supports an external list of stopwords (words that
* will not be indexed at all) and an external list of exclusions (word that will
* not be stemmed, but indexed).
*
*/
namespace Lucene.Net.Analysis.BR
{
public sealed class BrazilianAnalyzer : Analyzer
{
/*
* List of typical Brazilian stopwords.
*/
//TODO: Make this private in 3.1
public static string[] BRAZILIAN_STOP_WORDS = {
"a", "ainda", "alem", "ambas", "ambos", "antes",
"ao", "aonde", "aos", "apos", "aquele", "aqueles",
"as", "assim", "com", "como", "contra", "contudo",
"cuja", "cujas", "cujo", "cujos", "da", "das", "de",
"dela", "dele", "deles", "demais", "depois", "desde",
"desta", "deste", "dispoe", "dispoem", "diversa",
"diversas", "diversos", "do", "dos", "durante", "e",
"ela", "elas", "ele", "eles", "em", "entao", "entre",
"essa", "essas", "esse", "esses", "esta", "estas",
"este", "estes", "ha", "isso", "isto", "logo", "mais",
"mas", "mediante", "menos", "mesma", "mesmas", "mesmo",
"mesmos", "na", "nas", "nao", "nas", "nem", "nesse", "neste",
"nos", "o", "os", "ou", "outra", "outras", "outro", "outros",
"pelas", "pelas", "pelo", "pelos", "perante", "pois", "por",
"porque", "portanto", "proprio", "propios", "quais", "qual",
"qualquer", "quando", "quanto", "que", "quem", "quer", "se",
"seja", "sem", "sendo", "seu", "seus", "sob", "sobre", "sua",
"suas", "tal", "tambem", "teu", "teus", "toda", "todas",
"todo",
"todos", "tua", "tuas", "tudo", "um", "uma", "umas", "uns"
};
/// <summary>
/// Returns an unmodifiable instance of the default stop-words set.
/// </summary>
/// <returns>Returns an unmodifiable instance of the default stop-words set.</returns>
public static ISet<string> GetDefaultStopSet()
{
return DefaultSetHolder.DEFAULT_STOP_SET;
}
private static class DefaultSetHolder
{
internal static ISet<string> DEFAULT_STOP_SET =
CharArraySet.UnmodifiableSet(new CharArraySet((IEnumerable<string>)BRAZILIAN_STOP_WORDS, false));
}
/// <summary>
/// Contains the stopwords used with the StopFilter.
/// </summary>
private ISet<string> stoptable = Support.Compatibility.SetFactory.CreateHashSet<string>();
private readonly Version matchVersion;
// TODO: make this private in 3.1
/// <summary>
/// Contains words that should be indexed but not stemmed.
/// </summary>
private ISet<string> excltable = Support.Compatibility.SetFactory.CreateHashSet<string>();
public BrazilianAnalyzer(Version matchVersion)
: this(matchVersion, DefaultSetHolder.DEFAULT_STOP_SET)
{
}
/*
* Builds an analyzer with the given stop words
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
*/
public BrazilianAnalyzer(Version matchVersion, ISet<string> stopwords)
{
stoptable = CharArraySet.UnmodifiableSet(CharArraySet.Copy(stopwords));
this.matchVersion = matchVersion;
}
/*
* Builds an analyzer with the given stop words and stemming exclusion words
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
*/
public BrazilianAnalyzer(Version matchVersion, ISet<string> stopwords,
ISet<string> stemExclusionSet)
: this(matchVersion, stopwords)
{
excltable = CharArraySet.UnmodifiableSet(CharArraySet
.Copy(stemExclusionSet));
}
/*
* Builds an analyzer with the given stop words.
* @deprecated use {@link #BrazilianAnalyzer(Version, Set)} instead
*/
public BrazilianAnalyzer(Version matchVersion, params string[] stopwords)
: this(matchVersion, StopFilter.MakeStopSet(stopwords))
{
}
/*
* Builds an analyzer with the given stop words.
* @deprecated use {@link #BrazilianAnalyzer(Version, Set)} instead
*/
public BrazilianAnalyzer(Version matchVersion, IDictionary<string, string> stopwords)
: this(matchVersion, stopwords.Keys.ToArray())
{
}
/*
* Builds an analyzer with the given stop words.
* @deprecated use {@link #BrazilianAnalyzer(Version, Set)} instead
*/
public BrazilianAnalyzer(Version matchVersion, FileInfo stopwords)
: this(matchVersion, WordlistLoader.GetWordSet(stopwords))
{
}
/*
* Builds an exclusionlist from an array of Strings.
* @deprecated use {@link #BrazilianAnalyzer(Version, Set, Set)} instead
*/
public void SetStemExclusionTable(params string[] exclusionlist)
{
excltable = StopFilter.MakeStopSet(exclusionlist);
PreviousTokenStream = null; // force a new stemmer to be created
}
/*
* Builds an exclusionlist from a {@link Map}.
* @deprecated use {@link #BrazilianAnalyzer(Version, Set, Set)} instead
*/
public void SetStemExclusionTable(IDictionary<string, string> exclusionlist)
{
excltable = Support.Compatibility.SetFactory.CreateHashSet(exclusionlist.Keys);
PreviousTokenStream = null; // force a new stemmer to be created
}
/*
* Builds an exclusionlist from the words contained in the given file.
* @deprecated use {@link #BrazilianAnalyzer(Version, Set, Set)} instead
*/
public void SetStemExclusionTable(FileInfo exclusionlist)
{
excltable = WordlistLoader.GetWordSet(exclusionlist);
PreviousTokenStream = null; // force a new stemmer to be created
}
/*
* Creates a {@link TokenStream} which tokenizes all the text in the provided {@link Reader}.
*
* @return A {@link TokenStream} built from a {@link StandardTokenizer} filtered with
* {@link LowerCaseFilter}, {@link StandardFilter}, {@link StopFilter}, and
* {@link BrazilianStemFilter}.
*/
public override TokenStream TokenStream(String fieldName, TextReader reader)
{
TokenStream result = new StandardTokenizer(matchVersion, reader);
result = new LowerCaseFilter(result);
result = new StandardFilter(result);
result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion),
result, stoptable);
result = new BrazilianStemFilter(result, excltable);
return result;
}
private class SavedStreams
{
protected internal Tokenizer source;
protected internal TokenStream result;
};
/*
* Returns a (possibly reused) {@link TokenStream} which tokenizes all the text
* in the provided {@link Reader}.
*
* @return A {@link TokenStream} built from a {@link StandardTokenizer} filtered with
* {@link LowerCaseFilter}, {@link StandardFilter}, {@link StopFilter}, and
* {@link BrazilianStemFilter}.
*/
public override TokenStream ReusableTokenStream(String fieldName, TextReader reader)
{
SavedStreams streams = (SavedStreams) PreviousTokenStream;
if (streams == null)
{
streams = new SavedStreams();
streams.source = new StandardTokenizer(matchVersion, reader);
streams.result = new LowerCaseFilter(streams.source);
streams.result = new StandardFilter(streams.result);
streams.result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion),
streams.result, stoptable);
streams.result = new BrazilianStemFilter(streams.result, excltable);
PreviousTokenStream = streams;
}
else
{
streams.source.Reset(reader);
}
return streams.result;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcmv = Google.Cloud.Monitoring.V3;
namespace Google.Cloud.Monitoring.V3
{
public partial class ListGroupsRequest
{
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="ChildrenOfGroup"/> resource name property.
/// </summary>
public GroupName ChildrenOfGroupAsGroupName
{
get => string.IsNullOrEmpty(ChildrenOfGroup) ? null : GroupName.Parse(ChildrenOfGroup, allowUnparsed: true);
set => ChildrenOfGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="ChildrenOfGroup"/> resource name property.
/// </summary>
public gax::IResourceName ChildrenOfGroupAsResourceName
{
get
{
if (string.IsNullOrEmpty(ChildrenOfGroup))
{
return null;
}
if (GroupName.TryParse(ChildrenOfGroup, out GroupName group))
{
return group;
}
return gax::UnparsedResourceName.Parse(ChildrenOfGroup);
}
set => ChildrenOfGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="AncestorsOfGroup"/> resource name property.
/// </summary>
public GroupName AncestorsOfGroupAsGroupName
{
get => string.IsNullOrEmpty(AncestorsOfGroup) ? null : GroupName.Parse(AncestorsOfGroup, allowUnparsed: true);
set => AncestorsOfGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="AncestorsOfGroup"/> resource name property.
/// </summary>
public gax::IResourceName AncestorsOfGroupAsResourceName
{
get
{
if (string.IsNullOrEmpty(AncestorsOfGroup))
{
return null;
}
if (GroupName.TryParse(AncestorsOfGroup, out GroupName group))
{
return group;
}
return gax::UnparsedResourceName.Parse(AncestorsOfGroup);
}
set => AncestorsOfGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="DescendantsOfGroup"/> resource name property.
/// </summary>
public GroupName DescendantsOfGroupAsGroupName
{
get => string.IsNullOrEmpty(DescendantsOfGroup) ? null : GroupName.Parse(DescendantsOfGroup, allowUnparsed: true);
set => DescendantsOfGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="DescendantsOfGroup"/> resource name
/// property.
/// </summary>
public gax::IResourceName DescendantsOfGroupAsResourceName
{
get
{
if (string.IsNullOrEmpty(DescendantsOfGroup))
{
return null;
}
if (GroupName.TryParse(DescendantsOfGroup, out GroupName group))
{
return group;
}
return gax::UnparsedResourceName.Parse(DescendantsOfGroup);
}
set => DescendantsOfGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gagr::ProjectName ProjectName
{
get => string.IsNullOrEmpty(Name) ? null : gagr::ProjectName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gagr::OrganizationName OrganizationName
{
get => string.IsNullOrEmpty(Name) ? null : gagr::OrganizationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gagr::FolderName FolderName
{
get => string.IsNullOrEmpty(Name) ? null : gagr::FolderName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gagr::ProjectName.TryParse(Name, out gagr::ProjectName project))
{
return project;
}
if (gagr::OrganizationName.TryParse(Name, out gagr::OrganizationName organization))
{
return organization;
}
if (gagr::FolderName.TryParse(Name, out gagr::FolderName folder))
{
return folder;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class GetGroupRequest
{
/// <summary>
/// <see cref="gcmv::GroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::GroupName GroupName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::GroupName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::GroupName.TryParse(Name, out gcmv::GroupName group))
{
return group;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateGroupRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gagr::ProjectName ProjectName
{
get => string.IsNullOrEmpty(Name) ? null : gagr::ProjectName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gagr::OrganizationName OrganizationName
{
get => string.IsNullOrEmpty(Name) ? null : gagr::OrganizationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gagr::FolderName FolderName
{
get => string.IsNullOrEmpty(Name) ? null : gagr::FolderName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gagr::ProjectName.TryParse(Name, out gagr::ProjectName project))
{
return project;
}
if (gagr::OrganizationName.TryParse(Name, out gagr::OrganizationName organization))
{
return organization;
}
if (gagr::FolderName.TryParse(Name, out gagr::FolderName folder))
{
return folder;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteGroupRequest
{
/// <summary>
/// <see cref="gcmv::GroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::GroupName GroupName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::GroupName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::GroupName.TryParse(Name, out gcmv::GroupName group))
{
return group;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class ListGroupMembersRequest
{
/// <summary>
/// <see cref="gcmv::GroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::GroupName GroupName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::GroupName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::GroupName.TryParse(Name, out gcmv::GroupName group))
{
return group;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Windows;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Input;
namespace WPFDemo.Common.Extensions
{
[System.Diagnostics.DebuggerStepThrough]
public static class WPFs
{
#region Static Methods
public static void Execute(this ICommand Command)
{
if (Command == null)
return;
if (Command.CanExecute(null))
Command.Execute(null);
}
public static bool CanExecute(this ICommand Command)
{
if (Command == null)
return false;
return Command.CanExecute(null);
}
public static System.Windows.MessageBoxButton ToMessageBoxButton(this System.Windows.Forms.MessageBoxButtons MessageBoxButtons)
{
switch (MessageBoxButtons)
{
case System.Windows.Forms.MessageBoxButtons.AbortRetryIgnore:
return MessageBoxButton.YesNoCancel;
case System.Windows.Forms.MessageBoxButtons.OK:
return MessageBoxButton.OK;
case System.Windows.Forms.MessageBoxButtons.OKCancel:
return MessageBoxButton.OKCancel;
case System.Windows.Forms.MessageBoxButtons.RetryCancel:
return MessageBoxButton.YesNo;
case System.Windows.Forms.MessageBoxButtons.YesNo:
return MessageBoxButton.YesNo;
case System.Windows.Forms.MessageBoxButtons.YesNoCancel:
return MessageBoxButton.YesNoCancel;
default:
return MessageBoxButton.OK;
}
}
public static System.Windows.MessageBoxImage ToMessageBoxImage(this System.Windows.Forms.MessageBoxIcon MessageBoxIcon)
{
switch (MessageBoxIcon)
{
case System.Windows.Forms.MessageBoxIcon.Information:
return MessageBoxImage.Information;
case System.Windows.Forms.MessageBoxIcon.Error:
return MessageBoxImage.Stop;
case System.Windows.Forms.MessageBoxIcon.Exclamation:
return MessageBoxImage.Warning;
case System.Windows.Forms.MessageBoxIcon.None:
return MessageBoxImage.None;
case System.Windows.Forms.MessageBoxIcon.Question:
return MessageBoxImage.Question;
default:
return MessageBoxImage.None;
}
}
public static System.Windows.MessageBoxResult ToMessageBoxResult(this System.Windows.Forms.DialogResult DialogResult)
{
switch (DialogResult)
{
case System.Windows.Forms.DialogResult.Abort:
return MessageBoxResult.No;
case System.Windows.Forms.DialogResult.Cancel:
return MessageBoxResult.Cancel;
case System.Windows.Forms.DialogResult.Ignore:
return MessageBoxResult.None;
case System.Windows.Forms.DialogResult.No:
return MessageBoxResult.No;
case System.Windows.Forms.DialogResult.None:
return MessageBoxResult.None;
case System.Windows.Forms.DialogResult.OK:
return MessageBoxResult.OK;
case System.Windows.Forms.DialogResult.Retry:
return MessageBoxResult.Yes;
case System.Windows.Forms.DialogResult.Yes:
return MessageBoxResult.Yes;
default:
return MessageBoxResult.None;
}
}
public static T FindVisualChild<T>(this DependencyObject obj) where T : DependencyObject
{
return FindVisualChildEx<T>(obj, null);
}
public static T FindVisualChildEx<T>(this DependencyObject obj, Func<T, bool> WhereFunc) where T : DependencyObject
{
//http://msdn.microsoft.com/en-us/library/bb613579.aspx
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (
child != null && child is T &&
(WhereFunc == null || WhereFunc((T)obj))
)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
public static T FindVisualParent<T>(this DependencyObject obj) where T : DependencyObject
{
var Parent = VisualTreeHelper.GetParent(obj);
if (Parent == null)
return null;
else if (Parent is T)
return Parent as T;
else
return FindVisualParent<T>(Parent);
}
public static DependencyObject FindVisualParent(this DependencyObject obj, string TypeName)
{
var Parent = VisualTreeHelper.GetParent(obj);
if (Parent == null)
return null;
else if (Parent.GetType().Name.Equals(TypeName))
return Parent;
else
return FindVisualParent(Parent, TypeName);
}
/// <summary>
/// Find the visual children of type T. Does not recurse under these children.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject obj) where T : DependencyObject
{
return FindVisualChildren<T>(obj, true);
}
/// <summary>
/// Find the visual children of type T. Will recurse to the end.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static IEnumerable<T> FindAllVisualChildren<T>(this DependencyObject obj) where T : DependencyObject
{
return FindVisualChildren<T>(obj, false);
}
private static IEnumerable<T> FindVisualChildren<T>(this DependencyObject obj, bool stopRecurseOnHit) where T : DependencyObject
{
if (obj == null)
throw new ArgumentNullException("obj");
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
//The previous incarnation of FindVisualChildren<T> would stop its recursion hunting when it first
//encountered the child of type T.
//The previous incarnation of FindAllVisualChildren<T> would take it and continue recursion.
var child = VisualTreeHelper.GetChild(obj, i);
bool isHit = false;
if (child is T)
{
yield return child as T;
isHit = true;
}
//Thus, if we are not stopping the recursion on it
//OR we are stopping but it wasn't a hit,
//then continue.
if (!stopRecurseOnHit || !isHit)
{
foreach (var GrandChild in FindVisualChildren<T>(child, stopRecurseOnHit))
yield return GrandChild;
}
}
}
public static IEnumerable<T> FindInputBindings<T>(this UIElement Element)
where T : InputBinding
{
var Current = Element as FrameworkElement;
while (Current != null)
{
foreach (InputBinding Item in Current.InputBindings)
if (Item is T)
yield return Item as T;
Current = Current.Parent as FrameworkElement;
}
}
public static IEnumerable<KeyBinding> FindKeyBindings(this UIElement Element)
{
return FindInputBindings<KeyBinding>(Element);
}
public static IEnumerable<MouseBinding> FindMouseBindings(this UIElement Element)
{
return FindInputBindings<MouseBinding>(Element);
}
public static void SetElementFocus(this UIElement element)
{
SetElementFocus(element, null);
}
public static void SetElementFocus(this UIElement element, string specificElementName)
{
if (element == null)
throw new ArgumentNullException("Element");
//If a specific name is given, attempt to find a child with that name.
//If one is found, either focus on it or its first focusable child.
//If none of these are focusable, exit out.
//If no specific name is given,
//attempt to set focus on the given element or its first focusable child.
UIElement FocusElement = null;
if (!string.IsNullOrEmpty(specificElementName))
{
var NamedChild = element.FindAllVisualChildren<FrameworkElement>().Where(o => o.Name == specificElementName).FirstOrDefault();
if (NamedChild.Focusable)
FocusElement = NamedChild;
else
FocusElement = NamedChild.FindAllVisualChildren<UIElement>().Where(o => o.Focusable).FirstOrDefault();
}
else
{
if (element.Focusable)
FocusElement = element;
else
FocusElement = element.FindAllVisualChildren<UIElement>().Where(o => o.Focusable).FirstOrDefault();
}
if (FocusElement == null)
return;
FocusElement.Focus();
Keyboard.Focus(FocusElement);
}
/// <summary>
/// Calls UpdateSource on the binding expression for a dependency object and property. Does nothing if there is no binding.
/// </summary>
/// <param name="o"></param>
/// <param name="property"></param>
/// <returns></returns>
public static bool UpdateBindingExpressionSource(this DependencyObject o, DependencyProperty property)
{
if (o == null)
throw new ArgumentNullException("o");
if (property == null)
throw new ArgumentNullException("property");
var BindingExpression = System.Windows.Data.BindingOperations.GetBindingExpression(o, property);
if (BindingExpression != null)
{
BindingExpression.UpdateSource();
return true;
}
else
return false;
}
/// <summary>
/// Calls UpdateTarget on the binding expression for a dependency object and property. Does nothing if there is no binding.
/// </summary>
/// <param name="o"></param>
/// <param name="property"></param>
/// <returns></returns>
public static bool UpdateBindingExpressionTarget(this DependencyObject o, DependencyProperty property)
{
if (o == null)
throw new ArgumentNullException("o");
if (property == null)
throw new ArgumentNullException("property");
var BindingExpression = System.Windows.Data.BindingOperations.GetBindingExpression(o, property);
if (BindingExpression != null)
{
BindingExpression.UpdateTarget();
return true;
}
else
return false;
}
public static System.Windows.Media.Color ToMediaColor(this System.Drawing.Color Color)
{
return System.Windows.Media.Color.FromArgb(Color.A, Color.R, Color.G, Color.B);
}
public static BitmapImage ToBitmapImage(this byte[] imageBytes)
{
if (imageBytes == null || imageBytes.Length == 0)
return null;
var Image = new BitmapImage();
Image.BeginInit();
using (var Stream = new System.IO.MemoryStream(imageBytes))
{
Image.CacheOption = BitmapCacheOption.OnLoad;
Image.StreamSource = Stream;
Image.EndInit();
}
return Image;
}
public static System.Windows.Controls.ItemsControl GetHost(this System.Windows.Controls.ItemContainerGenerator generator)
{
if (generator == null)
throw new ArgumentNullException("generator");
var HostProperty = typeof(System.Windows.Controls.ItemContainerGenerator).GetProperty("Host", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (HostProperty == null || !HostProperty.CanRead)
return null;
return HostProperty.GetValue(generator, null) as System.Windows.Controls.ItemsControl;
}
/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
/// http://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap
/// </summary>
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
/// </remarks>
/// <param name="source">The source bitmap.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
BitmapSource bitSrc = null;
var hBitmap = source.GetHbitmap();
try
{
bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
catch (Win32Exception)
{
bitSrc = null;
}
finally
{
DeleteObject(hBitmap);
}
return bitSrc;
}
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using GitTools.Testing;
using GitVersion;
using GitVersion.Extensions;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
using GitVersionCore.Tests.Helpers;
using LibGit2Sharp;
using NUnit.Framework;
namespace GitVersionCore.Tests.IntegrationTests
{
public class MainlineDevelopmentMode : TestBase
{
private readonly Config config = new Config
{
VersioningMode = VersioningMode.Mainline
};
[Test]
public void VerifyNonMasterMainlineVersionIdenticalAsMaster()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("2 +semver: major");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.0", config);
fixture.BranchTo("support/1.0", "support");
fixture.AssertFullSemver("1.0.0", config);
}
[Test]
public void MergedFeatureBranchesToMasterImpliesRelease()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("2");
fixture.AssertFullSemver("1.0.1-foo.1", config);
fixture.MakeACommit("2.1");
fixture.AssertFullSemver("1.0.1-foo.2", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.1", config);
fixture.BranchTo("feature/foo2", "foo2");
fixture.MakeACommit("3 +semver: minor");
fixture.AssertFullSemver("1.1.0-foo2.1", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo2");
fixture.AssertFullSemver("1.1.0", config);
fixture.BranchTo("feature/foo3", "foo3");
fixture.MakeACommit("4");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo3");
fixture.SequenceDiagram.NoteOver("Merge message contains '+semver: minor'", "master");
var commit = fixture.Repository.Head.Tip;
// Put semver increment in merge message
fixture.Repository.Commit(commit.Message + " +semver: minor", commit.Author, commit.Committer, new CommitOptions
{
AmendPreviousCommit = true
});
fixture.AssertFullSemver("1.2.0", config);
fixture.BranchTo("feature/foo4", "foo4");
fixture.MakeACommit("5 +semver: major");
fixture.AssertFullSemver("2.0.0-foo4.1", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo4");
fixture.AssertFullSemver("2.0.0", config);
// We should evaluate any commits not included in merge commit calculations for direct commit/push or squash to merge commits
fixture.MakeACommit("6 +semver: major");
fixture.AssertFullSemver("3.0.0", config);
fixture.MakeACommit("7 +semver: minor");
fixture.AssertFullSemver("3.1.0", config);
fixture.MakeACommit("8");
fixture.AssertFullSemver("3.1.1", config);
// Finally verify that the merge commits still function properly
fixture.BranchTo("feature/foo5", "foo5");
fixture.MakeACommit("9 +semver: minor");
fixture.AssertFullSemver("3.2.0-foo5.1", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo5");
fixture.AssertFullSemver("3.2.0", config);
// One more direct commit for good measure
fixture.MakeACommit("10 +semver: minor");
fixture.AssertFullSemver("3.3.0", config);
// And we can commit without bumping semver
fixture.MakeACommit("11 +semver: none");
fixture.AssertFullSemver("3.3.0", config);
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void VerifyPullRequestsActLikeContinuousDelivery()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.1", config);
fixture.BranchTo("feature/foo", "foo");
fixture.AssertFullSemver("1.0.2-foo.0", config);
fixture.MakeACommit();
fixture.MakeACommit();
fixture.Repository.CreatePullRequestRef("feature/foo", "master", normalise: true, prNumber: 8);
fixture.AssertFullSemver("1.0.2-PullRequest0008.3", config);
}
[Test]
public void SupportBranches()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit(); // 1.0.1
fixture.MakeACommit(); // 1.0.2
fixture.AssertFullSemver("1.0.2", config);
fixture.BranchTo("support/1.0", "support10");
fixture.AssertFullSemver("1.0.2", config);
// Move master on
fixture.Checkout("master");
fixture.MakeACommit("+semver: major"); // 2.0.0 (on master)
fixture.AssertFullSemver("2.0.0", config);
// Continue on support/1.0
fixture.Checkout("support/1.0");
fixture.MakeACommit(); // 1.0.3
fixture.MakeACommit(); // 1.0.4
fixture.AssertFullSemver("1.0.4", config);
fixture.BranchTo("feature/foo", "foo");
fixture.AssertFullSemver("1.0.5-foo.0", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.5-foo.1", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.5-foo.2", config);
fixture.Repository.CreatePullRequestRef("feature/foo", "support/1.0", normalise: true, prNumber: 7);
fixture.AssertFullSemver("1.0.5-PullRequest0007.3", config);
}
[Test]
public void VerifyForwardMerge()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit(); // 1.0.1
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.2-foo.1", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.2-foo.2", config);
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.2", config);
fixture.Checkout("feature/foo");
// This may seem surprising, but this happens because we branched off mainline
// and incremented. Mainline has then moved on. We do not follow mainline
// in feature branches, you need to merge mainline in to get the mainline version
fixture.AssertFullSemver("1.0.2-foo.2", config);
fixture.MergeNoFF("master");
fixture.AssertFullSemver("1.0.3-foo.3", config);
}
[Test]
public void VerifySupportForwardMerge()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit(); // 1.0.1
fixture.BranchTo("support/1.0", "support10");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.Checkout("master");
fixture.MakeACommit("+semver: minor");
fixture.AssertFullSemver("1.1.0", config);
fixture.MergeNoFF("support/1.0");
fixture.AssertFullSemver("1.1.1", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.2", config);
fixture.Checkout("support/1.0");
fixture.AssertFullSemver("1.0.3", config);
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.4-foo.2", config); // TODO This probably should be 1.0.5
}
[Test]
public void VerifyDevelopTracksMasterVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit();
// branching increments the version
fixture.BranchTo("develop");
fixture.AssertFullSemver("1.1.0-alpha.0", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// merging develop into master increments minor version on master
fixture.Checkout("master");
fixture.MergeNoFF("develop");
fixture.AssertFullSemver("1.1.0", config);
// a commit on develop before the merge still has the same version number
fixture.Checkout("develop");
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// moving on to further work on develop tracks master's version from the merge
fixture.MakeACommit();
fixture.AssertFullSemver("1.2.0-alpha.1", config);
// adding a commit to master increments patch
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.1", config);
// adding a commit to master doesn't change develop's version
fixture.Checkout("develop");
fixture.AssertFullSemver("1.2.0-alpha.1", config);
}
[Test]
public void VerifyDevelopFeatureTracksMasterVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit();
// branching increments the version
fixture.BranchTo("develop");
fixture.AssertFullSemver("1.1.0-alpha.0", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// merging develop into master increments minor version on master
fixture.Checkout("master");
fixture.MergeNoFF("develop");
fixture.AssertFullSemver("1.1.0", config);
// a commit on develop before the merge still has the same version number
fixture.Checkout("develop");
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// a branch from develop before the merge tracks the pre-merge version from master
// (note: the commit on develop looks like a commit to this branch, thus the .1)
fixture.BranchTo("feature/foo");
fixture.AssertFullSemver("1.0.2-foo.1", config);
// further work on the branch tracks the merged version from master
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.1-foo.1", config);
// adding a commit to master increments patch
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.1", config);
// adding a commit to master doesn't change the feature's version
fixture.Checkout("feature/foo");
fixture.AssertFullSemver("1.1.1-foo.1", config);
// merging the feature to develop increments develop
fixture.Checkout("develop");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.2.0-alpha.2", config);
}
[Test]
public void VerifyMergingMasterToFeatureDoesNotCauseBranchCommitsToIncrementVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.Checkout("master");
fixture.MakeACommit("second in master");
fixture.Checkout("feature/foo");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in foo");
fixture.Checkout("master");
fixture.MakeATaggedCommit("1.0.0");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.1", config);
}
[Test]
public void VerifyMergingMasterToFeatureDoesNotStopMasterCommitsIncrementingVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.Checkout("master");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit("third in master");
fixture.Checkout("feature/foo");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in foo");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.2", config);
}
[Test]
public void VerifyIssue1154CanForwardMergeMasterToFeatureBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("feature/branch2");
fixture.BranchTo("feature/branch1");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.Checkout("master");
fixture.MergeNoFF("feature/branch1");
fixture.AssertFullSemver("0.1.1", config);
fixture.Checkout("feature/branch2");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.MakeACommit();
fixture.MergeNoFF("master");
fixture.AssertFullSemver("0.1.2-branch2.4", config);
}
[Test]
public void VerifyMergingMasterIntoAFeatureBranchWorksWithMultipleBranches()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.BranchTo("feature/bar", "bar");
fixture.MakeACommit("first in bar");
fixture.Checkout("master");
fixture.MakeACommit("second in master");
fixture.Checkout("feature/foo");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in foo");
fixture.Checkout("feature/bar");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in bar");
fixture.Checkout("master");
fixture.MakeATaggedCommit("1.0.0");
fixture.MergeNoFF("feature/foo");
fixture.MergeNoFF("feature/bar");
fixture.AssertFullSemver("1.0.2", config);
}
[Test]
public void MergingFeatureBranchThatIncrementsMinorNumberIncrementsMinorVersionOfMaster()
{
var currentConfig = new Config
{
VersioningMode = VersioningMode.Mainline,
Branches = new Dictionary<string, BranchConfig>
{
{
"feature", new BranchConfig
{
VersioningMode = VersioningMode.ContinuousDeployment,
Increment = IncrementStrategy.Minor
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.MakeATaggedCommit("1.0.0");
fixture.AssertFullSemver("1.0.0", currentConfig);
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.MakeACommit("second in foo");
fixture.AssertFullSemver("1.1.0-foo.2", currentConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.1.0", currentConfig);
}
[Test]
public void VerifyIncrementConfigIsHonoured()
{
var minorIncrementConfig = new Config
{
VersioningMode = VersioningMode.Mainline,
Increment = IncrementStrategy.Minor,
Branches = new Dictionary<string, BranchConfig>
{
{
"master",
new BranchConfig
{
Increment = IncrementStrategy.Minor,
Name = "master",
Regex = "master"
}
},
{
"feature",
new BranchConfig
{
Increment = IncrementStrategy.Minor,
Name = "feature",
Regex = "features?[/-]"
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("2");
fixture.AssertFullSemver("1.1.0-foo.1", minorIncrementConfig);
fixture.MakeACommit("2.1");
fixture.AssertFullSemver("1.1.0-foo.2", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.1.0", minorIncrementConfig);
fixture.BranchTo("feature/foo2", "foo2");
fixture.MakeACommit("3 +semver: patch");
fixture.AssertFullSemver("1.1.1-foo2.1", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo2");
fixture.AssertFullSemver("1.1.1", minorIncrementConfig);
fixture.BranchTo("feature/foo3", "foo3");
fixture.MakeACommit("4");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo3");
fixture.SequenceDiagram.NoteOver("Merge message contains '+semver: patch'", "master");
var commit = fixture.Repository.Head.Tip;
// Put semver increment in merge message
fixture.Repository.Commit(commit.Message + " +semver: patch", commit.Author, commit.Committer, new CommitOptions
{
AmendPreviousCommit = true
});
fixture.AssertFullSemver("1.1.2", minorIncrementConfig);
fixture.BranchTo("feature/foo4", "foo4");
fixture.MakeACommit("5 +semver: major");
fixture.AssertFullSemver("2.0.0-foo4.1", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo4");
fixture.AssertFullSemver("2.0.0", config);
// We should evaluate any commits not included in merge commit calculations for direct commit/push or squash to merge commits
fixture.MakeACommit("6 +semver: major");
fixture.AssertFullSemver("3.0.0", minorIncrementConfig);
fixture.MakeACommit("7");
fixture.AssertFullSemver("3.1.0", minorIncrementConfig);
fixture.MakeACommit("8 +semver: patch");
fixture.AssertFullSemver("3.1.1", minorIncrementConfig);
// Finally verify that the merge commits still function properly
fixture.BranchTo("feature/foo5", "foo5");
fixture.MakeACommit("9 +semver: patch");
fixture.AssertFullSemver("3.1.2-foo5.1", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo5");
fixture.AssertFullSemver("3.1.2", minorIncrementConfig);
// One more direct commit for good measure
fixture.MakeACommit("10 +semver: patch");
fixture.AssertFullSemver("3.1.3", minorIncrementConfig);
// And we can commit without bumping semver
fixture.MakeACommit("11 +semver: none");
fixture.AssertFullSemver("3.1.3", minorIncrementConfig);
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
}
internal static class CommitExtensions
{
public static void MakeACommit(this RepositoryFixtureBase fixture, string commitMsg)
{
fixture.Repository.MakeACommit(commitMsg);
var diagramBuilder = (StringBuilder)typeof(SequenceDiagram)
.GetField("_diagramBuilder", BindingFlags.Instance | BindingFlags.NonPublic)
?.GetValue(fixture.SequenceDiagram);
string GetParticipant(string participant) =>
(string)typeof(SequenceDiagram).GetMethod("GetParticipant", BindingFlags.Instance | BindingFlags.NonPublic)
?.Invoke(fixture.SequenceDiagram, new object[]
{
participant
});
diagramBuilder.AppendLineFormat("{0} -> {0}: Commit '{1}'", GetParticipant(fixture.Repository.Head.FriendlyName),
commitMsg);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcbbv = Google.Cloud.Billing.Budgets.V1;
using sys = System;
namespace Google.Cloud.Billing.Budgets.V1
{
/// <summary>Resource name for the <c>Budget</c> resource.</summary>
public sealed partial class BudgetName : gax::IResourceName, sys::IEquatable<BudgetName>
{
/// <summary>The possible contents of <see cref="BudgetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>billingAccounts/{billing_account}/budgets/{budget}</c>.
/// </summary>
BillingAccountBudget = 1,
}
private static gax::PathTemplate s_billingAccountBudget = new gax::PathTemplate("billingAccounts/{billing_account}/budgets/{budget}");
/// <summary>Creates a <see cref="BudgetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="BudgetName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static BudgetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BudgetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BudgetName"/> with the pattern <c>billingAccounts/{billing_account}/budgets/{budget}</c>
/// .
/// </summary>
/// <param name="billingAccountId">The <c>BillingAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="budgetId">The <c>Budget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BudgetName"/> constructed from the provided ids.</returns>
public static BudgetName FromBillingAccountBudget(string billingAccountId, string budgetId) =>
new BudgetName(ResourceNameType.BillingAccountBudget, billingAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(billingAccountId, nameof(billingAccountId)), budgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(budgetId, nameof(budgetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BudgetName"/> with pattern
/// <c>billingAccounts/{billing_account}/budgets/{budget}</c>.
/// </summary>
/// <param name="billingAccountId">The <c>BillingAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="budgetId">The <c>Budget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BudgetName"/> with pattern
/// <c>billingAccounts/{billing_account}/budgets/{budget}</c>.
/// </returns>
public static string Format(string billingAccountId, string budgetId) =>
FormatBillingAccountBudget(billingAccountId, budgetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BudgetName"/> with pattern
/// <c>billingAccounts/{billing_account}/budgets/{budget}</c>.
/// </summary>
/// <param name="billingAccountId">The <c>BillingAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="budgetId">The <c>Budget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BudgetName"/> with pattern
/// <c>billingAccounts/{billing_account}/budgets/{budget}</c>.
/// </returns>
public static string FormatBillingAccountBudget(string billingAccountId, string budgetId) =>
s_billingAccountBudget.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(billingAccountId, nameof(billingAccountId)), gax::GaxPreconditions.CheckNotNullOrEmpty(budgetId, nameof(budgetId)));
/// <summary>Parses the given resource name string into a new <see cref="BudgetName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>billingAccounts/{billing_account}/budgets/{budget}</c></description></item>
/// </list>
/// </remarks>
/// <param name="budgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="BudgetName"/> if successful.</returns>
public static BudgetName Parse(string budgetName) => Parse(budgetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BudgetName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>billingAccounts/{billing_account}/budgets/{budget}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="budgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="BudgetName"/> if successful.</returns>
public static BudgetName Parse(string budgetName, bool allowUnparsed) =>
TryParse(budgetName, allowUnparsed, out BudgetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BudgetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>billingAccounts/{billing_account}/budgets/{budget}</c></description></item>
/// </list>
/// </remarks>
/// <param name="budgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BudgetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string budgetName, out BudgetName result) => TryParse(budgetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BudgetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>billingAccounts/{billing_account}/budgets/{budget}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="budgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BudgetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string budgetName, bool allowUnparsed, out BudgetName result)
{
gax::GaxPreconditions.CheckNotNull(budgetName, nameof(budgetName));
gax::TemplatedResourceName resourceName;
if (s_billingAccountBudget.TryParseName(budgetName, out resourceName))
{
result = FromBillingAccountBudget(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(budgetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BudgetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string billingAccountId = null, string budgetId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BillingAccountId = billingAccountId;
BudgetId = budgetId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BudgetName"/> class from the component parts of pattern
/// <c>billingAccounts/{billing_account}/budgets/{budget}</c>
/// </summary>
/// <param name="billingAccountId">The <c>BillingAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="budgetId">The <c>Budget</c> ID. Must not be <c>null</c> or empty.</param>
public BudgetName(string billingAccountId, string budgetId) : this(ResourceNameType.BillingAccountBudget, billingAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(billingAccountId, nameof(billingAccountId)), budgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(budgetId, nameof(budgetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>BillingAccount</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string BillingAccountId { get; }
/// <summary>
/// The <c>Budget</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string BudgetId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.BillingAccountBudget: return s_billingAccountBudget.Expand(BillingAccountId, BudgetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as BudgetName);
/// <inheritdoc/>
public bool Equals(BudgetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BudgetName a, BudgetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BudgetName a, BudgetName b) => !(a == b);
}
public partial class Budget
{
/// <summary>
/// <see cref="gcbbv::BudgetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbbv::BudgetName BudgetName
{
get => string.IsNullOrEmpty(Name) ? null : gcbbv::BudgetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Diagnostics;
namespace System.DirectoryServices.ActiveDirectory
{
public class ActiveDirectorySiteLink : IDisposable
{
internal readonly DirectoryContext context = null;
private readonly string _name = null;
private readonly ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
private bool _disposed = false;
internal bool existing = false;
internal readonly DirectoryEntry cachedEntry = null;
private const int systemDefaultCost = 0;
private readonly TimeSpan _systemDefaultInterval = new TimeSpan(0, 15, 0);
private const int appDefaultCost = 100;
private const int appDefaultInterval = 180;
private readonly ActiveDirectorySiteCollection _sites = new ActiveDirectorySiteCollection();
private bool _siteRetrieved = false;
public ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName) : this(context, siteLinkName, ActiveDirectoryTransportType.Rpc, null)
{
}
public ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport) : this(context, siteLinkName, transport, null)
{
}
public ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport, ActiveDirectorySchedule schedule)
{
ValidateArgument(context, siteLinkName, transport);
// work with copy of the context
context = new DirectoryContext(context);
this.context = context;
_name = siteLinkName;
_transport = transport;
// bind to the rootdse to get the configurationnamingcontext
DirectoryEntry de;
try
{
de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
string parentDN = null;
if (transport == ActiveDirectoryTransportType.Rpc)
parentDN = "CN=IP,CN=Inter-Site Transports,CN=Sites," + config;
else
parentDN = "CN=SMTP,CN=Inter-Site Transports,CN=Sites," + config;
de = DirectoryEntryManager.GetDirectoryEntry(context, parentDN);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
{
string rdn = "cn=" + _name;
rdn = Utils.GetEscapedPath(rdn);
cachedEntry = de.Children.Add(rdn, "siteLink");
cachedEntry.Properties["cost"].Value = appDefaultCost;
cachedEntry.Properties["replInterval"].Value = appDefaultInterval;
if (schedule != null)
cachedEntry.Properties[nameof(schedule)].Value = schedule.GetUnmanagedSchedule();
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// if it is ADAM and transport type is SMTP, throw NotSupportedException.
DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp)
{
throw new NotSupportedException(SR.NotSupportTransportSMTP);
}
}
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
de.Dispose();
}
}
internal ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport, bool existing, DirectoryEntry entry)
{
this.context = context;
_name = siteLinkName;
_transport = transport;
this.existing = existing;
this.cachedEntry = entry;
}
public static ActiveDirectorySiteLink FindByName(DirectoryContext context, string siteLinkName)
{
return FindByName(context, siteLinkName, ActiveDirectoryTransportType.Rpc);
}
public static ActiveDirectorySiteLink FindByName(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport)
{
ValidateArgument(context, siteLinkName, transport);
// work with copy of the context
context = new DirectoryContext(context);
// bind to the rootdse to get the configurationnamingcontext
DirectoryEntry de;
try
{
de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
string containerDN = "CN=Inter-Site Transports,CN=Sites," + config;
if (transport == ActiveDirectoryTransportType.Rpc)
containerDN = "CN=IP," + containerDN;
else
containerDN = "CN=SMTP," + containerDN;
de = DirectoryEntryManager.GetDirectoryEntry(context, containerDN);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
{
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=siteLink)(objectCategory=SiteLink)(name=" + Utils.GetEscapedFilterValue(siteLinkName) + "))",
new string[] { "distinguishedName" },
SearchScope.OneLevel,
false, /* don't need paged search */
false /* don't need to cache result */
);
SearchResult srchResult = adSearcher.FindOne();
if (srchResult == null)
{
// no such sitelink object
Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLink), siteLinkName);
throw e;
}
else
{
DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry();
// it is an existing site object
ActiveDirectorySiteLink link = new ActiveDirectorySiteLink(context, siteLinkName, transport, true, connectionEntry);
return link;
}
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// if it is ADAM and transport type is SMTP, throw NotSupportedException.
DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp)
{
throw new NotSupportedException(SR.NotSupportTransportSMTP);
}
else
{
// object is not found since we cannot even find the container in which to search
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLink), siteLinkName);
}
}
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
de.Dispose();
}
}
public string Name
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _name;
}
}
public ActiveDirectoryTransportType TransportType
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _transport;
}
}
public ActiveDirectorySiteCollection Sites
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
// if asked the first time, we need to properly construct the site collection
if (!_siteRetrieved)
{
_sites.initialized = false;
_sites.Clear();
GetSites();
_siteRetrieved = true;
}
}
_sites.initialized = true;
_sites.de = cachedEntry;
_sites.context = context;
return _sites;
}
}
public int Cost
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
if (cachedEntry.Properties.Contains("cost"))
return (int)cachedEntry.Properties["cost"][0];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
// property is not set in the directory, we need to return the system default value
return systemDefaultCost;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (value < 0)
throw new ArgumentException(nameof(value));
try
{
cachedEntry.Properties["cost"].Value = value;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public TimeSpan ReplicationInterval
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
if (cachedEntry.Properties.Contains("replInterval"))
{
int tmpValue = (int)cachedEntry.Properties["replInterval"][0];
return new TimeSpan(0, tmpValue, 0);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
return _systemDefaultInterval;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (value < TimeSpan.Zero)
throw new ArgumentException(SR.NoNegativeTime, nameof(value));
double tmpVal = value.TotalMinutes;
if (tmpVal > int.MaxValue)
throw new ArgumentException(SR.ReplicationIntervalExceedMax, nameof(value));
int totalMinutes = (int)tmpVal;
if (totalMinutes < tmpVal)
throw new ArgumentException(SR.ReplicationIntervalInMinutes, nameof(value));
try
{
cachedEntry.Properties["replInterval"].Value = totalMinutes;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool ReciprocalReplicationEnabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int options = 0;
PropertyValueCollection propValue = null;
try
{
propValue = cachedEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count != 0)
{
options = (int)propValue[0];
}
//NTDSSITELINK_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync
if ((options & 0x2) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int options = 0;
PropertyValueCollection propValue = null;
try
{
propValue = cachedEntry.Properties["options"];
if (propValue.Count != 0)
{
options = (int)propValue[0];
}
//NTDSSITELINK_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync
if (value == true)
{
options |= 0x2;
}
else
{
options &= (~(0x2));
}
cachedEntry.Properties["options"].Value = options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool NotificationEnabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int options = 0;
PropertyValueCollection propValue = null;
try
{
propValue = cachedEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count != 0)
{
options = (int)propValue[0];
}
// NTDSSITELINK_OPT_USE_NOTIFY ( 1 << 0 ) Use notification on this link
if ((options & 0x1) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int options = 0;
PropertyValueCollection propValue = null;
try
{
propValue = cachedEntry.Properties["options"];
if (propValue.Count != 0)
{
options = (int)propValue[0];
}
// NTDSSITELINK_OPT_USE_NOTIFY ( 1 << 0 ) Use notification on this link
if (value)
{
options |= 0x1;
}
else
{
options &= (~(0x1));
}
cachedEntry.Properties["options"].Value = options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool DataCompressionEnabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int options = 0;
PropertyValueCollection propValue = null;
try
{
propValue = cachedEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count != 0)
{
options = (int)propValue[0];
}
//NTDSSITELINK_OPT_DISABLE_COMPRESSION ( 1 << 2 )
// 0 - Compression of replication data across this site link enabled
// 1 - Compression of replication data across this site link disabled
if ((options & 0x4) == 0)
return true;
else
return false;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int options = 0;
PropertyValueCollection propValue = null;
try
{
propValue = cachedEntry.Properties["options"];
if (propValue.Count != 0)
{
options = (int)propValue[0];
}
//NTDSSITELINK_OPT_DISABLE_COMPRESSION ( 1 << 2 )
// 0 - Compression of replication data across this site link enabled
// 1 - Compression of replication data across this site link disabled
if (value == false)
{
options |= 0x4;
}
else
{
options &= (~(0x4));
}
cachedEntry.Properties["options"].Value = options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public ActiveDirectorySchedule InterSiteReplicationSchedule
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
ActiveDirectorySchedule schedule = null;
try
{
if (cachedEntry.Properties.Contains("schedule"))
{
byte[] tmpSchedule = (byte[])cachedEntry.Properties["schedule"][0];
Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188);
schedule = new ActiveDirectorySchedule();
schedule.SetUnmanagedSchedule(tmpSchedule);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
return schedule;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
if (value == null)
{
if (cachedEntry.Properties.Contains("schedule"))
cachedEntry.Properties["schedule"].Clear();
}
else
{
cachedEntry.Properties["schedule"].Value = value.GetUnmanagedSchedule();
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public void Save()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
cachedEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (existing)
{
_siteRetrieved = false;
}
else
{
existing = true;
}
}
public void Delete()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existing)
{
throw new InvalidOperationException(SR.CannotDelete);
}
else
{
try
{
cachedEntry.Parent.Children.Remove(cachedEntry);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public override string ToString()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _name;
}
public DirectoryEntry GetDirectoryEntry()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existing)
{
throw new InvalidOperationException(SR.CannotGetObject);
}
else
{
return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedEntry.Path);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free other state (managed objects)
if (cachedEntry != null)
cachedEntry.Dispose();
}
// free your own state (unmanaged objects)
_disposed = true;
}
private static void ValidateArgument(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport)
{
// basic validation first
if (context == null)
throw new ArgumentNullException(nameof(context));
// if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context));
}
// more validation for the context, if the target is not null, then it should be either forest name or server name
if (context.Name != null)
{
if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet()))
throw new ArgumentException(SR.NotADOrADAM, nameof(context));
}
if (siteLinkName == null)
throw new ArgumentNullException(nameof(siteLinkName));
if (siteLinkName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteLinkName));
if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp)
throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType));
}
private void GetSites()
{
NativeComInterfaces.IAdsPathname pathCracker = null;
pathCracker = (NativeComInterfaces.IAdsPathname)new NativeComInterfaces.Pathname();
ArrayList propertyList = new ArrayList();
// need to turn off the escaping for name
pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX;
string propertyName = "siteList";
propertyList.Add(propertyName);
Hashtable values = Utils.GetValuesWithRangeRetrieval(cachedEntry, "(objectClass=*)", propertyList, SearchScope.Base);
ArrayList siteLists = (ArrayList)values[propertyName.ToLower(CultureInfo.InvariantCulture)];
// somehow no site list
if (siteLists == null)
return;
for (int i = 0; i < siteLists.Count; i++)
{
string dn = (string)siteLists[i];
// escaping manipulation
pathCracker.Set(dn, NativeComInterfaces.ADS_SETTYPE_DN);
string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF);
Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0);
rdn = rdn.Substring(3);
ActiveDirectorySite site = new ActiveDirectorySite(context, rdn, true);
// add to the collection
_sites.Add(site);
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Internal.Common
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
public class ConsoleApplicationStandardOutputEvents :
StandardOutputEvents,
ICommandParserOutputEvents
{
static protected ConsoleColor DefaultForegroundColor { get; private set; }
static protected bool SetCursorPostionSupported { get; private set;}
static public bool Verbose { get; set; }
protected TraceSource TraceSource { get; set; }
public int NumberOfErrors { get; private set; }
public int NumberOfWarnings { get; private set; }
public bool HasErrors { get { return NumberOfErrors > 0; } }
public bool HasWarnings { get { return NumberOfWarnings > 0; } }
protected ConsoleApplicationStandardOutputEvents()
{
}
public ConsoleApplicationStandardOutputEvents(TraceSource traceSource)
{
TraceSource = traceSource;
}
static ConsoleApplicationStandardOutputEvents()
{
if (Environment.GetEnvironmentVariable("_CSVERBOSE") != null)
{
Verbose = true;
}
DefaultForegroundColor = Console.ForegroundColor;
try
{
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop);
SetCursorPostionSupported = true;
}
catch (Exception)
{
SetCursorPostionSupported = false;
}
}
override public void LogWarning(int ecode, string fmt, params object[] args)
{
NumberOfWarnings++;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(fmt,args);
Console.ForegroundColor = DefaultForegroundColor;
if (TraceSource != null)
{
TraceSource.TraceEvent(TraceEventType.Warning, ecode, fmt, args);
}
}
override public void LogError(int ecode, string fmt, params object[] args)
{
NumberOfErrors++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(fmt, args);
Console.ForegroundColor = DefaultForegroundColor;
if (TraceSource != null)
{
TraceSource.TraceEvent(TraceEventType.Error, ecode, fmt, args);
}
}
override public void LogImportantMessage(int ecode, string fmt, params object[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(fmt, args);
Console.ForegroundColor = DefaultForegroundColor;
if (TraceSource != null)
{
TraceSource.TraceEvent(TraceEventType.Information, ecode, fmt, args);
}
}
override public void LogMessage(int ecode, string fmt, params object[] args)
{
Console.WriteLine(fmt, args);
if (TraceSource != null)
{
TraceSource.TraceEvent(TraceEventType.Information, ecode, fmt, args);
}
}
override public void LogDebug(string fmt, params object[] args)
{
if (Verbose)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(fmt, args);
Console.ForegroundColor = DefaultForegroundColor;
}
if (TraceSource != null)
{
TraceSource.TraceEvent(TraceEventType.Verbose, 0, fmt, args);
}
}
override public void LogProgress(string fmt, params object[] args)
{
if (SetCursorPostionSupported)
{
int lineWidth = Console.BufferWidth;
var emptyLine = new String(' ', lineWidth);
Console.Write(emptyLine);
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.WriteLine(fmt, args);
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
else
{
Console.WriteLine(fmt, args);
}
}
public void ShowBanner(string title,string version)
{
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(
System.Reflection.Assembly.GetExecutingAssembly().Location);
if (version == null)
version = versionInfo.FileVersion;
LogMessage("Windows(R) Azure(TM) {0} version {1}",title, version );
LogMessage("for Microsoft(R) .NET Framework 3.5");
LogMessage(versionInfo.LegalCopyright);
LogMessage("");
}
public void CommandUnknown(string commandName)
{
LogError("Command {0} is unknown.", commandName);
}
public void CommandTooManyArguments(string commandName, int expected, int found, IEnumerable<string> args)
{
var fmtArgs = "'" + string.Join("', '",args.ToArray()) + "'";
LogError("Too many arguments for command {0} expects {1} argument(s) found {2}.\nFound: {3}",
commandName,
expected,
found,
fmtArgs);
}
public void CommandTooFewArguments(string commandName, int expected, int found, IEnumerable<string> args)
{
var fmtArgs = "'" + string.Join("', '", args.ToArray()) + "'";
LogError("Too few arguments for command {0} expects {1} argument(s) found {2}.\nFound: {3}",
commandName,
expected,
found,
fmtArgs);
}
public void CommandParamUnknown(string commandName, string switchName)
{
LogError("Named parameter \"{0}\" for command {1} is unknown.", switchName, commandName);
}
public void CommandMissingParam(string commandName, string switchUsage)
{
LogError("Named parameter \"{0}\" missing for command {1}.", switchUsage, commandName);
}
public void CommandMissing()
{
LogError("No command specified.");
}
public void CommandParamMissingArgument(string commandName, string switchUsage)
{
LogError("Parameter \"{0}\" for command {1} is required.",
switchUsage, commandName);
}
public void CommandUsage(CommandDefinition commandDefiniton, Func<SwitchDefinition,string> switchUsage)
{
var indent = " ";
var switchSyntax =
from sw in commandDefiniton.Switches.Values
orderby sw.Name
where sw.Undocumented == false
select switchUsage(sw);
LogMessage("NAME");
LogMessage(indent + commandDefiniton.Name);
LogMessage("");
if(commandDefiniton.Category != CommandCategory.None)
{
LogMessage("CATEGORY");
LogMessage(indent + commandDefiniton.Category);
LogMessage("");
}
LogMessage("SYNOPSIS");
LogMessage(indent + commandDefiniton.Description);
LogMessage("");
LogMessage("SYNTAX");
LogMessage(indent + commandDefiniton.Name + " " + String.Join(" ", switchSyntax.ToArray()));
LogMessage("");
}
public void CommandDeprecated(CommandDefinition old, CommandDefinition newCmd)
{
LogWarning("The command {0} is deprecated. Please use the command {1} instead.", old.Name, newCmd.Name);
}
public void Format(IEnumerable<CommandDefinition> commands)
{
if (commands.All(cd => cd.Category == CommandCategory.None))
{
var fmt = new ListOutputFormatter(this, "Name", "Synopsis");
var records = from cmddef in commands
orderby cmddef.Name
select fmt.MakeRecord(cmddef.Name, cmddef.Description);
fmt.OutputRecords(records);
}
else
{
var fmt = new ListOutputFormatter(this, "Name", "Category", "Synopsis");
var records = from cmddef in commands
orderby cmddef.Category, cmddef.Name
select fmt.MakeRecord(cmddef.Name, cmddef.Category, cmddef.Description);
fmt.OutputRecords(records);
}
}
public void CommandDuplicateParam(string switchUsage)
{
LogWarning("Duplicate named parameter: {0}", switchUsage);
}
public void DebugCommandLine(string[] args)
{
int i = 0;
foreach (var arg in args)
{
int argnum = i++;
LogDebug("arg[{0}]=\"{1}\"", argnum, arg);
string[] charCodes = arg.ToCharArray().Select(c => String.Format("{0}", (int)c)).ToArray();
LogDebug("arg[{0}]={{ {1} }}", argnum, String.Join(", ", charCodes));
}
}
}
}
| |
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Firebase.Database.Internal;
namespace Firebase.Database {
/// <summary>
/// The Query class (and its subclass,
/// <see cref="DatabaseReference" />
/// ) are used for reading data.
/// Listeners are attached, and they will be triggered when the corresponding data changes.
/// <br /><br />
/// Instances of Query are obtained by calling StartAt(), EndAt(), or Limit() on a
/// DatabaseReference.
/// </summary>
public class Query {
private readonly InternalQuery internalQuery;
// The query only keeps a reference to the database to ensure that it's kept alive,
// as the underlying C++ code needs that.
private readonly FirebaseDatabase database;
private readonly InternalValueListener valueListener;
private readonly InternalChildListener childListener;
internal Query(InternalQuery internalQuery, FirebaseDatabase database) {
if (!internalQuery.is_valid()) {
// This is a bit awkward - if misused, the C++ SDK simply returns an invalid Query and
// *logs* the error. Which means that we can't access the cause of the error and have
// to refer the user to the log.
// Also, we throw an ArgumentException, instead of a DatabaseException, because that's
// what the old C# implementation did.
throw new ArgumentException("Resulting query is invalid, please check error log for details");
}
this.internalQuery = internalQuery;
this.database = database;
valueListener = new InternalValueListener(internalQuery, database);
childListener = new InternalChildListener(internalQuery, database);
}
/// <summary>Event for changes in the data at this location.</summary>
/// <remarks>
/// Register a handler to observe changes at the location of this Query object.
/// Each time time the data changes, your handler will be called with an
/// immutable snapshot of the data.
/// </remarks>
public event EventHandler<ValueChangedEventArgs> ValueChanged {
add { valueListener.ValueChanged += value; }
remove { valueListener.ValueChanged -= value; }
}
/// <summary>Event raised when children nodes are added relative to this location.</summary>
/// <remarks>
/// Register a handler to observe when children are added relative to this Query object.
/// Each time time children nodes are added, your handler will be called with an
/// immutable snapshot of the data.
/// </remarks>
public event EventHandler<ChildChangedEventArgs> ChildAdded {
add { childListener.ChildAdded += value; }
remove { childListener.ChildAdded -= value; }
}
/// <summary>Event raised when children nodes are changed relative to this location.</summary>
/// <remarks>
/// Register a handler to observe changes to children relative to this Query object.
/// Each time time children nodes are changed, your handler will be called with an
/// immutable snapshot of the data.
/// </remarks>
public event EventHandler<ChildChangedEventArgs> ChildChanged {
add { childListener.ChildChanged += value; }
remove { childListener.ChildChanged -= value; }
}
/// <summary>Event raised when children nodes are removed relative to this location.</summary>
/// <remarks>
/// Register a handler to observe when children are removed relative to this Query object.
/// Each time time children nodes are removed, your handler will be called with an
/// immutable snapshot of the data.
/// </remarks>
public event EventHandler<ChildChangedEventArgs> ChildRemoved {
add { childListener.ChildRemoved += value; }
remove { childListener.ChildRemoved -= value; }
}
/// <summary>Event raised when children nodes are moved relative to this location.</summary>
/// <remarks>
/// Register a handler to observe when children are moved relative to this Query object.
/// Each time time children nodes are moved, your handler will be called with an
/// immutable snapshot of the data.
/// </remarks>
public event EventHandler<ChildChangedEventArgs> ChildMoved {
add { childListener.ChildMoved += value; }
remove { childListener.ChildMoved -= value; }
}
/// Check if the task is faulted or canceled.
/// This also keeps a reference to FirebaseDatabase (through Query) and prevents it from being
/// Garbage-Collected until the task is done.
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
internal bool CheckTaskStatus<TResult>(Task task, TaskCompletionSource<TResult> tcs) {
if (task.IsFaulted) {
tcs.SetException(new DatabaseException("Internal task faulted", task.Exception));
return false;
} else if (task.IsCanceled) {
tcs.SetCanceled();
return false;
} else if (!task.IsCompleted) {
// This should not happen - ContinueWith(), the block where this should be called from,
// should not have been called if the task is neither faulted, canceled nor completed.
tcs.SetException(new DatabaseException("Unexpected internal task state"));
return false;
}
return true;
}
/// Creates a wrapper around the internal task returned by the SWIG classes.
internal Task<DataSnapshot> WrapInternalDataSnapshotTask(Task<InternalDataSnapshot> it) {
TaskCompletionSource<DataSnapshot> tcs = new TaskCompletionSource<DataSnapshot>();
it.ContinueWith(task => {
// By calling CheckTaskStatus(), it keeps a reference to this, which holds a reference to
// FirebaseDatabase. This prevents FirebaseDatabase from being GCed until the end of this
// block.
if (CheckTaskStatus<DataSnapshot>(task, tcs)){
tcs.SetResult(DataSnapshot.CreateSnapshot(task.Result, database));
}
});
return tcs.Task;
}
public Task<DataSnapshot> GetValueAsync() {
return WrapInternalDataSnapshotTask(internalQuery.GetValueAsync());
}
/// <summary>
/// By calling `keepSynced(true)` on a location, the data for that location will automatically
/// be downloaded and kept in sync, even when no listeners are attached for that location.
/// </summary>
/// <remarks>
/// By calling `keepSynced(true)` on a location, the data for that location will automatically
/// be downloaded and kept in sync, even when no listeners are attached for that location.
/// </remarks>
/// <param name="keepSynced">
/// Pass `true` to keep this location synchronized, pass `false` to stop synchronization.
/// </param>
public void KeepSynced(bool keepSynced) {
internalQuery.SetKeepSynchronized(keepSynced);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value greater than or equal
/// to the given value, using the given orderBy directive or priority as default.
/// </summary>
/// <param name="value">The value to start at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query StartAt(string value) {
return new Query(internalQuery.StartAt(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value greater than or equal
/// to the given value, using the given orderBy directive or priority as default.
/// </summary>
/// <param name="value">The value to start at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query StartAt(double value) {
return new Query(internalQuery.StartAt(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value greater than or equal
/// to the given value, using the given orderBy directive or priority as default.
/// </summary>
/// <param name="value">The value to start at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query StartAt(bool value) {
return new Query(internalQuery.StartAt(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value greater than or equal
/// to the given value, using the given orderBy directive or priority as default, and
/// additionally only child nodes with a key greater than or equal to the given key.
/// </summary>
/// <remark>
/// <b>Known issue</b> This currently does not work properly on all platforms. Please use
/// StartAt(string value) instead.
/// </remark>
/// <param name="value">The priority to start at, inclusive</param>
/// <param name="key">The key to start at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query StartAt(string value, string key) {
return new Query(internalQuery.StartAt(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value greater than or equal
/// to the given value, using the given orderBy directive or priority as default, and
/// additionally only child nodes with a key greater than or equal to the given key.
/// </summary>
/// <remark>
/// <b>Known issue</b> This currently does not work properly on all platforms. Please use
/// StartAt(double value) instead.
/// </remark>
/// <param name="value">The priority to start at, inclusive</param>
/// <param name="key">The key name to start at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query StartAt(double value, string key) {
return new Query(internalQuery.StartAt(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value greater than or equal
/// to the given value, using the given orderBy directive or priority as default, and
/// additionally only child nodes with a key greater than or equal to the given key.
/// </summary>
/// <remark>
/// <b>Known issue</b> This currently does not work properly on all platforms. Please use
/// StartAt(bool value) instead.
/// </remark>
/// <param name="value">The priority to start at, inclusive</param>
/// <param name="key">The key to start at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query StartAt(bool value, string key) {
return new Query(internalQuery.StartAt(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value less than or equal to
/// the given value, using the given orderBy directive or priority as default.
/// </summary>
/// <param name="value">The value to end at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query EndAt(string value) {
return new Query(internalQuery.EndAt(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value less than or equal to
/// the given value, using the given orderBy directive or priority as default.
/// </summary>
/// <param name="value">The value to end at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query EndAt(double value) {
return new Query(internalQuery.EndAt(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value less than or equal to
/// the given value, using the given orderBy directive or priority as default.
/// </summary>
/// <param name="value">The value to end at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query EndAt(bool value) {
return new Query(internalQuery.EndAt(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value less than or equal to
/// the given value, using the given orderBy directive or priority as default, and
/// additionally only child nodes with a key key less than or equal to the given key.
/// </summary>
/// <remark>
/// <b>Known issue</b> This currently does not work properly on all platforms. Please use
/// EndAt(string value) instead.
/// </remark>
/// <param name="value">The value to end at, inclusive</param>
/// <param name="key">The key to end at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query EndAt(string value, string key) {
return new Query(internalQuery.EndAt(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value less than or equal to
/// the given value, using the given orderBy directive or priority as default, and
/// additionally only child nodes with a key less than or equal to the given key.
/// </summary>
/// <remark>
/// <b>Known issue</b> This currently does not work properly on all platforms. Please use
/// EndAt(double value) instead.
/// </remark>
/// <param name="value">The value to end at, inclusive</param>
/// <param name="key">The key to end at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query EndAt(double value, string key) {
return new Query(internalQuery.EndAt(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with a value less than or equal to
/// the given value, using the given orderBy directive or priority as default, and
/// additionally only child nodes with a key less than or equal to the given key.
/// </summary>
/// <remark>
/// <b>Known issue</b> This currently does not work properly on all platforms. Please use
/// EndAt(bool value) instead.
/// </remark>
/// <param name="value">The value to end at, inclusive</param>
/// <param name="key">The key to end at, inclusive</param>
/// <returns>A Query with the new constraint</returns>
public Query EndAt(bool value, string key) {
return new Query(internalQuery.EndAt(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with the given value
/// </summary>
/// <param name="value">The value to query for</param>
/// <returns>A query with the new constraint</returns>
public Query EqualTo(string value) {
return new Query(internalQuery.EqualTo(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with the given value
/// </summary>
/// <param name="value">The value to query for</param>
/// <returns>A query with the new constraint</returns>
public Query EqualTo(double value) {
return new Query(internalQuery.EqualTo(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return child nodes with the given value.
/// </summary>
/// <param name="value">The value to query for</param>
/// <returns>A query with the new constraint</returns>
public Query EqualTo(bool value) {
return new Query(internalQuery.EqualTo(Utilities.MakeVariant(value)), database);
}
/// <summary>
/// Create a query constrained to only return the child node with the given key and value.
/// </summary>
/// <remarks>
/// Create a query constrained to only return the child node with the given key and value.
/// Note that there is at most one such child as names are unique. <br />
/// <br />
/// <b>Known issue</b> This currently does not work properly on iOS. Please use
/// EqualTo(string value) instead.
/// </remarks>
/// <param name="value">The value to query for</param>
/// <param name="key">The key of the child</param>
/// <returns>A query with the new constraint</returns>
public Query EqualTo(string value, string key) {
return new Query(internalQuery.EqualTo(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return the child node with the given key and value.
/// </summary>
/// <remarks>
/// Create a query constrained to only return the child node with the given key and value.
/// Note that there is at most one such child as keys are unique. <br />
/// <br />
/// <b>Known issue</b> This currently does not work properly on iOS. Please use
/// EqualTo(double value) instead.
/// </remarks>
/// <param name="value">The value to query for</param>
/// <param name="key">The key of the child</param>
/// <returns>A query with the new constraint</returns>
public Query EqualTo(double value, string key) {
return new Query(internalQuery.EqualTo(Utilities.MakeVariant(value), key), database);
}
/// <summary>
/// Create a query constrained to only return the child node with the given key and value.
/// </summary>
/// <remarks>
/// Create a query constrained to only return the child node with the given key and value.
/// Note that there is at most one such child as keys are unique. <br />
/// <br />
/// <b>Known issue</b> This currently does not work properly on iOS. Please use
/// EqualTo(bool value) instead.
/// </remarks>
/// <param name="value">The value to query for</param>
/// <param name="key">The name of the child</param>
/// <returns>A query with the new constraint</returns>
public Query EqualTo(bool value, string key) {
return new Query(internalQuery.EqualTo(Utilities.MakeVariant(value), key), database);
}
/// <summary>Create a query with limit and anchor it to the start of the window</summary>
/// <param name="limit">The maximum number of child nodes to return</param>
/// <returns>A Query with the new constraint</returns>
public Query LimitToFirst(int limit) {
return new Query(internalQuery.LimitToFirst(checked((uint)limit)), database);
}
/// <summary>Create a query with limit and anchor it to the end of the window</summary>
/// <param name="limit">The maximum number of child nodes to return</param>
/// <returns>A Query with the new constraint</returns>
public Query LimitToLast(int limit) {
return new Query(internalQuery.LimitToLast(checked((uint)limit)), database);
}
/// <summary>
/// Create a query in which child nodes are ordered by the values of the specified path.
/// </summary>
/// <param name="path">The path to the child node to use for sorting</param>
/// <returns>A Query with the new constraint</returns>
public Query OrderByChild(string path) {
return new Query(internalQuery.OrderByChild(path), database);
}
/// <summary>Create a query in which child nodes are ordered by their priorities.</summary>
/// <returns>A Query with the new constraint</returns>
public Query OrderByPriority() {
return new Query(internalQuery.OrderByPriority(), database);
}
/// <summary>Create a query in which child nodes are ordered by their keys.</summary>
/// <returns>A Query with the new constraint</returns>
public Query OrderByKey() {
return new Query(internalQuery.OrderByKey(), database);
}
/// <summary>Create a query in which nodes are ordered by their value</summary>
/// <returns>A Query with the new constraint</returns>
public Query OrderByValue() {
return new Query(internalQuery.OrderByValue(), database);
}
/// <value>A DatabaseReference to this location</value>
public DatabaseReference Reference {
get { return new DatabaseReference(internalQuery.GetReference(), database); }
}
}
}
| |
using Prism.Windows.AppModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
namespace Prism.Windows.Navigation
{
/// <summary>
/// The <see cref="FrameNavigationService"/> interface is used for navigating across the pages of your Windows Store app.
/// The <see cref="FrameNavigationService"/> class, uses a class that implements the <see cref="IFrameFacade"/> interface to provide page navigation.
/// </summary>
public class FrameNavigationService : INavigationService
{
private const string LastNavigationParameterKey = "LastNavigationParameter";
private const string LastNavigationPageKey = "LastNavigationPageKey";
private readonly IFrameFacade _frame;
private readonly Func<string, Type> _navigationResolver;
private readonly ISessionStateService _sessionStateService;
/// <summary>
/// Initializes a new instance of the <see cref="FrameNavigationService"/> class.
/// </summary>
/// <param name="frame">The frame.</param>
/// <param name="navigationResolver">The navigation resolver.</param>
/// <param name="sessionStateService">The session state service.</param>
public FrameNavigationService(IFrameFacade frame, Func<string, Type> navigationResolver, ISessionStateService sessionStateService)
{
_frame = frame;
_navigationResolver = navigationResolver;
_sessionStateService = sessionStateService;
if (frame != null)
{
_frame.NavigatingFrom += OnFrameNavigatingFrom;
_frame.NavigatedTo += OnFrameNavigatedTo;
}
}
/// <summary>
/// Navigates to the page with the specified page token, passing the specified parameter.
/// </summary>
/// <param name="pageToken">The page token.</param>
/// <param name="parameter">The parameter.</param>
/// <returns>Returns <c>true</c> if the navigation succeeds: otherwise, <c>false</c>.</returns>
public bool Navigate(string pageToken, object parameter)
{
Type pageType = _navigationResolver(pageToken);
if (pageType == null)
{
var resourceLoader = ResourceLoader.GetForCurrentView(Constants.InfrastructureResourceMapId);
var error = string.Format(CultureInfo.CurrentCulture, resourceLoader.GetString("FrameNavigationServiceUnableResolveMessage"), pageToken);
throw new ArgumentException(error, nameof(pageToken));
}
// Get the page type and parameter of the last navigation to check if we
// are trying to navigate to the exact same page that we are currently on
var lastNavigationParameter = _sessionStateService.SessionState.ContainsKey(LastNavigationParameterKey) ? _sessionStateService.SessionState[LastNavigationParameterKey] : null;
var lastPageTypeFullName = _sessionStateService.SessionState.ContainsKey(LastNavigationPageKey) ? _sessionStateService.SessionState[LastNavigationPageKey] as string : string.Empty;
if (lastPageTypeFullName != pageType.FullName || !AreEquals(lastNavigationParameter, parameter))
{
return _frame.Navigate(pageType, parameter);
}
return false;
}
/// <summary>
/// Goes to the previous page in the navigation stack.
/// </summary>
public void GoBack()
{
_frame.GoBack();
}
/// <summary>
/// Determines whether the navigation service can navigate to the previous page or not.
/// </summary>
/// <returns>
/// <c>true</c> if the navigation service can go back; otherwise, <c>false</c>.
/// </returns>
public bool CanGoBack()
{
return _frame.CanGoBack;
}
/// <summary>
/// Goes to the next page in the navigation stack.
/// </summary>
public void GoForward()
{
_frame.GoForward();
}
/// <summary>
/// Determines whether the navigation service can navigate to the next page or not.
/// </summary>
/// <returns>
/// <c>true</c> if the navigation service can go forward; otherwise, <c>false</c>.
/// </returns>
public bool CanGoForward()
{
return _frame.CanGoForward();
}
/// <summary>
/// Clears the navigation history.
/// </summary>
public void ClearHistory()
{
_frame.SetNavigationState("1,0");
}
/// <summary>
/// Remove the first page of the backstack with optional pageToken and parameter
/// </summary>
/// <param name="pageToken"></param>
/// <param name="parameter"></param>
public void RemoveFirstPage(string pageToken = null, object parameter = null)
{
PageStackEntry page;
if (pageToken != null)
{
var pageType = _navigationResolver(pageToken);
if (parameter != null)
{
page = _frame.BackStack.FirstOrDefault(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter));
}
else
{
page = _frame.BackStack.FirstOrDefault(x => x.SourcePageType == pageType);
}
}
else
{
page = _frame.BackStack.FirstOrDefault();
}
if (page != null)
{
_frame.RemoveBackStackEntry(page);
}
}
/// <summary>
/// Remove the last page of the backstack with optional pageToken and parameter
/// </summary>
/// <param name="pageToken"></param>
/// <param name="parameter"></param>
public void RemoveLastPage(string pageToken = null, object parameter = null)
{
PageStackEntry page;
if (pageToken != null)
{
var pageType = _navigationResolver(pageToken);
if (parameter != null)
{
page = _frame.BackStack.LastOrDefault(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter));
}
else
{
page = _frame.BackStack.LastOrDefault(x => x.SourcePageType == pageType);
}
}
else
{
page = _frame.BackStack.LastOrDefault();
}
if (page != null)
{
_frame.RemoveBackStackEntry(page);
}
}
/// <summary>
/// Remove the all pages of the backstack with optional pageToken and parameter
/// </summary>
/// <param name="pageToken"></param>
/// <param name="parameter"></param>
public void RemoveAllPages(string pageToken = null, object parameter = null)
{
if (pageToken != null)
{
IEnumerable<PageStackEntry> pages;
var pageType = _navigationResolver(pageToken);
if (parameter != null)
{
pages = _frame.BackStack.Where(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter));
}
else
{
pages = _frame.BackStack.Where(x => x.SourcePageType == pageType);
}
foreach (var page in pages)
{
_frame.RemoveBackStackEntry(page);
}
}
else
{
_frame.ClearBackStack();
}
}
/// <summary>
/// Restores the saved navigation.
/// </summary>
public void RestoreSavedNavigation()
{
NavigateToCurrentViewModel(new NavigatedToEventArgs()
{
NavigationMode = NavigationMode.Refresh,
Parameter = _sessionStateService.SessionState[LastNavigationParameterKey]
});
}
/// <summary>
/// Used for navigating away from the current view model due to a suspension event, in this way you can execute additional logic to handle suspensions.
/// </summary>
public void Suspending()
{
NavigateFromCurrentViewModel(new NavigatingFromEventArgs(), true);
}
/// <summary>
/// This method is triggered after navigating to a view model. It is used to load the view model state that was saved previously.
/// </summary>
/// <param name="e">The <see cref="NavigatedToEventArgs"/> instance containing the event data.</param>
private void NavigateToCurrentViewModel(NavigatedToEventArgs e)
{
var frameState = _sessionStateService.GetSessionStateForFrame(_frame);
var viewModelKey = "ViewModel-" + _frame.BackStackDepth;
if (e.NavigationMode == NavigationMode.New)
{
// Clear existing state for forward navigation when adding a new page/view model to the
// navigation stack
var nextViewModelKey = viewModelKey;
int nextViewModelIndex = _frame.BackStackDepth;
while (frameState.Remove(nextViewModelKey))
{
nextViewModelIndex++;
nextViewModelKey = "ViewModel-" + nextViewModelIndex;
}
}
var newView = _frame.Content as FrameworkElement;
if (newView == null) return;
var newViewModel = newView.DataContext as INavigationAware;
if (newViewModel != null)
{
Dictionary<string, object> viewModelState;
if (frameState.ContainsKey(viewModelKey))
{
viewModelState = frameState[viewModelKey] as Dictionary<string, object>;
}
else
{
viewModelState = new Dictionary<string, object>();
}
newViewModel.OnNavigatedTo(e, viewModelState);
frameState[viewModelKey] = viewModelState;
}
}
/// <summary>
/// Navigates away from the current viewmodel.
/// </summary>
/// <param name="e">The <see cref="NavigatingFromEventArgs"/> instance containing the event data.</param>
/// <param name="suspending">True if it is navigating away from the viewmodel due to a suspend event.</param>
private void NavigateFromCurrentViewModel(NavigatingFromEventArgs e, bool suspending)
{
var departingView = _frame.Content as FrameworkElement;
if (departingView == null) return;
var frameState = _sessionStateService.GetSessionStateForFrame(_frame);
var departingViewModel = departingView.DataContext as INavigationAware;
var viewModelKey = "ViewModel-" + _frame.BackStackDepth;
if (departingViewModel != null)
{
var viewModelState = frameState.ContainsKey(viewModelKey)
? frameState[viewModelKey] as Dictionary<string, object>
: null;
departingViewModel.OnNavigatingFrom(e, viewModelState, suspending);
}
}
/// <summary>
/// Handles the Navigating event of the Frame control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="NavigatingFromEventArgs"/> instance containing the event data.</param>
private void OnFrameNavigatingFrom(object sender, NavigatingFromEventArgs e)
{
NavigateFromCurrentViewModel(e, false);
}
/// <summary>
/// Handles the Navigated event of the Frame control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="NavigatedToEventArgs"/> instance containing the event data.</param>
private void OnFrameNavigatedTo(object sender, NavigatedToEventArgs e)
{
// Update the page type and parameter of the last navigation
_sessionStateService.SessionState[LastNavigationPageKey] = _frame.Content.GetType().FullName;
_sessionStateService.SessionState[LastNavigationParameterKey] = e.Parameter;
NavigateToCurrentViewModel(e);
}
/// <summary>
/// Returns <c>true</c> if both objects are equal. Two objects are equal if they are null or the same string object.
/// </summary>
/// <param name="obj1">First object to compare.</param>
/// <param name="obj2">Second object to compare.</param>
/// <returns>Returns <c>true</c> if both parameters are equal; otherwise, <c>false</c>.</returns>
private static bool AreEquals(object obj1, object obj2)
{
if (obj1 != null)
{
return obj1.Equals(obj2);
}
return obj2 == null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.Web.Models;
namespace Umbraco.Tests.PublishedContent
{
/// <summary>
/// Tests the methods on IPublishedContent using the DefaultPublishedContentStore
/// </summary>
[TestFixture]
public class PublishedContentTests : PublishedContentTestBase
{
private PluginManager _pluginManager;
public override void Initialize()
{
// required so we can access property.Value
//PropertyValueConvertersResolver.Current = new PropertyValueConvertersResolver();
base.Initialize();
// this is so the model factory looks into the test assembly
_pluginManager = PluginManager.Current;
PluginManager.Current = new PluginManager(new ActivatorServiceProvider(), CacheHelper.RuntimeCache, ProfilingLogger, false)
{
AssembliesToScan = _pluginManager.AssembliesToScan
.Union(new[] { typeof(PublishedContentTests).Assembly })
};
// need to specify a custom callback for unit tests
// AutoPublishedContentTypes generates properties automatically
// when they are requested, but we must declare those that we
// explicitely want to be here...
var propertyTypes = new[]
{
// AutoPublishedContentType will auto-generate other properties
new PublishedPropertyType("umbracoNaviHide", 0, Constants.PropertyEditors.TrueFalseAlias),
new PublishedPropertyType("selectedNodes", 0, "?"),
new PublishedPropertyType("umbracoUrlAlias", 0, "?"),
new PublishedPropertyType("content", 0, Constants.PropertyEditors.TinyMCEAlias),
new PublishedPropertyType("testRecursive", 0, "?"),
};
var compositionAliases = new[] { "MyCompositionAlias" };
var type = new AutoPublishedContentType(0, "anything", "anything", "anything", compositionAliases, propertyTypes);
PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
}
public override void TearDown()
{
PluginManager.Current = _pluginManager;
ApplicationContext.Current.DisposeIfDisposable();
ApplicationContext.Current = null;
}
protected override void FreezeResolution()
{
var types = PluginManager.Current.ResolveTypes<PublishedContentModel>();
PublishedContentModelFactoryResolver.Current = new PublishedContentModelFactoryResolver(
new PublishedContentModelFactory(types));
base.FreezeResolution();
}
protected override string GetXmlContent(int templateId)
{
return @"<?xml version=""1.0"" encoding=""utf-8""?>
<!DOCTYPE root[
<!ELEMENT Home ANY>
<!ATTLIST Home id ID #REQUIRED>
<!ELEMENT CustomDocument ANY>
<!ATTLIST CustomDocument id ID #REQUIRED>
]>
<root id=""-1"">
<Home id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" isDoc="""">
<content><![CDATA[]]></content>
<umbracoUrlAlias><![CDATA[this/is/my/alias, anotheralias]]></umbracoUrlAlias>
<umbracoNaviHide>1</umbracoNaviHide>
<testRecursive><![CDATA[This is the recursive val]]></testRecursive>
<Home id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" isDoc="""">
<content><![CDATA[<div>This is some content</div>]]></content>
<umbracoUrlAlias><![CDATA[page2/alias, 2ndpagealias]]></umbracoUrlAlias>
<testRecursive><![CDATA[]]></testRecursive>
<Home id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" isDoc="""">
<content><![CDATA[]]></content>
<umbracoUrlAlias><![CDATA[only/one/alias]]></umbracoUrlAlias>
<creatorName><![CDATA[Custom data with same property name as the member name]]></creatorName>
<testRecursive><![CDATA[]]></testRecursive>
</Home>
<CustomDocument id=""117"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2018-07-18T10:06:37"" updateDate=""2018-07-18T10:06:37"" nodeName=""custom sub 1"" urlName=""custom-sub-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,117"" isDoc="""" />
<CustomDocument id=""1177"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""custom sub 1"" urlName=""custom-sub-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1177"" isDoc="""" />
<CustomDocument id=""1178"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 2"" urlName=""custom-sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1178"" isDoc="""">
<CustomDocument id=""1179"" parentID=""1178"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""custom sub sub 1"" urlName=""custom-sub-sub-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1178,1179"" isDoc="""" />
</CustomDocument>
<Home id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""5"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" isDoc="""" key=""CDB83BBC-A83B-4BA6-93B8-AADEF67D3C09"">
<content><![CDATA[]]></content>
<umbracoNaviHide>1</umbracoNaviHide>
</Home>
</Home>
<Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content>
</Home>
<CustomDocument id=""4444"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,4444"" isDoc="""">
<selectedNodes><![CDATA[1172,1176,1173]]></selectedNodes>
</CustomDocument>
</Home>
<CustomDocument id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" isDoc="""" />
</root>";
}
internal IPublishedContent GetNode(int id)
{
var ctx = GetUmbracoContext("/test", 1234);
var doc = ctx.ContentCache.GetById(id);
Assert.IsNotNull(doc);
return doc;
}
[Test]
[Ignore("IPublishedContent currently (6.1 as of april 25, 2013) has bugs")]
public void Fails()
{
var content = GetNode(1173);
var c1 = content.Children.First(x => x.Id == 1177);
Assert.IsFalse(c1.IsFirst());
var c2 = content.Children.Where(x => x.DocumentTypeAlias == "CustomDocument").First(x => x.Id == 1177);
Assert.IsTrue(c2.IsFirst());
// First is not implemented
var c2a = content.Children.First(x => x.DocumentTypeAlias == "CustomDocument" && x.Id == 1177);
Assert.IsTrue(c2a.IsFirst()); // so here it's luck
c1 = content.Children.First(x => x.Id == 1177);
Assert.IsFalse(c1.IsFirst()); // and here it fails
// but even using supported (where) method...
// do not replace by First(x => ...) here since it's not supported at the moment
c1 = content.Children.Where(x => x.Id == 1177).First();
c2 = content.Children.Where(x => x.DocumentTypeAlias == "CustomDocument" && x.Id == 1177).First();
Assert.IsFalse(c1.IsFirst()); // here it fails because c2 has corrupted it
// so there's only 1 IPublishedContent instance
// which keeps changing collection, ie being modified
// which is *bad* from a cache point of vue
// and from a consistency point of vue...
// => we want clones!
}
[Test]
public void Is_Last_From_Where_Filter_Dynamic_Linq()
{
var doc = GetNode(1173);
var items = doc.Children.Where("Visible").ToContentSet();
foreach (var item in items)
{
if (item.Id != 1178)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Is_Last_From_Where_Filter()
{
var doc = GetNode(1173);
var items = doc
.Children
.Where(x => x.IsVisible())
.ToContentSet();
Assert.AreEqual(4, items.Count());
foreach (var d in items)
{
switch (d.Id)
{
case 1174:
Assert.IsTrue(d.IsFirst());
Assert.IsFalse(d.IsLast());
break;
case 117:
Assert.IsFalse(d.IsFirst());
Assert.IsFalse(d.IsLast());
break;
case 1177:
Assert.IsFalse(d.IsFirst());
Assert.IsFalse(d.IsLast());
break;
case 1178:
Assert.IsFalse(d.IsFirst());
Assert.IsTrue(d.IsLast());
break;
default:
Assert.Fail("Invalid id.");
break;
}
}
}
[PublishedContentModel("Home")]
internal class Home : PublishedContentModel
{
public Home(IPublishedContent content)
: base(content)
{ }
}
[Test]
[Ignore("Fails as long as PublishedContentModel is internal.")] // fixme
public void Is_Last_From_Where_Filter2()
{
var doc = GetNode(1173);
var items = doc.Children
.Select(x => x.CreateModel()) // linq, returns IEnumerable<IPublishedContent>
// only way around this is to make sure every IEnumerable<T> extension
// explicitely returns a PublishedContentSet, not an IEnumerable<T>
.OfType<Home>() // ours, return IEnumerable<Home> (actually a PublishedContentSet<Home>)
.Where(x => x.IsVisible()) // so, here it's linq again :-(
.ToContentSet() // so, we need that one for the test to pass
.ToArray();
Assert.AreEqual(1, items.Count());
foreach (var d in items)
{
switch (d.Id)
{
case 1174:
Assert.IsTrue(d.IsFirst());
Assert.IsTrue(d.IsLast());
break;
default:
Assert.Fail("Invalid id.");
break;
}
}
}
[Test]
public void Is_Last_From_Take()
{
var doc = GetNode(1173);
var items = doc.Children.Take(4).ToContentSet();
foreach (var item in items)
{
if (item.Id != 1178)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Is_Last_From_Skip()
{
var doc = GetNode(1173);
foreach (var d in doc.Children.Skip(1))
{
if (d.Id != 1176)
{
Assert.IsFalse(d.IsLast());
}
else
{
Assert.IsTrue(d.IsLast());
}
}
}
[Test]
public void Is_Last_From_Concat()
{
var doc = GetNode(1173);
var items = doc.Children
.Concat(new[] { GetNode(1175), GetNode(4444) })
.ToContentSet();
foreach (var item in items)
{
if (item.Id != 4444)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Descendants_Ordered_Properly()
{
var doc = GetNode(1046);
var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 };
var exindex = 0;
// must respect the XPath descendants-or-self axis!
foreach (var d in doc.DescendantsOrSelf())
Assert.AreEqual(expected[exindex++], d.Id);
}
[Test]
public void Test_Get_Recursive_Val()
{
var doc = GetNode(1174);
var rVal = doc.GetRecursiveValue("testRecursive");
var nullVal = doc.GetRecursiveValue("DoNotFindThis");
Assert.AreEqual("This is the recursive val", rVal);
Assert.AreEqual("", nullVal);
}
[Test]
public void Get_Property_Value_Uses_Converter()
{
var doc = GetNode(1173);
var propVal = doc.GetPropertyValue("content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal);
Assert.AreEqual("<div>This is some content</div>", propVal.ToString());
var propVal2 = doc.GetPropertyValue<IHtmlString>("content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal2);
Assert.AreEqual("<div>This is some content</div>", propVal2.ToString());
var propVal3 = doc.GetPropertyValue("Content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal3);
Assert.AreEqual("<div>This is some content</div>", propVal3.ToString());
}
[Test]
public void Complex_Linq()
{
var doc = GetNode(1173);
var result = doc.Ancestors().OrderBy(x => x.Level)
.Single()
.Descendants()
.FirstOrDefault(x => x.GetPropertyValue<string>("selectedNodes", "").Split(',').Contains("1173"));
Assert.IsNotNull(result);
}
[Test]
public void Index()
{
var doc = GetNode(1173);
Assert.AreEqual(0, doc.Index());
doc = GetNode(1176);
Assert.AreEqual(4, doc.Index());
doc = GetNode(1177);
Assert.AreEqual(2, doc.Index());
doc = GetNode(1178);
Assert.AreEqual(3, doc.Index());
}
[Test]
public void Is_First()
{
var doc = GetNode(1046); //test root nodes
Assert.IsTrue(doc.IsFirst());
doc = GetNode(1172);
Assert.IsFalse(doc.IsFirst());
doc = GetNode(1173); //test normal nodes
Assert.IsTrue(doc.IsFirst());
doc = GetNode(1175);
Assert.IsFalse(doc.IsFirst());
}
[Test]
public void Is_Not_First()
{
var doc = GetNode(1046); //test root nodes
Assert.IsFalse(doc.IsNotFirst());
doc = GetNode(1172);
Assert.IsTrue(doc.IsNotFirst());
doc = GetNode(1173); //test normal nodes
Assert.IsFalse(doc.IsNotFirst());
doc = GetNode(1175);
Assert.IsTrue(doc.IsNotFirst());
}
[Test]
public void Is_Position()
{
var doc = GetNode(1046); //test root nodes
Assert.IsTrue(doc.IsPosition(0));
doc = GetNode(1172);
Assert.IsTrue(doc.IsPosition(1));
doc = GetNode(1173); //test normal nodes
Assert.IsTrue(doc.IsPosition(0));
doc = GetNode(1175);
Assert.IsTrue(doc.IsPosition(1));
}
[Test]
public void Children_GroupBy_DocumentTypeAlias()
{
var doc = GetNode(1046);
var found1 = doc.Children.GroupBy("DocumentTypeAlias");
Assert.AreEqual(2, found1.Count());
Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count());
Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count());
}
[Test]
public void Children_Where_DocumentTypeAlias()
{
var doc = GetNode(1046);
var found1 = doc.Children.Where("DocumentTypeAlias == \"CustomDocument\"");
var found2 = doc.Children.Where("DocumentTypeAlias == \"Home\"");
Assert.AreEqual(1, found1.Count());
Assert.AreEqual(2, found2.Count());
}
[Test]
public void Children_Order_By_Update_Date()
{
var doc = GetNode(1173);
var ordered = doc.Children.OrderBy("UpdateDate");
var correctOrder = new[] { 1178, 1177, 1174, 1176 };
for (var i = 0; i < correctOrder.Length; i++)
{
Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id);
}
}
[Test]
public void FirstChild()
{
var doc = GetNode(1173); // has child nodes
Assert.IsNotNull(doc.FirstChild());
Assert.IsNotNull(doc.FirstChild(x => true));
Assert.IsNotNull(doc.FirstChild<IPublishedContent>());
doc = GetNode(1175); // does not have child nodes
Assert.IsNull(doc.FirstChild());
Assert.IsNull(doc.FirstChild(x => true));
Assert.IsNull(doc.FirstChild<IPublishedContent>());
}
[Test]
public void FirstChildAsT()
{
var doc = GetNode(1046); // has child nodes
var model = doc.FirstChild<Home>();
Assert.IsNotNull(model);
Assert.IsTrue(model.Id == 1173);
Assert.IsInstanceOf<Home>(model);
Assert.IsInstanceOf<IPublishedContent>(model);
model = doc.FirstChildAs<Home>(x => true); // predicate
Assert.IsNotNull(model);
Assert.IsTrue(model.Id == 1173);
Assert.IsInstanceOf<Home>(model);
Assert.IsInstanceOf<IPublishedContent>(model);
doc = GetNode(1175); // does not have child nodes
Assert.IsNull(doc.FirstChildAs<Home>());
Assert.IsNull(doc.FirstChildAs<Home>(x => true));
}
[Test]
public void IsComposedOf()
{
var doc = GetNode(1173);
var isComposedOf = doc.IsComposedOf("MyCompositionAlias");
Assert.IsTrue(isComposedOf);
}
[Test]
public void HasProperty()
{
var doc = GetNode(1173);
var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias);
Assert.IsTrue(hasProp);
}
[Test]
public void HasValue()
{
var doc = GetNode(1173);
var hasValue = doc.HasValue(Constants.Conventions.Content.UrlAlias);
var noValue = doc.HasValue("blahblahblah");
Assert.IsTrue(hasValue);
Assert.IsFalse(noValue);
}
[Test]
public void Ancestors_Where_Visible()
{
var doc = GetNode(1174);
var whereVisible = doc.Ancestors().Where("Visible");
Assert.AreEqual(1, whereVisible.Count());
}
[Test]
public void Visible()
{
var hidden = GetNode(1046);
var visible = GetNode(1173);
Assert.IsFalse(hidden.IsVisible());
Assert.IsTrue(visible.IsVisible());
}
[Test]
public void Ancestor_Or_Self()
{
var doc = GetNode(1173);
var result = doc.AncestorOrSelf();
Assert.IsNotNull(result);
// ancestor-or-self has to be self!
Assert.AreEqual(1173, result.Id);
}
[Test]
public void U4_4559()
{
var doc = GetNode(1174);
var result = doc.AncestorOrSelf(1);
Assert.IsNotNull(result);
Assert.AreEqual(1046, result.Id);
}
[Test]
public void Ancestors_Or_Self()
{
var doc = GetNode(1174);
var result = doc.AncestorsOrSelf();
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 }));
}
[Test]
public void Ancestors()
{
var doc = GetNode(1174);
var result = doc.Ancestors();
Assert.IsNotNull(result);
Assert.AreEqual(2, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 }));
}
[Test]
public void IsAncestor()
{
// Structure:
// - Root : 1046 (no parent)
// -- Home: 1173 (parent 1046)
// -- Custom Doc: 1178 (parent 1173)
// --- Custom Doc2: 1179 (parent: 1178)
// -- Custom Doc4: 117 (parent 1173)
// - Custom Doc3: 1172 (no parent)
var home = GetNode(1173);
var root = GetNode(1046);
var customDoc = GetNode(1178);
var customDoc2 = GetNode(1179);
var customDoc3 = GetNode(1172);
var customDoc4 = GetNode(117);
Assert.IsTrue(root.IsAncestor(customDoc4));
Assert.IsFalse(root.IsAncestor(customDoc3));
Assert.IsTrue(root.IsAncestor(customDoc2));
Assert.IsTrue(root.IsAncestor(customDoc));
Assert.IsTrue(root.IsAncestor(home));
Assert.IsFalse(root.IsAncestor(root));
Assert.IsTrue(home.IsAncestor(customDoc4));
Assert.IsFalse(home.IsAncestor(customDoc3));
Assert.IsTrue(home.IsAncestor(customDoc2));
Assert.IsTrue(home.IsAncestor(customDoc));
Assert.IsFalse(home.IsAncestor(home));
Assert.IsFalse(home.IsAncestor(root));
Assert.IsFalse(customDoc.IsAncestor(customDoc4));
Assert.IsFalse(customDoc.IsAncestor(customDoc3));
Assert.IsTrue(customDoc.IsAncestor(customDoc2));
Assert.IsFalse(customDoc.IsAncestor(customDoc));
Assert.IsFalse(customDoc.IsAncestor(home));
Assert.IsFalse(customDoc.IsAncestor(root));
Assert.IsFalse(customDoc2.IsAncestor(customDoc4));
Assert.IsFalse(customDoc2.IsAncestor(customDoc3));
Assert.IsFalse(customDoc2.IsAncestor(customDoc2));
Assert.IsFalse(customDoc2.IsAncestor(customDoc));
Assert.IsFalse(customDoc2.IsAncestor(home));
Assert.IsFalse(customDoc2.IsAncestor(root));
Assert.IsFalse(customDoc3.IsAncestor(customDoc3));
}
[Test]
public void IsAncestorOrSelf()
{
// Structure:
// - Root : 1046 (no parent)
// -- Home: 1173 (parent 1046)
// -- Custom Doc: 1178 (parent 1173)
// --- Custom Doc2: 1179 (parent: 1178)
// -- Custom Doc4: 117 (parent 1173)
// - Custom Doc3: 1172 (no parent)
var home = GetNode(1173);
var root = GetNode(1046);
var customDoc = GetNode(1178);
var customDoc2 = GetNode(1179);
var customDoc3 = GetNode(1172);
var customDoc4 = GetNode(117);
Assert.IsTrue(root.IsAncestorOrSelf(customDoc4));
Assert.IsFalse(root.IsAncestorOrSelf(customDoc3));
Assert.IsTrue(root.IsAncestorOrSelf(customDoc2));
Assert.IsTrue(root.IsAncestorOrSelf(customDoc));
Assert.IsTrue(root.IsAncestorOrSelf(home));
Assert.IsTrue(root.IsAncestorOrSelf(root));
Assert.IsTrue(home.IsAncestorOrSelf(customDoc4));
Assert.IsFalse(home.IsAncestorOrSelf(customDoc3));
Assert.IsTrue(home.IsAncestorOrSelf(customDoc2));
Assert.IsTrue(home.IsAncestorOrSelf(customDoc));
Assert.IsTrue(home.IsAncestorOrSelf(home));
Assert.IsFalse(home.IsAncestorOrSelf(root));
Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc4));
Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc3));
Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc2));
Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc));
Assert.IsFalse(customDoc.IsAncestorOrSelf(home));
Assert.IsFalse(customDoc.IsAncestorOrSelf(root));
Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc4));
Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc3));
Assert.IsTrue(customDoc2.IsAncestorOrSelf(customDoc2));
Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc));
Assert.IsFalse(customDoc2.IsAncestorOrSelf(home));
Assert.IsFalse(customDoc2.IsAncestorOrSelf(root));
Assert.IsTrue(customDoc4.IsAncestorOrSelf(customDoc4));
Assert.IsTrue(customDoc3.IsAncestorOrSelf(customDoc3));
}
[Test]
public void Descendants_Or_Self()
{
var doc = GetNode(1046);
var result = doc.DescendantsOrSelf();
Assert.IsNotNull(result);
Assert.AreEqual(10, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 }));
}
[Test]
public void Descendants()
{
var doc = GetNode(1046);
var result = doc.Descendants();
Assert.IsNotNull(result);
Assert.AreEqual(9, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 }));
}
[Test]
public void IsDescendant()
{
// Structure:
// - Root : 1046 (no parent)
// -- Home: 1173 (parent 1046)
// -- Custom Doc: 1178 (parent 1173)
// --- Custom Doc2: 1179 (parent: 1178)
// -- Custom Doc4: 117 (parent 1173)
// - Custom Doc3: 1172 (no parent)
var home = GetNode(1173);
var root = GetNode(1046);
var customDoc = GetNode(1178);
var customDoc2 = GetNode(1179);
var customDoc3 = GetNode(1172);
var customDoc4 = GetNode(117);
Assert.IsFalse(root.IsDescendant(root));
Assert.IsFalse(root.IsDescendant(home));
Assert.IsFalse(root.IsDescendant(customDoc));
Assert.IsFalse(root.IsDescendant(customDoc2));
Assert.IsFalse(root.IsDescendant(customDoc3));
Assert.IsFalse(root.IsDescendant(customDoc4));
Assert.IsTrue(home.IsDescendant(root));
Assert.IsFalse(home.IsDescendant(home));
Assert.IsFalse(home.IsDescendant(customDoc));
Assert.IsFalse(home.IsDescendant(customDoc2));
Assert.IsFalse(home.IsDescendant(customDoc3));
Assert.IsFalse(home.IsDescendant(customDoc4));
Assert.IsTrue(customDoc.IsDescendant(root));
Assert.IsTrue(customDoc.IsDescendant(home));
Assert.IsFalse(customDoc.IsDescendant(customDoc));
Assert.IsFalse(customDoc.IsDescendant(customDoc2));
Assert.IsFalse(customDoc.IsDescendant(customDoc3));
Assert.IsFalse(customDoc.IsDescendant(customDoc4));
Assert.IsTrue(customDoc2.IsDescendant(root));
Assert.IsTrue(customDoc2.IsDescendant(home));
Assert.IsTrue(customDoc2.IsDescendant(customDoc));
Assert.IsFalse(customDoc2.IsDescendant(customDoc2));
Assert.IsFalse(customDoc2.IsDescendant(customDoc3));
Assert.IsFalse(customDoc2.IsDescendant(customDoc4));
Assert.IsFalse(customDoc3.IsDescendant(customDoc3));
}
[Test]
public void IsDescendantOrSelf()
{
// Structure:
// - Root : 1046 (no parent)
// -- Home: 1173 (parent 1046)
// -- Custom Doc: 1178 (parent 1173)
// --- Custom Doc2: 1179 (parent: 1178)
// -- Custom Doc4: 117 (parent 1173)
// - Custom Doc3: 1172 (no parent)
var home = GetNode(1173);
var root = GetNode(1046);
var customDoc = GetNode(1178);
var customDoc2 = GetNode(1179);
var customDoc3 = GetNode(1172);
var customDoc4 = GetNode(117);
Assert.IsTrue(root.IsDescendantOrSelf(root));
Assert.IsFalse(root.IsDescendantOrSelf(home));
Assert.IsFalse(root.IsDescendantOrSelf(customDoc));
Assert.IsFalse(root.IsDescendantOrSelf(customDoc2));
Assert.IsFalse(root.IsDescendantOrSelf(customDoc3));
Assert.IsFalse(root.IsDescendantOrSelf(customDoc4));
Assert.IsTrue(home.IsDescendantOrSelf(root));
Assert.IsTrue(home.IsDescendantOrSelf(home));
Assert.IsFalse(home.IsDescendantOrSelf(customDoc));
Assert.IsFalse(home.IsDescendantOrSelf(customDoc2));
Assert.IsFalse(home.IsDescendantOrSelf(customDoc3));
Assert.IsFalse(home.IsDescendantOrSelf(customDoc4));
Assert.IsTrue(customDoc.IsDescendantOrSelf(root));
Assert.IsTrue(customDoc.IsDescendantOrSelf(home));
Assert.IsTrue(customDoc.IsDescendantOrSelf(customDoc));
Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc2));
Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc3));
Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc4));
Assert.IsTrue(customDoc2.IsDescendantOrSelf(root));
Assert.IsTrue(customDoc2.IsDescendantOrSelf(home));
Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc));
Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc2));
Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc3));
Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc4));
Assert.IsTrue(customDoc3.IsDescendantOrSelf(customDoc3));
}
[Test]
public void Up()
{
var doc = GetNode(1173);
var result = doc.Up();
Assert.IsNotNull(result);
Assert.AreEqual((int)1046, (int)result.Id);
}
[Test]
public void Down()
{
var doc = GetNode(1173);
var result = doc.Down();
Assert.IsNotNull(result);
Assert.AreEqual((int)1174, (int)result.Id);
}
[Test]
public void Next()
{
var doc = GetNode(1173);
var result = doc.Next();
Assert.IsNotNull(result);
Assert.AreEqual((int)1175, (int)result.Id);
}
[Test]
public void Next_Without_Sibling()
{
var doc = GetNode(1176);
Assert.IsNull(doc.Next());
}
[Test]
public void Previous_Without_Sibling()
{
var doc = GetNode(1173);
Assert.IsNull(doc.Previous());
}
[Test]
public void Previous()
{
var doc = GetNode(1176);
var result = doc.Previous();
Assert.IsNotNull(result);
Assert.AreEqual((int)1178, (int)result.Id);
}
[Test]
public void GetKey()
{
var key = Guid.Parse("CDB83BBC-A83B-4BA6-93B8-AADEF67D3C09");
// doc is Home (a model) and GetKey unwraps and works
var doc = GetNode(1176);
Assert.IsInstanceOf<Home>(doc);
Assert.AreEqual(key, doc.GetKey());
// wrapped is PublishedContentWrapped and WithKey unwraps
var wrapped = new TestWrapped(doc);
Assert.AreEqual(key, wrapped.GetKey());
}
class TestWrapped : PublishedContentWrapped
{
public TestWrapped(IPublishedContent content)
: base(content)
{ }
}
[Test]
public void DetachedProperty1()
{
var type = new PublishedPropertyType("detached", Constants.PropertyEditors.IntegerAlias);
var prop = PublishedProperty.GetDetached(type.Detached(), "5548");
Assert.IsInstanceOf<int>(prop.Value);
Assert.AreEqual(5548, prop.Value);
}
public void CreateDetachedContentSample()
{
bool previewing = false;
var t = PublishedContentType.Get(PublishedItemType.Content, "detachedSomething");
var values = new Dictionary<string, object>();
var properties = t.PropertyTypes.Select(x =>
{
object value;
if (values.TryGetValue(x.PropertyTypeAlias, out value) == false) value = null;
return PublishedProperty.GetDetached(x.Detached(), value, previewing);
});
// and if you want some sort of "model" it's up to you really...
var c = new DetachedContent(properties);
}
public void CreatedDetachedContentInConverterSample()
{
// the converter args
PublishedPropertyType argPropertyType = null;
bool argPreview = false;
var pt1 = new PublishedPropertyType("legend", 0, Constants.PropertyEditors.TextboxAlias);
var pt2 = new PublishedPropertyType("image", 0, Constants.PropertyEditors.MediaPickerAlias);
string val1 = "";
int val2 = 0;
var c = new ImageWithLegendModel(
PublishedProperty.GetDetached(pt1.Nested(argPropertyType), val1, argPreview),
PublishedProperty.GetDetached(pt2.Nested(argPropertyType), val2, argPreview));
}
class ImageWithLegendModel
{
private IPublishedProperty _legendProperty;
private IPublishedProperty _imageProperty;
public ImageWithLegendModel(IPublishedProperty legendProperty, IPublishedProperty imageProperty)
{
_legendProperty = legendProperty;
_imageProperty = imageProperty;
}
public string Legend { get { return _legendProperty.GetValue<string>(); } }
public IPublishedContent Image { get { return _imageProperty.GetValue<IPublishedContent>(); } }
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
namespace Microsoft.VisualStudioTools.Project {
internal class FileNode : HierarchyNode, IDiskBasedNode {
private bool _isLinkFile;
private uint _docCookie;
private static readonly string[] _defaultOpensWithDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx", ".xsd", ".resource", ".xaml" };
private static readonly string[] _supportsDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx" };
private static readonly string[] _supportsDesignViewSubTypes = new[] { ProjectFileAttributeValue.Code, ProjectFileAttributeValue.Form, ProjectFileAttributeValue.UserControl, ProjectFileAttributeValue.Component, ProjectFileAttributeValue.Designer };
private string _caption;
#region static fields
#if !DEV14_OR_LATER
private static Dictionary<string, int> extensionIcons;
#endif
#endregion
#region overriden Properties
public override bool DefaultOpensWithDesignView {
get {
// ASPX\ASCX files support design view but should be opened by default with
// LOGVIEWID_Primary - this is because they support design and html view which
// is a tools option setting for them. If we force designview this option
// gets bypassed. We do a similar thing for asax/asmx/xsd. By doing so, we don't force
// the designer to be invoked when double-clicking on the - it will now go through the
// shell's standard open mechanism.
string extension = Path.GetExtension(Url);
return !_defaultOpensWithDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) &&
!IsCodeBehindFile &&
SupportsDesignView;
}
}
public override bool SupportsDesignView {
get {
if (ItemNode != null && !ItemNode.IsExcluded) {
string extension = Path.GetExtension(Url);
if (_supportsDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) ||
IsCodeBehindFile) {
return true;
} else {
var subType = ItemNode.GetMetadata("SubType");
if (subType != null && _supportsDesignViewExtensions.Contains(subType, StringComparer.OrdinalIgnoreCase)) {
return true;
}
}
}
return false;
}
}
public override bool IsNonMemberItem {
get {
return ItemNode is AllFilesProjectElement;
}
}
/// <summary>
/// overwrites of the generic hierarchyitem.
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public override string Caption {
get {
return _caption;
}
}
private void UpdateCaption() {
// Use LinkedIntoProjectAt property if available
string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt);
if (caption == null || caption.Length == 0) {
// Otherwise use filename
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
caption = Path.GetFileName(caption);
}
_caption = caption;
}
public override string GetEditLabel() {
if (IsLinkFile) {
// cannot rename link files
return null;
}
return Caption;
}
#if !DEV14_OR_LATER
public override int ImageIndex {
get {
// Check if the file is there.
if (!this.CanShowDefaultIcon()) {
return (int)ProjectNode.ImageName.MissingFile;
}
//Check for known extensions
int imageIndex;
string extension = Path.GetExtension(this.FileName);
if ((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex))) {
// Missing or unknown extension; let the base class handle this case.
return base.ImageIndex;
}
// The file type is known and there is an image for it in the image list.
return imageIndex;
}
}
#endif
public uint DocCookie {
get {
return this._docCookie;
}
set {
this._docCookie = value;
}
}
public override bool IsLinkFile {
get {
return _isLinkFile;
}
}
internal void SetIsLinkFile(bool value) {
_isLinkFile = value;
}
protected override VSOVERLAYICON OverlayIconIndex {
get {
if (IsLinkFile) {
return VSOVERLAYICON.OVERLAYICON_SHORTCUT;
}
return VSOVERLAYICON.OVERLAYICON_NONE;
}
}
public override Guid ItemTypeGuid {
get { return VSConstants.GUID_ItemType_PhysicalFile; }
}
public override int MenuCommandId {
get { return VsMenus.IDM_VS_CTXT_ITEMNODE; }
}
public override string Url {
get {
return ItemNode.Url;
}
}
#endregion
#region ctor
#if !DEV14_OR_LATER
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static FileNode() {
// Build the dictionary with the mapping between some well known extensions
// and the index of the icons inside the standard image list.
extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm);
extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass);
extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService);
extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl);
extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage);
extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig);
extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile);
extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap);
extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon);
extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap);
extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB);
extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR);
extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile);
extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema);
extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile);
extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX);
extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK);
}
#endif
/// <summary>
/// Constructor for the FileNode
/// </summary>
/// <param name="root">Root of the hierarchy</param>
/// <param name="e">Associated project element</param>
public FileNode(ProjectNode root, ProjectElement element)
: base(root, element) {
UpdateCaption();
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject() {
if (IsLinkFile) {
return new LinkFileNodeProperties(this);
} else if (IsNonMemberItem) {
return new ExcludedFileNodeProperties(this);
}
return new IncludedFileNodeProperties(this);
}
/// <summary>
/// Get an instance of the automation object for a FileNode
/// </summary>
/// <returns>An instance of the Automation.OAFileNode if succeeded</returns>
public override object GetAutomationObject() {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return null;
}
return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Renames a file node.
/// </summary>
/// <param name="label">The new name.</param>
/// <returns>An errorcode for failure or S_OK.</returns>
/// <exception cref="InvalidOperationException" if the file cannot be validated>
/// <devremark>
/// We are going to throw instead of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
/// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
/// Also the automation methods are also calling SetEditLabel
/// </devremark>
public override int SetEditLabel(string label) {
// IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
// expected that we can be called with a label which is the same as the current
// label and this should not be considered a NO-OP.
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return VSConstants.E_FAIL;
}
// Validate the filename.
if (String.IsNullOrEmpty(label)) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
} else if (label.Length > NativeMethods.MAX_PATH) {
throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
} else if (Utilities.IsFileNameInvalid(label)) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
}
for (HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling) {
// TODO: Distinguish between real Urls and fake ones (eg. "References")
if (n != this && String.Equals(n.Caption, label, StringComparison.OrdinalIgnoreCase)) {
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
//If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
throw new InvalidOperationException(SR.GetString(SR.FileOrFolderAlreadyExists, label));
}
}
string fileName = Path.GetFileNameWithoutExtension(label);
// Verify that the file extension is unchanged
string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site) &&
!String.Equals(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase)) {
// Prompt to confirm that they really want to change the extension of the file
string message = SR.GetString(SR.ConfirmExtensionChange, label);
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_INFO, shell)) {
// The user cancelled the confirmation for changing the extension.
// Return S_OK in order not to show any extra dialog box
return VSConstants.S_OK;
}
}
// Build the relative path by looking at folder names above us as one scenarios
// where we get called is when a folder above us gets renamed (in which case our path is invalid)
HierarchyNode parent = this.Parent;
while (parent != null && (parent is FolderNode)) {
strRelPath = Path.Combine(parent.Caption, strRelPath);
parent = parent.Parent;
}
return SetEditLabel(label, strRelPath);
}
public override string GetMkDocument() {
Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node");
Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path");
return this.Url;
}
/// <summary>
/// Delete the item corresponding to the specified path from storage.
/// </summary>
/// <param name="path"></param>
protected internal override void DeleteFromStorage(string path) {
if (File.Exists(path)) {
File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly.
File.Delete(path);
}
}
/// <summary>
/// Rename the underlying document based on the change the user just made to the edit label.
/// </summary>
protected internal override int SetEditLabel(string label, string relativePath) {
int returnValue = VSConstants.S_OK;
uint oldId = this.ID;
string strSavePath = Path.GetDirectoryName(relativePath);
strSavePath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectMgr.ProjectHome, strSavePath);
string newName = Path.Combine(strSavePath, label);
if (String.Equals(newName, this.Url, StringComparison.Ordinal)) {
// This is really a no-op (including changing case), so there is nothing to do
return VSConstants.S_FALSE;
} else if (String.Equals(newName, this.Url, StringComparison.OrdinalIgnoreCase)) {
// This is a change of file casing only.
} else {
// If the renamed file already exists then quit (unless it is the result of the parent having done the move).
if (IsFileOnDisk(newName)
&& (IsFileOnDisk(this.Url)
|| !String.Equals(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.OrdinalIgnoreCase))) {
throw new InvalidOperationException(SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, label));
} else if (newName.Length > NativeMethods.MAX_PATH) {
throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
}
}
string oldName = this.Url;
// must update the caption prior to calling RenameDocument, since it may
// cause queries of that property (such as from open editors).
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
try {
if (!RenameDocument(oldName, newName)) {
this.ItemNode.Rename(oldrelPath);
}
if (this is DependentFileNode) {
ProjectMgr.OnInvalidateItems(this.Parent);
}
} catch (Exception e) {
// Just re-throw the exception so we don't get duplicate message boxes.
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newName, oldrelPath);
returnValue = Marshal.GetHRForException(e);
throw;
}
// Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale
// hierarchy item id.
if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE;
}
return returnValue;
}
/// <summary>
/// Returns a specific Document manager to handle files
/// </summary>
/// <returns>Document manager object</returns>
protected internal override DocumentManager GetDocumentManager() {
return new FileDocumentManager(this);
}
public override int QueryService(ref Guid guidService, out object result) {
if (guidService == typeof(EnvDTE.Project).GUID) {
result = ProjectMgr.GetAutomationObject();
return VSConstants.S_OK;
} else if (guidService == typeof(EnvDTE.ProjectItem).GUID) {
result = GetAutomationObject();
return VSConstants.S_OK;
}
return base.QueryService(ref guidService, out result);
}
/// <summary>
/// Called by the drag&drop implementation to ask the node
/// which is being dragged/droped over which nodes should
/// process the operation.
/// This allows for dragging to a node that cannot contain
/// items to let its parent accept the drop, while a reference
/// node delegate to the project and a folder/project node to itself.
/// </summary>
/// <returns></returns>
protected internal override HierarchyNode GetDragTargetHandlerNode() {
Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode");
HierarchyNode handlerNode = this;
while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode))
handlerNode = handlerNode.Parent;
if (handlerNode == null)
handlerNode = this.ProjectMgr;
return handlerNode;
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Exec on special filenode commands
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
IVsWindowFrame windowFrame = null;
switch ((VsCommands)cmd) {
case VsCommands.ViewCode:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.ViewForm:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.Open:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show);
case VsCommands.OpenWith:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show);
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.ViewCode:
//case VsCommands.Delete: goto case VsCommands.OpenWith;
case VsCommands.Open:
case VsCommands.OpenWith:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
protected override void DoDefaultAction() {
FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager;
Utilities.CheckNotNull(manager, "Could not get the FileDocumentManager");
manager.Open(false, false, WindowFrameShowAction.Show);
}
/// <summary>
/// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
/// </summary>
/// <param name="docData">A pointer to the document in the rdt</param>
/// <param name="newFilePath">The new file path to the document</param>
/// <returns></returns>
internal override int AfterSaveItemAs(IntPtr docData, string newFilePath) {
Utilities.ArgumentNotNullOrEmpty("newFilePath", newFilePath);
int returnCode = VSConstants.S_OK;
newFilePath = newFilePath.Trim();
//Identify if Path or FileName are the same for old and new file
string newDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(newFilePath));
string oldDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.GetMkDocument()));
bool isSamePath = CommonUtils.IsSameDirectory(newDirectoryName, oldDirectoryName);
bool isSameFile = CommonUtils.IsSamePath(newFilePath, this.Url);
//Get target container
HierarchyNode targetContainer = null;
bool isLink = false;
if (isSamePath) {
targetContainer = this.Parent;
} else if (!CommonUtils.IsSubpathOf(this.ProjectMgr.ProjectHome, newDirectoryName)) {
targetContainer = this.Parent;
isLink = true;
} else if (CommonUtils.IsSameDirectory(this.ProjectMgr.ProjectHome, newDirectoryName)) {
//the projectnode is the target container
targetContainer = this.ProjectMgr;
} else {
//search for the target container among existing child nodes
targetContainer = this.ProjectMgr.FindNodeByFullPath(newDirectoryName);
if (targetContainer != null && (targetContainer is FileNode)) {
// We already have a file node with this name in the hierarchy.
throw new InvalidOperationException(SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, Path.GetFileName(newFilePath)));
}
}
if (targetContainer == null) {
// Add a chain of subdirectories to the project.
string relativeUri = CommonUtils.GetRelativeDirectoryPath(this.ProjectMgr.ProjectHome, newDirectoryName);
targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
}
Utilities.CheckNotNull(targetContainer, "Could not find a target container");
//Suspend file changes while we rename the document
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
string oldName = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, oldrelPath);
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try {
// Rename the node.
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
// Check if the file name was actually changed.
// In same cases (e.g. if the item is a file and the user has changed its encoding) this function
// is called even if there is no real rename.
if (!isSameFile || (this.Parent.ID != targetContainer.ID)) {
// The path of the file is changed or its parent is changed; in both cases we have
// to rename the item.
if (isLink != IsLinkFile) {
if (isLink) {
var newPath = CommonUtils.GetRelativeFilePath(
this.ProjectMgr.ProjectHome,
Path.Combine(Path.GetDirectoryName(Url), Path.GetFileName(newFilePath))
);
ItemNode.SetMetadata(ProjectFileConstants.Link, newPath);
} else {
ItemNode.SetMetadata(ProjectFileConstants.Link, null);
}
SetIsLinkFile(isLink);
}
RenameFileNode(oldName, newFilePath, targetContainer);
ProjectMgr.OnInvalidateItems(this.Parent);
}
} catch (Exception e) {
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newFilePath, oldrelPath);
throw;
} finally {
sfc.Resume();
}
return returnCode;
}
/// <summary>
/// Determines if this is node a valid node for painting the default file icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
string moniker = this.GetMkDocument();
return File.Exists(moniker);
}
#endregion
#region virtual methods
public override object GetProperty(int propId) {
switch ((__VSHPROPID)propId) {
case __VSHPROPID.VSHPROPID_ItemDocCookie:
if (this.DocCookie != 0)
return (IntPtr)this.DocCookie; //cast to IntPtr as some callers expect VT_INT
break;
}
return base.GetProperty(propId);
}
public virtual string FileName {
get {
return this.Caption;
}
set {
this.SetEditLabel(value);
}
}
/// <summary>
/// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented.
/// </summary>
/// <param name="showMessage">true if user should be presented for UI in case the file is not present</param>
/// <returns>true if file is on disk</returns>
internal protected virtual bool IsFileOnDisk(bool showMessage) {
bool fileExist = IsFileOnDisk(this.Url);
if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) {
string message = SR.GetString(SR.ItemDoesNotExistInProjectDirectory, Caption);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
Utilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
return fileExist;
}
/// <summary>
/// Determine if the file represented by "path" exist in storage.
/// Override this method if your files are not persisted on disk.
/// </summary>
/// <param name="path">Url representing the file</param>
/// <returns>True if the file exist</returns>
internal protected virtual bool IsFileOnDisk(string path) {
return File.Exists(path);
}
/// <summary>
/// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
/// </summary>
/// <param name="oldFileName">The old file name.</param>
/// <param name="newFileName">The new file name</param>
/// <param name="newParentId">The new parent id of the item.</param>
/// <returns>The newly added FileNode.</returns>
/// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
internal FileNode RenameFileNode(string oldFileName, string newFileName, HierarchyNode newParent) {
if (CommonUtils.IsSamePath(oldFileName, newFileName)) {
// We do not want to rename the same file
return null;
}
//If we are included in the project and our parent isn't then
//we need to bring our parent into the project
if (!this.IsNonMemberItem && newParent.IsNonMemberItem) {
ErrorHandler.ThrowOnFailure(newParent.IncludeInProject(false));
}
// Retrieve child nodes to add later.
List<HierarchyNode> childNodes = this.GetChildNodes();
FileNode renamedNode;
using (this.ProjectMgr.ExtensibilityEventsDispatcher.Suspend()) {
// Remove this from its parent.
ProjectMgr.OnItemDeleted(this);
this.Parent.RemoveChild(this);
// Update name in MSBuild
this.ItemNode.Rename(CommonUtils.GetRelativeFilePath(ProjectMgr.ProjectHome, newFileName));
// Request a new file node be made. This is used to replace the old file node. This way custom
// derived FileNode types will be used and correctly associated on rename. This is useful for things
// like .txt -> .js where the file would now be able to be a startup project/file.
renamedNode = this.ProjectMgr.CreateFileNode(this.ItemNode);
renamedNode.ItemNode.RefreshProperties();
renamedNode.UpdateCaption();
newParent.AddChild(renamedNode);
renamedNode.Parent = newParent;
}
UpdateCaption();
ProjectMgr.ReDrawNode(renamedNode, UIHierarchyElement.Caption);
renamedNode.ProjectMgr.ExtensibilityEventsDispatcher.FireItemRenamed(this, oldFileName);
//Update the new document in the RDT.
DocumentManager.RenameDocument(renamedNode.ProjectMgr.Site, oldFileName, newFileName, renamedNode.ID);
//Select the new node in the hierarchy
renamedNode.ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
// Add children to new node and rename them appropriately.
childNodes.ForEach(x => renamedNode.AddChild(x));
RenameChildNodes(renamedNode);
return renamedNode;
}
/// <summary>
/// Rename all childnodes
/// </summary>
/// <param name="newFileNode">The newly added Parent node.</param>
protected virtual void RenameChildNodes(FileNode parentNode) {
foreach (var childNode in GetChildNodes().OfType<FileNode>()) {
string newfilename;
if (childNode.HasParentNodeNameRelation) {
string relationalName = childNode.Parent.GetRelationalName();
string extension = childNode.GetRelationNameExtension();
newfilename = relationalName + extension;
newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename);
} else {
newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.Caption);
}
childNode.RenameDocument(childNode.GetMkDocument(), newfilename);
//We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed
//which happens if the is no name relation between the parent and the child
string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
if (!string.IsNullOrEmpty(dependentOf)) {
childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include));
}
}
}
/// <summary>
/// Tries recovering from a rename failure.
/// </summary>
/// <param name="fileThatFailed"> The file that failed to be renamed.</param>
/// <param name="originalFileName">The original filenamee</param>
protected virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName) {
if (this.ItemNode != null && !String.IsNullOrEmpty(originalFileName)) {
this.ItemNode.Rename(originalFileName);
}
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
/// <summary>
/// This should be overriden for node that are not saved on disk
/// </summary>
/// <param name="oldName">Previous name in storage</param>
/// <param name="newName">New name in storage</param>
internal virtual void RenameInStorage(string oldName, string newName) {
// Make a few attempts over a short time period
for (int retries = 4; retries > 0; --retries) {
try {
File.Move(oldName, newName);
return;
} catch (IOException) {
System.Threading.Thread.Sleep(50);
}
}
// Final attempt has no handling so exception propagates
File.Move(oldName, newName);
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) {
if (this.ExcludeNodeFromScc) {
return;
}
Utilities.ArgumentNotNull("files", files);
Utilities.ArgumentNotNull("flags", flags);
foreach (HierarchyNode node in this.GetChildNodes()) {
files.Add(node.GetMkDocument());
}
}
#endregion
#region Helper methods
/// <summary>
/// Gets called to rename the eventually running document this hierarchyitem points to
/// </summary>
/// returns FALSE if the doc can not be renamed
internal bool RenameDocument(string oldName, string newName) {
IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null)
return false;
IntPtr docData = IntPtr.Zero;
IVsHierarchy pIVsHierarchy;
uint itemId;
uint uiVsDocCookie;
SuspendFileChanges sfc = null;
if (File.Exists(oldName)) {
sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
}
try {
// Suspend ms build since during a rename operation no msbuild re-evaluation should be performed until we have finished.
// Scenario that could fail if we do not suspend.
// We have a project system relying on MPF that triggers a Compile target build (re-evaluates itself) whenever the project changes. (example: a file is added, property changed.)
// 1. User renames a file in the above project sytem relying on MPF
// 2. Our rename funstionality implemented in this method removes and readds the file and as a post step copies all msbuild entries from the removed file to the added file.
// 3. The project system mentioned will trigger an msbuild re-evaluate with the new item, because it was listening to OnItemAdded.
// The problem is that the item at the "add" time is only partly added to the project, since the msbuild part has not yet been copied over as mentioned in part 2 of the last step of the rename process.
// The result is that the project re-evaluates itself wrongly.
VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr)) {
// Don't rename it if it wasn't opened by us.
return false;
}
// ask other potentially running packages
if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag)) {
return false;
}
if (IsFileOnDisk(oldName)) {
RenameInStorage(oldName, newName);
}
// For some reason when ignoreFileChanges is called in Resume, we get an ArgumentException because
// Somewhere a required fileWatcher is null. This issue only occurs when you copy and rename a typescript file,
// Calling Resume here prevents said fileWatcher from being null. Don't know why it works, but it does.
// Also fun! This is the only location it can go (between RenameInStorage and RenameFileNode)
// So presumably there is some condition that is no longer met once both of these methods are called with a ts file.
// https://nodejstools.codeplex.com/workitem/1510
if (sfc != null) {
sfc.Resume();
sfc.Suspend();
}
if (!CommonUtils.IsSamePath(oldName, newName)) {
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
this.RenameFileNode(oldName, newName);
} else {
this.RenameCaseOnlyChange(oldName, newName);
}
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Caption, docData);
// changed from MPFProj:
// http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8231
this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
} finally {
if (sfc != null) {
sfc.Resume();
}
if (docData != IntPtr.Zero) {
Marshal.Release(docData);
}
}
return true;
}
internal virtual FileNode RenameFileNode(string oldFileName, string newFileName) {
string newFolder = Path.GetDirectoryName(newFileName) + Path.DirectorySeparatorChar;
var parentFolder = ProjectMgr.FindNodeByFullPath(newFolder);
if (parentFolder == null) {
Debug.Assert(newFolder == ProjectMgr.ProjectHome);
parentFolder = ProjectMgr;
}
return this.RenameFileNode(oldFileName, newFileName, parentFolder);
}
/// <summary>
/// Renames the file node for a case only change.
/// </summary>
/// <param name="newFileName">The new file name.</param>
private void RenameCaseOnlyChange(string oldName, string newName) {
//Update the include for this item.
string relName = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, newName);
Debug.Assert(String.Equals(this.ItemNode.GetMetadata(ProjectFileConstants.Include), relName, StringComparison.OrdinalIgnoreCase),
"Not just changing the filename case");
this.ItemNode.Rename(relName);
this.ItemNode.RefreshProperties();
UpdateCaption();
ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption);
this.RenameChildNodes(this);
// Refresh the property browser.
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
//Select the new node in the hierarchy
ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
}
#endregion
#region helpers
/// <summary>
/// Update the ChildNodes after the parent node has been renamed
/// </summary>
/// <param name="newFileNode">The new FileNode created as part of the rename of this node</param>
private void SetNewParentOnChildNodes(FileNode newFileNode) {
foreach (HierarchyNode childNode in GetChildNodes()) {
childNode.Parent = newFileNode;
}
}
private List<HierarchyNode> GetChildNodes() {
List<HierarchyNode> childNodes = new List<HierarchyNode>();
HierarchyNode childNode = this.FirstChild;
while (childNode != null) {
childNodes.Add(childNode);
childNode = childNode.NextSibling;
}
return childNodes;
}
#endregion
void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath) {
string oldLoc = CommonUtils.GetAbsoluteFilePath(basePath, ItemNode.GetMetadata(ProjectFileConstants.Include));
string newLoc = CommonUtils.GetAbsoluteFilePath(baseNewPath, ItemNode.GetMetadata(ProjectFileConstants.Include));
ProjectMgr.UpdatePathForDeferredSave(oldLoc, newLoc);
// make sure the directory is there
Directory.CreateDirectory(Path.GetDirectoryName(newLoc));
if (File.Exists(oldLoc)) {
File.Move(oldLoc, newLoc);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Services
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
/// <summary>
/// Defines functionality to deploy distributed services in the Ignite.
/// </summary>
public interface IServices
{
/// <summary>
/// Gets the cluster group to which this instance belongs.
/// </summary>
/// <value>
/// The cluster group to which this instance belongs.
/// </value>
IClusterGroup ClusterGroup { get; }
/// <summary>
/// Deploys a cluster-wide singleton service. Ignite guarantees that there is always
/// one instance of the service in the cluster. In case if Ignite node on which the service
/// was deployed crashes or stops, Ignite will automatically redeploy it on another node.
/// However, if the node on which the service is deployed remains in topology, then the
/// service will always be deployed on that node only, regardless of topology changes.
/// <para />
/// Note that in case of topology changes, due to network delays, there may be a temporary situation
/// when a singleton service instance will be active on more than one node (e.g. crash detection delay).
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
void DeployClusterSingleton(string name, IService service);
/// <summary>
/// Deploys a cluster-wide singleton service. Ignite guarantees that there is always
/// one instance of the service in the cluster. In case if Ignite node on which the service
/// was deployed crashes or stops, Ignite will automatically redeploy it on another node.
/// However, if the node on which the service is deployed remains in topology, then the
/// service will always be deployed on that node only, regardless of topology changes.
/// <para />
/// Note that in case of topology changes, due to network delays, there may be a temporary situation
/// when a singleton service instance will be active on more than one node (e.g. crash detection delay).
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
Task DeployClusterSingletonAsync(string name, IService service);
/// <summary>
/// Deploys a per-node singleton service. Ignite guarantees that there is always
/// one instance of the service running on each node. Whenever new nodes are started
/// within the underlying cluster group, Ignite will automatically deploy one instance of
/// the service on every new node.
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
void DeployNodeSingleton(string name, IService service);
/// <summary>
/// Deploys a per-node singleton service. Ignite guarantees that there is always
/// one instance of the service running on each node. Whenever new nodes are started
/// within the underlying cluster group, Ignite will automatically deploy one instance of
/// the service on every new node.
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
Task DeployNodeSingletonAsync(string name, IService service);
/// <summary>
/// Deploys one instance of this service on the primary node for a given affinity key.
/// Whenever topology changes and primary node assignment changes, Ignite will always
/// make sure that the service is undeployed on the previous primary node and deployed
/// on the new primary node.
/// <para />
/// Note that in case of topology changes, due to network delays, there may be a temporary situation
/// when a service instance will be active on more than one node (e.g. crash detection delay).
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
/// <param name="cacheName">Name of the cache on which affinity for key should be calculated, null for
/// default cache.</param>
/// <param name="affinityKey">Affinity cache key.</param>
void DeployKeyAffinitySingleton<TK>(string name, IService service, string cacheName, TK affinityKey);
/// <summary>
/// Deploys one instance of this service on the primary node for a given affinity key.
/// Whenever topology changes and primary node assignment changes, Ignite will always
/// make sure that the service is undeployed on the previous primary node and deployed
/// on the new primary node.
/// <para />
/// Note that in case of topology changes, due to network delays, there may be a temporary situation
/// when a service instance will be active on more than one node (e.g. crash detection delay).
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
/// <param name="cacheName">Name of the cache on which affinity for key should be calculated, null for
/// default cache.</param>
/// <param name="affinityKey">Affinity cache key.</param>
Task DeployKeyAffinitySingletonAsync<TK>(string name, IService service, string cacheName, TK affinityKey);
/// <summary>
/// Deploys multiple instances of the service on the grid. Ignite will deploy a
/// maximum amount of services equal to <paramref name="totalCount" /> parameter making sure that
/// there are no more than <paramref name="maxPerNodeCount" /> service instances running
/// on each node. Whenever topology changes, Ignite will automatically rebalance
/// the deployed services within cluster to make sure that each node will end up with
/// about equal number of deployed instances whenever possible.
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
/// <param name="totalCount">Maximum number of deployed services in the grid, 0 for unlimited.</param>
/// <param name="maxPerNodeCount">Maximum number of deployed services on each node, 0 for unlimited.</param>
void DeployMultiple(string name, IService service, int totalCount, int maxPerNodeCount);
/// <summary>
/// Deploys multiple instances of the service on the grid. Ignite will deploy a
/// maximum amount of services equal to <paramref name="totalCount" /> parameter making sure that
/// there are no more than <paramref name="maxPerNodeCount" /> service instances running
/// on each node. Whenever topology changes, Ignite will automatically rebalance
/// the deployed services within cluster to make sure that each node will end up with
/// about equal number of deployed instances whenever possible.
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="service">Service instance.</param>
/// <param name="totalCount">Maximum number of deployed services in the grid, 0 for unlimited.</param>
/// <param name="maxPerNodeCount">Maximum number of deployed services on each node, 0 for unlimited.</param>
Task DeployMultipleAsync(string name, IService service, int totalCount, int maxPerNodeCount);
/// <summary>
/// Deploys instances of the service in the Ignite according to provided configuration.
/// </summary>
/// <param name="configuration">Service configuration.</param>
void Deploy(ServiceConfiguration configuration);
/// <summary>
/// Deploys instances of the service in the Ignite according to provided configuration.
/// </summary>
/// <param name="configuration">Service configuration.</param>
Task DeployAsync(ServiceConfiguration configuration);
/// <summary>
/// Deploys multiple services described by provided configurations. Depending on specified parameters,
/// multiple instances of the same service may be deployed. Whenever topology changes,
/// Ignite will automatically rebalance the deployed services within cluster to make sure that each node
/// will end up with about equal number of deployed instances whenever possible.
/// <para/>
/// If deployment of some of the provided services fails, then <see cref="ServiceDeploymentException"/>
/// containing a list of failed service configurations
/// (<see cref="ServiceDeploymentException.FailedConfigurations"/>) will be thrown. It is guaranteed that all
/// services that were provided to this method and are not present in the list of failed services are
/// successfully deployed by the moment of the exception being thrown.
/// Note that if exception is thrown, then partial deployment may have occurred.
/// </summary>
/// <param name="configurations">Collection of service configurations to be deployed.</param>
void DeployAll(IEnumerable<ServiceConfiguration> configurations);
/// <summary>
/// Asynchronously deploys multiple services described by provided configurations. Depending on specified
/// parameters, multiple instances of the same service may be deployed (<see cref="ServiceConfiguration"/>).
/// Whenever topology changes, Ignite will automatically rebalance the deployed services within cluster to make
/// sure that each node will end up with about equal number of deployed instances whenever possible.
/// <para/>
/// If deployment of some of the provided services fails, then <see cref="ServiceDeploymentException"/>
/// containing a list of failed service configurations
/// (<see cref="ServiceDeploymentException.FailedConfigurations"/>) will be thrown. It is guaranteed that all
/// services, that were provided to this method and are not present in the list of failed services, are
/// successfully deployed by the moment of the exception being thrown.
/// Note that if exception is thrown, then partial deployment may have occurred.
/// </summary>
/// <param name="configurations">Collection of service configurations to be deployed.</param>
Task DeployAllAsync(IEnumerable<ServiceConfiguration> configurations);
/// <summary>
/// Cancels service deployment. If a service with specified name was deployed on the grid,
/// then <see cref="IService.Cancel"/> method will be called on it.
/// <para/>
/// Note that Ignite cannot guarantee that the service exits from <see cref="IService.Execute"/>
/// method whenever <see cref="IService.Cancel"/> is called. It is up to the user to
/// make sure that the service code properly reacts to cancellations.
/// </summary>
/// <param name="name">Name of the service to cancel.</param>
void Cancel(string name);
/// <summary>
/// Cancels service deployment. If a service with specified name was deployed on the grid,
/// then <see cref="IService.Cancel"/> method will be called on it.
/// <para/>
/// Note that Ignite cannot guarantee that the service exits from <see cref="IService.Execute"/>
/// method whenever <see cref="IService.Cancel"/> is called. It is up to the user to
/// make sure that the service code properly reacts to cancellations.
/// </summary>
/// <param name="name">Name of the service to cancel.</param>
Task CancelAsync(string name);
/// <summary>
/// Cancels all deployed services.
/// <para/>
/// Note that depending on user logic, it may still take extra time for a service to
/// finish execution, even after it was cancelled.
/// </summary>
void CancelAll();
/// <summary>
/// Cancels all deployed services.
/// <para/>
/// Note that depending on user logic, it may still take extra time for a service to
/// finish execution, even after it was cancelled.
/// </summary>
Task CancelAllAsync();
/// <summary>
/// Gets metadata about all deployed services.
/// </summary>
/// <returns>Metadata about all deployed services.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Expensive operation.")]
ICollection<IServiceDescriptor> GetServiceDescriptors();
/// <summary>
/// Gets deployed service with specified name.
/// </summary>
/// <typeparam name="T">Service type.</typeparam>
/// <param name="name">Service name.</param>
/// <returns>Deployed service with specified name.</returns>
T GetService<T>(string name);
/// <summary>
/// Gets all deployed services with specified name.
/// </summary>
/// <typeparam name="T">Service type.</typeparam>
/// <param name="name">Service name.</param>
/// <returns>All deployed services with specified name.</returns>
ICollection<T> GetServices<T>(string name);
/// <summary>
/// Gets a remote handle on the service. If service is available locally,
/// then local instance is returned, otherwise, a remote proxy is dynamically
/// created and provided for the specified service.
/// </summary>
/// <typeparam name="T">Service type.</typeparam>
/// <param name="name">Service name.</param>
/// <returns>Either proxy over remote service or local service if it is deployed locally.</returns>
T GetServiceProxy<T>(string name) where T : class;
/// <summary>
/// Gets a remote handle on the service. If service is available locally,
/// then local instance is returned, otherwise, a remote proxy is dynamically
/// created and provided for the specified service.
/// </summary>
/// <typeparam name="T">Service type.</typeparam>
/// <param name="name">Service name.</param>
/// <param name="sticky">Whether or not Ignite should always contact the same remote
/// service or try to load-balance between services.</param>
/// <returns>Either proxy over remote service or local service if it is deployed locally.</returns>
T GetServiceProxy<T>(string name, bool sticky) where T : class;
/// <summary>
/// Gets a remote handle on the service with the specified caller context.
/// The proxy is dynamically created and provided for the specified service.
/// </summary>
/// <typeparam name="T">Service type.</typeparam>
/// <param name="name">Service name.</param>
/// <param name="sticky">Whether or not Ignite should always contact the same remote
/// service or try to load-balance between services.</param>
/// <param name="callCtx">Service call context.</param>
/// <returns>Proxy over service.</returns>
/// <seealso cref="IServiceCallContext"/>
[IgniteExperimental]
T GetServiceProxy<T>(string name, bool sticky, IServiceCallContext callCtx) where T : class;
/// <summary>
/// Gets a remote handle on the service as a dynamic object. If service is available locally,
/// then local instance is returned, otherwise, a remote proxy is dynamically
/// created and provided for the specified service.
/// <para />
/// This method utilizes <c>dynamic</c> feature of the language and does not require any
/// service interfaces or classes. Java services can be accessed as well as .NET services.
/// </summary>
/// <param name="name">Service name.</param>
/// <returns>Either proxy over remote service or local service if it is deployed locally.</returns>
dynamic GetDynamicServiceProxy(string name);
/// <summary>
/// Gets a remote handle on the service as a dynamic object. If service is available locally,
/// then local instance is returned, otherwise, a remote proxy is dynamically
/// created and provided for the specified service.
/// <para />
/// This method utilizes <c>dynamic</c> feature of the language and does not require any
/// service interfaces or classes. Java services can be accessed as well as .NET services.
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="sticky">Whether or not Ignite should always contact the same remote
/// service or try to load-balance between services.</param>
/// <returns>Either proxy over remote service or local service if it is deployed locally.</returns>
dynamic GetDynamicServiceProxy(string name, bool sticky);
/// <summary>
/// Gets a remote handle on the service with the specified caller context.
/// The proxy is dynamically created and provided for the specified service.
/// <para />
/// This method utilizes <c>dynamic</c> feature of the language and does not require any
/// service interfaces or classes. Java services can be accessed as well as .NET services.
/// </summary>
/// <param name="name">Service name.</param>
/// <param name="sticky">Whether or not Ignite should always contact the same remote
/// service or try to load-balance between services.</param>
/// <param name="callCtx">Service call context.</param>
/// <returns>Proxy over service.</returns>
/// <seealso cref="IServiceCallContext"/>
[IgniteExperimental]
dynamic GetDynamicServiceProxy(string name, bool sticky, IServiceCallContext callCtx);
/// <summary>
/// Returns an instance with binary mode enabled.
/// Service method results will be kept in binary form.
/// </summary>
/// <returns>Instance with binary mode enabled.</returns>
IServices WithKeepBinary();
/// <summary>
/// Returns an instance with server-side binary mode enabled.
/// Service method arguments will be kept in binary form.
/// </summary>
/// <returns>Instance with server-side binary mode enabled.</returns>
IServices WithServerKeepBinary();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Buffers.Text;
using static System.Runtime.InteropServices.MemoryMarshal;
namespace System.Text.Http.Parser.Internal
{
internal static class HttpUtilities
{
public const string Http10Version = "HTTP/1.0";
public const string Http11Version = "HTTP/1.1";
public const string HttpUriScheme = "http://";
public const string HttpsUriScheme = "https://";
// readonly primitive statics can be Jit'd to consts https://github.com/dotnet/coreclr/issues/1079
private readonly static ulong _httpSchemeLong = GetAsciiStringAsLong(HttpUriScheme + "\0");
private readonly static ulong _httpsSchemeLong = GetAsciiStringAsLong(HttpsUriScheme);
private readonly static ulong _httpConnectMethodLong = GetAsciiStringAsLong("CONNECT ");
private readonly static ulong _httpDeleteMethodLong = GetAsciiStringAsLong("DELETE \0");
private const uint _httpGetMethodInt = 542393671; // retun of GetAsciiStringAsInt("GET "); const results in better codegen
private readonly static ulong _httpHeadMethodLong = GetAsciiStringAsLong("HEAD \0\0\0");
private readonly static ulong _httpPatchMethodLong = GetAsciiStringAsLong("PATCH \0\0");
private readonly static ulong _httpPostMethodLong = GetAsciiStringAsLong("POST \0\0\0");
private readonly static ulong _httpPutMethodLong = GetAsciiStringAsLong("PUT \0\0\0\0");
private readonly static ulong _httpOptionsMethodLong = GetAsciiStringAsLong("OPTIONS ");
private readonly static ulong _httpTraceMethodLong = GetAsciiStringAsLong("TRACE \0\0");
private const ulong _http10VersionLong = 3471766442030158920; // GetAsciiStringAsLong("HTTP/1.0"); const results in better codegen
private const ulong _http11VersionLong = 3543824036068086856; // GetAsciiStringAsLong("HTTP/1.1"); const results in better codegen
private readonly static ulong _mask8Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
private readonly static ulong _mask7Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 });
private readonly static ulong _mask6Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00 });
private readonly static ulong _mask5Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00 });
private readonly static ulong _mask4Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 });
private readonly static Tuple<ulong, ulong, Http.Method, int>[] _knownMethods =
{
Tuple.Create(_mask4Chars, _httpPutMethodLong, Http.Method.Put, 3),
Tuple.Create(_mask5Chars, _httpPostMethodLong, Http.Method.Post, 4),
Tuple.Create(_mask5Chars, _httpHeadMethodLong, Http.Method.Head, 4),
Tuple.Create(_mask6Chars, _httpTraceMethodLong, Http.Method.Trace, 5),
Tuple.Create(_mask6Chars, _httpPatchMethodLong, Http.Method.Patch, 5),
Tuple.Create(_mask7Chars, _httpDeleteMethodLong, Http.Method.Delete, 6),
Tuple.Create(_mask8Chars, _httpConnectMethodLong, Http.Method.Connect, 7),
Tuple.Create(_mask8Chars, _httpOptionsMethodLong, Http.Method.Options, 7),
};
private readonly static string[] _methodNames = CreateMethodNames();
private static string[] CreateMethodNames()
{
var methodNames = new string[9];
methodNames[(byte)Http.Method.Get] = "GET";
methodNames[(byte)Http.Method.Put] = "PUT";
methodNames[(byte)Http.Method.Delete] = "DELETE";
methodNames[(byte)Http.Method.Post] = "POST";
methodNames[(byte)Http.Method.Head] = "HEAD";
methodNames[(byte)Http.Method.Trace] = "TRACE";
methodNames[(byte)Http.Method.Patch] = "PATCH";
methodNames[(byte)Http.Method.Connect] = "CONNECT";
methodNames[(byte)Http.Method.Options] = "OPTIONS";
return methodNames;
}
private static ulong GetAsciiStringAsLong(string str)
{
Debug.Assert(str.Length == 8, "String must be exactly 8 (ASCII) characters long.");
Span<byte> span = stackalloc byte[8];
Encodings.Utf16.ToUtf8(AsBytes(str.AsSpan()), span, out int consumed, out int written);
return Read<ulong>(span);
}
private static uint GetAsciiStringAsInt(string str)
{
Debug.Assert(str.Length == 4, "String must be exactly 4 (ASCII) characters long.");
Span<byte> span = stackalloc byte[4];
Encodings.Utf16.ToUtf8(AsBytes(str.AsSpan()), span, out int consumed, out int written);
return Read<uint>(span);
}
private unsafe static ulong GetMaskAsLong(byte[] bytes)
{
Debug.Assert(bytes.Length == 8, "Mask must be exactly 8 bytes long.");
fixed (byte* ptr = bytes)
{
return *(ulong*)ptr;
}
}
public unsafe static string GetAsciiStringNonNullCharacters(this Span<byte> span)
{
if (span.IsEmpty)
{
return string.Empty;
}
var asciiString = new string('\0', span.Length);
fixed (char* output = asciiString)
fixed (byte* buffer = &MemoryMarshal.GetReference(span))
{
// This version if AsciiUtilities returns null if there are any null (0 byte) characters
// in the string
if (!AsciiUtilities.TryGetAsciiString(buffer, output, span.Length))
{
throw new InvalidOperationException();
}
}
return asciiString;
}
public static string GetAsciiStringEscaped(this Span<byte> span, int maxChars)
{
var sb = new StringBuilder();
for (var i = 0; i < Math.Min(span.Length, maxChars); i++)
{
var ch = span[i];
sb.Append(ch < 0x20 || ch >= 0x7F ? $"\\x{ch:X2}" : ((char)ch).ToString());
}
if (span.Length > maxChars)
{
sb.Append("...");
}
return sb.ToString();
}
/// <summary>
/// Checks that up to 8 bytes from <paramref name="span"/> correspond to a known HTTP method.
/// </summary>
/// <remarks>
/// A "known HTTP method" can be an HTTP method name defined in the HTTP/1.1 RFC.
/// Since all of those fit in at most 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known method.
/// The Known Methods (CONNECT, DELETE, GET, HEAD, PATCH, POST, PUT, OPTIONS, TRACE) are all less than 8 bytes
/// and will be compared with the required space. A mask is used if the Known method is less than 8 bytes.
/// To optimize performance the GET method will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool GetKnownMethod(this Span<byte> span, out Http.Method method, out int length)
{
fixed (byte* data = &MemoryMarshal.GetReference(span))
{
method = GetKnownMethod(data, span.Length, out length);
return method != Http.Method.Custom;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe static Http.Method GetKnownMethod(byte* data, int length, out int methodLength)
{
methodLength = 0;
if (length < sizeof(uint))
{
return Http.Method.Custom;
}
else if (*(uint*)data == _httpGetMethodInt)
{
methodLength = 3;
return Http.Method.Get;
}
else if (length < sizeof(ulong))
{
return Http.Method.Custom;
}
else
{
var value = *(ulong*)data;
foreach (var x in _knownMethods)
{
if ((value & x.Item1) == x.Item2)
{
methodLength = x.Item4;
return x.Item3;
}
}
}
return Http.Method.Custom;
}
/// <summary>
/// Checks 9 bytes from <paramref name="span"/> correspond to a known HTTP version.
/// </summary>
/// <remarks>
/// A "known HTTP version" Is is either HTTP/1.0 or HTTP/1.1.
/// Since those fit in 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known versions.
/// The Known versions will be checked with the required '\r'.
/// To optimize performance the HTTP/1.1 will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool GetKnownVersion(this Span<byte> span, out Http.Version knownVersion, out byte length)
{
fixed (byte* data = &MemoryMarshal.GetReference(span))
{
knownVersion = GetKnownVersion(data, span.Length);
if (knownVersion != Http.Version.Unknown)
{
length = sizeof(ulong);
return true;
}
length = 0;
return false;
}
}
/// <summary>
/// Checks 9 bytes from <paramref name="location"/> correspond to a known HTTP version.
/// </summary>
/// <remarks>
/// A "known HTTP version" Is is either HTTP/1.0 or HTTP/1.1.
/// Since those fit in 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known versions.
/// The Known versions will be checked with the required '\r'.
/// To optimize performance the HTTP/1.1 will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe static Http.Version GetKnownVersion(byte* location, int length)
{
Http.Version knownVersion;
var version = *(ulong*)location;
if (length < sizeof(ulong) + 1 || location[sizeof(ulong)] != (byte)'\r')
{
knownVersion = Http.Version.Unknown;
}
else if (version == _http11VersionLong)
{
knownVersion = Http.Version.Http11;
}
else if (version == _http10VersionLong)
{
knownVersion = Http.Version.Http10;
}
else
{
knownVersion = Http.Version.Unknown;
}
return knownVersion;
}
/// <summary>
/// Checks 8 bytes from <paramref name="span"/> that correspond to 'http://' or 'https://'
/// </summary>
/// <param name="span">The span</param>
/// <param name="knownScheme">A reference to the known scheme, if the input matches any</param>
/// <returns>True when memory starts with known http or https schema</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool GetKnownHttpScheme(this Span<byte> span, out HttpScheme knownScheme)
{
fixed (byte* data = &MemoryMarshal.GetReference(span))
{
return GetKnownHttpScheme(data, span.Length, out knownScheme);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe bool GetKnownHttpScheme(byte* location, int length, out HttpScheme knownScheme)
{
if (length >= sizeof(ulong))
{
var scheme = *(ulong*)location;
if ((scheme & _mask7Chars) == _httpSchemeLong)
{
knownScheme = HttpScheme.Http;
return true;
}
if (scheme == _httpsSchemeLong)
{
knownScheme = HttpScheme.Https;
return true;
}
}
knownScheme = HttpScheme.Unknown;
return false;
}
public static string VersionToString(Http.Version httpVersion)
{
switch (httpVersion)
{
case Http.Version.Http10:
return Http10Version;
case Http.Version.Http11:
return Http11Version;
default:
return null;
}
}
public static string MethodToString(Http.Method method)
{
int methodIndex = (int)method;
if (methodIndex >= 0 && methodIndex <= 8)
{
return _methodNames[methodIndex];
}
return null;
}
public static string SchemeToString(HttpScheme scheme)
{
switch (scheme)
{
case HttpScheme.Http:
return HttpUriScheme;
case HttpScheme.Https:
return HttpsUriScheme;
default:
return null;
}
}
}
}
| |
using System;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Contract details returned from Interactive Brokers
/// </summary>
[Serializable()]
public class ContractDetails
{
#region Private Variables
private String marketName;
private double minTick;
private String orderTypes;
private int priceMagnifier;
private Contract summary;
private String tradingClass;
private String validExchanges;
private int underConId;
private String longName;
private String contractMonth;
private String industry;
private String category;
private String subcategory;
private String timeZoneId;
private String tradingHours;
private String liquidHours;
// BOND values
private String cusip;
private String ratings;
private String descriptionAppend;
private String bondType;
private String couponType;
private bool callable;
private bool putable;
private double coupon;
private bool convertible;
private String maturity;
private String issueDate;
private String nextOptionDate;
private String nextOptionType;
private bool nextOptionPartial;
private String notes;
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public ContractDetails() :
this(new Contract(), null, null, 0, null, null, 0, null, null, null, null, null, null, null, null)
{
}
/// <summary>
/// Full Constructor
/// </summary>
/// <param name="summary">A contract summary.</param>
/// <param name="marketName">The market name for this contract.</param>
/// <param name="tradingClass">The trading class name for this contract.</param>
/// <param name="minTick">The minimum price tick.</param>
/// <param name="orderTypes">The list of valid order types for this contract.</param>
/// <param name="validExchanges">The list of exchanges this contract is traded on.</param>
/// <param name="underConId">The Underlying Contract Id (for derivatives only)</param>
/// <param name="longName">Long Name</param>
/// <param name="contractMonth">The contract month. Typically the contract month of the underlying for a futures contract.</param>
/// <param name="industry">The industry classification of the underlying/product. For example, Financial.</param>
/// <param name="category">The industry category of the underlying. For example, InvestmentSvc.</param>
/// <param name="subcategory">The industry subcategory of the underlying. For example, Brokerage.</param>
/// <param name="timeZoneId">The ID of the time zone for the trading hours of the product. For example, EST.</param>
/// <param name="tradingHours">The trading hours of the product. For example, 20090507:0700-1830,1830-2330;20090508:CLOSED.</param>
/// <param name="liquidHours">The liquid trading hours of the product. For example, 20090507:0930-1600;20090508:CLOSED.</param>
public ContractDetails(Contract summary, String marketName, String tradingClass, double minTick,
String orderTypes, String validExchanges, int underConId, String longName,
String contractMonth, String industry, String category, String subcategory,
String timeZoneId, String tradingHours, String liquidHours)
{
this.summary = summary;
this.marketName = marketName;
this.tradingClass = tradingClass;
this.minTick = minTick;
this.orderTypes = orderTypes;
this.validExchanges = validExchanges;
this.underConId = underConId;
this.longName = longName;
this.contractMonth = contractMonth;
this.industry = industry;
this.category = category;
this.subcategory = subcategory;
this.timeZoneId = timeZoneId;
this.tradingHours = tradingHours;
this.liquidHours = liquidHours;
}
#endregion
#region Properties
/// <summary>
/// A contract summary.
/// </summary>
public Contract Summary
{
get { return summary; }
set { summary = value; }
}
/// <summary>
/// The market name for this contract.
/// </summary>
public string MarketName
{
get { return marketName; }
set { marketName = value; }
}
/// <summary>
/// The trading class name for this contract.
/// </summary>
public string TradingClass
{
get { return tradingClass; }
set { tradingClass = value; }
}
/// <summary>
/// The minimum price tick.
/// </summary>
public double MinTick
{
get { return minTick; }
set { minTick = value; }
}
/// <summary>
/// Allows execution and strike prices to be reported consistently with
/// market data, historical data and the order price, i.e. Z on LIFFE is
/// reported in index points and not GBP.
/// </summary>
public int PriceMagnifier
{
get { return priceMagnifier; }
set { priceMagnifier = value; }
}
/// <summary>
/// The list of valid order types for this contract.
/// </summary>
public string OrderTypes
{
get { return orderTypes; }
set { orderTypes = value; }
}
/// <summary>
/// The list of exchanges this contract is traded on.
/// </summary>
public string ValidExchanges
{
get { return validExchanges; }
set { validExchanges = value; }
}
/// <summary>
/// Underlying Contract Id
/// underConId (underlying contract ID), has been added to the
/// ContractDetails structure to allow unambiguous identification with the underlying contract
/// (you no longer have to match by symbol, etc.). This new field applies to derivatives only.
/// </summary>
public int UnderConId
{
get { return underConId; }
set { underConId = value; }
}
/// <summary>
/// For Bonds. The nine-character bond CUSIP or the 12-character SEDOL.
/// </summary>
public string Cusip
{
get { return cusip; }
set { cusip = value; }
}
/// <summary>
/// For Bonds. Identifies the credit rating of the issuer. A higher credit
/// rating generally indicates a less risky investment. Bond ratings
/// are from Moody's and SP respectively.
/// </summary>
public string Ratings
{
get { return ratings; }
set { ratings = value; }
}
/// <summary>
/// For Bonds. A description string containing further descriptive information about the bond.
/// </summary>
public string DescriptionAppend
{
get { return descriptionAppend; }
set { descriptionAppend = value; }
}
/// <summary>
/// For Bonds. The type of bond, such as "CORP."
/// </summary>
public string BondType
{
get { return bondType; }
set { bondType = value; }
}
/// <summary>
/// For Bonds. The type of bond coupon, such as "FIXED."
/// </summary>
public string CouponType
{
get { return couponType; }
set { couponType = value; }
}
/// <summary>
/// For Bonds. Values are True or False. If true, the bond can be called
/// by the issuer under certain conditions.
/// </summary>
public bool Callable
{
get { return callable; }
set { callable = value; }
}
/// <summary>
/// For Bonds. Values are True or False. If true, the bond can be sold
/// back to the issuer under certain conditions.
/// </summary>
public bool Putable
{
get { return putable; }
set { putable = value; }
}
/// <summary>
/// For Bonds. The interest rate used to calculate the amount you will
/// receive in interest payments over the course of the year.
/// </summary>
public double Coupon
{
get { return coupon; }
set { coupon = value; }
}
/// <summary>
/// For Bonds. Values are True or False.
/// If true, the bond can be converted to stock under certain conditions.
/// </summary>
public bool Convertible
{
get { return convertible; }
set { convertible = value; }
}
/// <summary>
/// For Bonds. The date on which the issuer must repay the face value of the bond.
/// </summary>
public string Maturity
{
get { return maturity; }
set { maturity = value; }
}
/// <summary>
/// For Bonds. The date the bond was issued.
/// </summary>
public string IssueDate
{
get { return issueDate; }
set { issueDate = value; }
}
/// <summary>
/// For Bonds, relevant if the bond has embedded options
/// </summary>
public string NextOptionDate
{
get { return nextOptionDate; }
set { nextOptionDate = value; }
}
/// <summary>
/// For Bonds, relevant if the bond has embedded options
/// </summary>
public string NextOptionType
{
get { return nextOptionType; }
set { nextOptionType = value; }
}
/// <summary>
/// For Bonds, relevant if the bond has embedded options, i.e., is the next option full or partial?
/// </summary>
public bool NextOptionPartial
{
get { return nextOptionPartial; }
set { nextOptionPartial = value; }
}
/// <summary>
/// For Bonds, if populated for the bond in IBs database
/// </summary>
public string Notes
{
get { return notes; }
set { notes = value; }
}
/// <summary>
/// Long Name
/// </summary>
public String LongName
{
get { return longName; }
set { longName = value; }
}
/// <summary>
/// The contract month. Typically the contract month of the underlying for a futures contract.
/// </summary>
public String ContractMonth
{
get { return contractMonth; }
set { contractMonth = value; }
}
/// <summary>
/// The industry classification of the underlying/product. For example, Financial.
/// </summary>
public String Industry
{
get { return industry; }
set { industry = value; }
}
/// <summary>
/// The industry category of the underlying. For example, InvestmentSvc.
/// </summary>
public String Category
{
get { return category; }
set { category = value; }
}
/// <summary>
/// The industry subcategory of the underlying. For example, Brokerage.
/// </summary>
public String Subcategory
{
get { return subcategory; }
set { subcategory = value; }
}
/// <summary>
/// The ID of the time zone for the trading hours of the product. For example, EST.
/// </summary>
public String TimeZoneId
{
get { return timeZoneId; }
set { timeZoneId = value; }
}
/// <summary>
/// The trading hours of the product. For example, 20090507:0700-1830,1830-2330;20090508:CLOSED.
/// </summary>
public String TradingHours
{
get { return tradingHours; }
set { tradingHours = value; }
}
/// <summary>
/// The liquid trading hours of the product. For example, 20090507:0930-1600;20090508:CLOSED.
/// </summary>
public String LiquidHours
{
get { return liquidHours; }
set { liquidHours = value; }
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Diagnostics;
using mshtml;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.Mshtml;
namespace OpenLiveWriter.PostEditor.Tables
{
internal class TableSelection
{
public TableSelection(MarkupRange markupRange)
{
// calculate the begin and end cells
IHTMLTableCell beginCell;
IHTMLTableCell endCell;
ArrayList selectedCells;
FindCellRange(markupRange, out selectedCells, out beginCell, out endCell);
// see if the two cells have a single containing table
IHTMLTable table = GetSelectedTable(beginCell, endCell, markupRange) as IHTMLTable;
// if we have a table then calculate the rest of our states
if (table != null)
{
// validate the table selection
if (ValidateTableSelection(table, markupRange, out _entireTableSelected))
{
_table = table;
_beginCell = beginCell;
_endCell = endCell;
// filter selected cells to only include direct descendents of this table (no
// cells from nested tables)
_selectedCells = new ArrayList();
foreach (IHTMLElement cell in selectedCells)
if (HTMLElementHelper.ElementsAreEqual(TableHelper.GetContainingTableElement(cell) as IHTMLElement, _table as IHTMLElement))
_selectedCells.Add(cell);
_hasContiguousSelection = !HTMLElementHelper.ElementsAreEqual(_beginCell as IHTMLElement, _endCell as IHTMLElement);
_beginRow = GetContainingRowForCell(beginCell);
_endRow = GetContainingRowForCell(endCell);
_beginColumn = new HTMLTableColumn(_table, beginCell);
_endColumn = new HTMLTableColumn(_table, endCell);
}
}
}
public bool HasContiguousSelection
{
get { return _hasContiguousSelection; }
}
private bool _hasContiguousSelection = false;
public IHTMLTable Table
{
get { return _table; }
}
private IHTMLTable _table = null;
public bool EntireTableSelected
{
get { return _entireTableSelected; }
}
private bool _entireTableSelected;
public IHTMLTableCell BeginCell
{
get { return _beginCell; }
}
private IHTMLTableCell _beginCell;
public IHTMLTableCell EndCell
{
get { return _endCell; }
}
private IHTMLTableCell _endCell;
public ArrayList SelectedCells
{
get { return _selectedCells; }
}
private ArrayList _selectedCells = new ArrayList();
public bool SelectionSpansAllCells
{
get
{
return (_table as IHTMLTable2).cells.length == SelectedCells.Count;
}
}
public IHTMLTableRow BeginRow
{
get { return _beginRow; }
}
private IHTMLTableRow _beginRow = null;
public IHTMLTableRow EndRow
{
get { return _endRow; }
}
private IHTMLTableRow _endRow = null;
public bool SingleRowSelected
{
get { return HTMLElementHelper.ElementsAreEqual(_beginRow as IHTMLElement, _endRow as IHTMLElement); }
}
public HTMLTableColumn BeginColumn
{
get { return _beginColumn; }
}
private HTMLTableColumn _beginColumn = null;
public HTMLTableColumn EndColumn
{
get { return _endColumn; }
}
private HTMLTableColumn _endColumn = null;
public bool SingleColumnSelected
{
get { return !HasContiguousSelection; }
}
private void FindCellRange(MarkupRange selectedRange, out ArrayList selectedCells, out IHTMLTableCell beginCell, out IHTMLTableCell endCell)
{
// default to null
beginCell = null;
endCell = null;
selectedCells = new ArrayList();
// JJA: fix bug #476623 -- at document initialization the selected markup range
// may not yet be positioned so protect ourselves in this case
if (!selectedRange.Positioned)
return;
// query for all of the table cells within the range
selectedCells.AddRange(selectedRange.GetElements(ElementFilters.TABLE_CELL_ELEMENT, false));
// extract the begin and end cells
if (selectedCells.Count == 0)
{
// see if the selection is contained within a single cell
beginCell = selectedRange.Start.GetParentElement(ElementFilters.TABLE_CELL_ELEMENT) as IHTMLTableCell;
if (beginCell != null)
{
// make sure the cell is content editable (it would not be in the case
// where the call to GetParentElement went all the way out of the body
// and found a cell that was part of the containing template)
if (!(beginCell as IHTMLElement3).isContentEditable)
beginCell = null;
}
endCell = beginCell;
selectedCells.Add(beginCell);
}
else if (selectedCells.Count == 1)
{
beginCell = selectedCells[0] as IHTMLTableCell;
endCell = selectedCells[0] as IHTMLTableCell;
}
else
{
beginCell = selectedCells[0] as IHTMLTableCell;
endCell = selectedCells[selectedCells.Count - 1] as IHTMLTableCell;
}
}
private IHTMLElement GetSelectedTable(IHTMLTableCell beginCell, IHTMLTableCell endCell, MarkupRange selectionMarkupRange)
{
// screen null cases
if (beginCell == null || endCell == null)
return null;
// get containing tables
IHTMLTable beginTable = TableHelper.GetContainingTableElement(beginCell as IHTMLElement);
IHTMLTable endTable = TableHelper.GetContainingTableElement(endCell as IHTMLElement);
// see if they are from the same table
if (HTMLElementHelper.ElementsAreEqual(beginTable as IHTMLElement, endTable as IHTMLElement))
{
return beginTable as IHTMLElement;
}
else
return null;
}
private IHTMLTableRow GetContainingRowForCell(IHTMLTableCell tableCell)
{
// search up the parent heirarchy
IHTMLElement element = tableCell as IHTMLElement;
while (element != null)
{
if (element is IHTMLTableRow)
{
return element as IHTMLTableRow;
}
// search parent
element = element.parentElement;
}
// didn't find a row
return null;
}
private bool ValidateTableSelection(IHTMLTable table, MarkupRange selectionMarkupRange, out bool tableFullySelected)
{
// assume table is not fully selected
tableFullySelected = false;
// first check to see that this is a "Writer" editable table
if (!TableHelper.TableElementContainsWriterEditingMark(table as IHTMLElement))
return false;
// get elemental objects we need to analyze the table
IHTMLElement tableElement = table as IHTMLElement;
MarkupRange tableMarkupRange = selectionMarkupRange.Clone();
tableMarkupRange.MoveToElement(table as IHTMLElement, true);
// analyze selection
bool selectionAtTableStart = tableMarkupRange.Start.IsEqualTo(selectionMarkupRange.Start);
bool selectionAtTableEnd = tableMarkupRange.End.IsEqualTo(selectionMarkupRange.End);
// is the table fully selected?
if (selectionAtTableStart && selectionAtTableEnd)
{
tableFullySelected = true;
return true;
}
else
{
MarkupRange selectionMarkupRange2 = selectionMarkupRange.Clone();
// is the selection bounded by the table
IHTMLElement beginParentTable = selectionMarkupRange2.Start.SeekElementLeft(ElementFilters.CreateEqualFilter(tableElement));
IHTMLElement endParentTable = selectionMarkupRange2.End.SeekElementRight(ElementFilters.CreateEqualFilter(tableElement));
return beginParentTable != null && endParentTable != null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Versioning;
using NuGet.Resources;
using NuGet.V3Interop;
namespace NuGet
{
public static class PackageRepositoryExtensions
{
public static IDisposable StartOperation(this IPackageRepository self, string operation, string mainPackageId, string mainPackageVersion)
{
IOperationAwareRepository repo = self as IOperationAwareRepository;
if (repo != null)
{
return repo.StartOperation(operation, mainPackageId, mainPackageVersion);
}
return DisposableAction.NoOp;
}
public static bool Exists(this IPackageRepository repository, IPackageName package)
{
return repository.Exists(package.Id, package.Version);
}
public static bool Exists(this IPackageRepository repository, string packageId)
{
return Exists(repository, packageId, version: null);
}
public static bool Exists(this IPackageRepository repository, string packageId, SemanticVersion version)
{
IPackageLookup packageLookup = repository as IPackageLookup;
if ((packageLookup != null) && !String.IsNullOrEmpty(packageId) && (version != null))
{
return packageLookup.Exists(packageId, version);
}
return repository.FindPackage(packageId, version) != null;
}
public static bool TryFindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, out IPackage package)
{
package = repository.FindPackage(packageId, version);
return package != null;
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId)
{
return repository.FindPackage(packageId, version: null);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version)
{
// Default allow pre release versions to true here because the caller typically wants to find all packages in this scenario for e.g when checking if a
// a package is already installed in the local repository. The same applies to allowUnlisted.
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions: true, allowUnlisted: true);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, bool allowPrereleaseVersions, bool allowUnlisted)
{
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions, allowUnlisted);
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
SemanticVersion version,
IPackageConstraintProvider constraintProvider,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
// if an explicit version is specified, disregard the 'allowUnlisted' argument
// and always allow unlisted packages.
if (version != null)
{
allowUnlisted = true;
}
else if (!allowUnlisted && (constraintProvider == null || constraintProvider == NullConstraintProvider.Instance))
{
var packageLatestLookup = repository as ILatestPackageLookup;
if (packageLatestLookup != null)
{
IPackage package;
if (packageLatestLookup.TryFindLatestPackageById(packageId, allowPrereleaseVersions, out package))
{
return package;
}
}
}
// If the repository implements it's own lookup then use that instead.
// This is an optimization that we use so we don't have to enumerate packages for
// sources that don't need to.
var packageLookup = repository as IPackageLookup;
if (packageLookup != null && version != null)
{
return packageLookup.FindPackage(packageId, version);
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId);
packages = packages.ToList()
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (version != null)
{
packages = packages.Where(p => p.Version == version);
}
else if (constraintProvider != null)
{
packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionSpec,
IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted)
{
var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted);
if (constraintProvider != null)
{
packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds)
{
if (packageIds == null)
{
throw new ArgumentNullException("packageIds");
}
// If we're in V3-land, find packages using that API
var v3Repo = repository as IV3InteropRepository;
if (v3Repo != null)
{
return packageIds.SelectMany(id => v3Repo.FindPackagesById(id)).ToList();
}
else
{
return FindPackages(repository, packageIds, GetFilterExpression);
}
}
public static IEnumerable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId)
{
var directRepo = repository as IV3InteropRepository;
if (directRepo != null)
{
return directRepo.FindPackagesById(packageId);
}
var serviceBasedRepository = repository as IPackageLookup;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.FindPackagesById(packageId).ToList();
}
else
{
return FindPackagesByIdCore(repository, packageId);
}
}
internal static IEnumerable<IPackage> FindPackagesByIdCore(IPackageRepository repository, string packageId)
{
var cultureRepository = repository as ICultureAwareRepository;
if (cultureRepository != null)
{
packageId = packageId.ToLower(cultureRepository.Culture);
}
else
{
packageId = packageId.ToLower(CultureInfo.CurrentCulture);
}
return (from p in repository.GetPackages()
where p.Id.ToLower() == packageId
orderby p.Id
select p).ToList();
}
/// <summary>
/// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of packages.
/// </summary>
private static IEnumerable<IPackage> FindPackages<T>(
this IPackageRepository repository,
IEnumerable<T> items,
Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector)
{
const int batchSize = 10;
while (items.Any())
{
IEnumerable<T> currentItems = items.Take(batchSize);
Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems);
var query = repository.GetPackages()
.Where(filterExpression)
.OrderBy(p => p.Id);
foreach (var package in query)
{
yield return package;
}
items = items.Skip(batchSize);
}
}
public static IEnumerable<IPackage> FindPackages(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId)
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (versionSpec != null)
{
packages = packages.FindByVersion(versionSpec);
}
packages = FilterPackagesByConstraints(NullConstraintProvider.Instance, packages, packageId, allowPrereleaseVersions);
return packages;
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
return repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted).FirstOrDefault();
}
public static IEnumerable<IPackage> FindCompatiblePackages(this IPackageRepository repository,
IPackageConstraintProvider constraintProvider,
IEnumerable<string> packageIds,
IPackage package,
FrameworkName targetFramework,
bool allowPrereleaseVersions)
{
return (from p in repository.FindPackages(packageIds)
where allowPrereleaseVersions || p.IsReleaseVersion()
let dependency = p.FindDependency(package.Id, targetFramework)
let otherConstaint = constraintProvider.GetConstraint(p.Id)
where dependency != null &&
dependency.VersionSpec.Satisfies(package.Version) &&
(otherConstaint == null || otherConstaint.Satisfies(package.Version))
select p);
}
public static PackageDependency FindDependency(this IPackageMetadata package, string packageId, FrameworkName targetFramework)
{
return (from dependency in package.GetCompatiblePackageDependencies(targetFramework)
where dependency.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)
select dependency).FirstOrDefault();
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, bool allowPrereleaseVersions)
{
return Search(repository, searchTerm, targetFrameworks: Enumerable.Empty<string>(), allowPrereleaseVersions: allowPrereleaseVersions);
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
if (targetFrameworks == null)
{
throw new ArgumentNullException("targetFrameworks");
}
var serviceBasedRepository = repository as IServiceBasedRepository;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.Search(searchTerm, targetFrameworks, allowPrereleaseVersions);
}
// Ignore the target framework if the repository doesn't support searching
var result = repository
.GetPackages()
.Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions)
.AsQueryable();
return result;
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, bool allowPrereleaseVersions, bool preferListedPackages)
{
return ResolveDependency(repository, dependency, constraintProvider: null, allowPrereleaseVersions: allowPrereleaseVersions, preferListedPackages: preferListedPackages, dependencyVersion: DependencyVersion.Lowest);
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages)
{
return ResolveDependency(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion: DependencyVersion.Lowest);
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages, DependencyVersion dependencyVersion)
{
IDependencyResolver dependencyResolver = repository as IDependencyResolver;
if (dependencyResolver != null)
{
return dependencyResolver.ResolveDependency(dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion);
}
return ResolveDependencyCore(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion);
}
internal static IPackage ResolveDependencyCore(
this IPackageRepository repository,
PackageDependency dependency,
IPackageConstraintProvider constraintProvider,
bool allowPrereleaseVersions,
bool preferListedPackages,
DependencyVersion dependencyVersion)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (dependency == null)
{
throw new ArgumentNullException("dependency");
}
IEnumerable<IPackage> packages = repository.FindPackagesById(dependency.Id).ToList();
// Always filter by constraints when looking for dependencies
packages = FilterPackagesByConstraints(constraintProvider, packages, dependency.Id, allowPrereleaseVersions);
IList<IPackage> candidates = packages.ToList();
if (preferListedPackages)
{
// pick among Listed packages first
IPackage listedSelectedPackage = ResolveDependencyCore(
candidates.Where(PackageExtensions.IsListed),
dependency,
dependencyVersion);
if (listedSelectedPackage != null)
{
return listedSelectedPackage;
}
}
return ResolveDependencyCore(candidates, dependency, dependencyVersion);
}
/// <summary>
/// From the list of packages <paramref name="packages"/>, selects the package that best
/// matches the <paramref name="dependency"/>.
/// </summary>
/// <param name="packages">The list of packages.</param>
/// <param name="dependency">The dependency used to select package from the list.</param>
/// <param name="dependencyVersion">Indicates the method used to select dependency.
/// Applicable only when dependency.VersionSpec is not null.</param>
/// <returns>The selected package.</returns>
private static IPackage ResolveDependencyCore(
IEnumerable<IPackage> packages,
PackageDependency dependency,
DependencyVersion dependencyVersion)
{
// If version info was specified then use it
if (dependency.VersionSpec != null)
{
packages = packages.FindByVersion(dependency.VersionSpec).OrderBy(p => p.Version);
return packages.SelectDependency(dependencyVersion);
}
else
{
// BUG 840: If no version info was specified then pick the latest
return packages.OrderByDescending(p => p.Version)
.FirstOrDefault();
}
}
/// <summary>
/// Returns updates for packages from the repository
/// </summary>
/// <param name="repository">The repository to search for updates</param>
/// <param name="packages">Packages to look for updates</param>
/// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
/// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
public static IEnumerable<IPackage> GetUpdates(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFrameworks = null,
IEnumerable<IVersionSpec> versionConstraints = null)
{
if (packages.IsEmpty())
{
return Enumerable.Empty<IPackage>();
}
var serviceBasedRepository = repository as IServiceBasedRepository;
return serviceBasedRepository != null ? serviceBasedRepository.GetUpdates(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints) :
repository.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints);
}
public static IEnumerable<IPackage> GetUpdatesCore(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFramework,
IEnumerable<IVersionSpec> versionConstraints)
{
List<IPackageName> packageList = packages.ToList();
if (!packageList.Any())
{
return Enumerable.Empty<IPackage>();
}
IList<IVersionSpec> versionConstraintList;
if (versionConstraints == null)
{
versionConstraintList = new IVersionSpec[packageList.Count];
}
else
{
versionConstraintList = versionConstraints.ToList();
}
if (packageList.Count != versionConstraintList.Count)
{
throw new ArgumentException(NuGetResources.GetUpdatesParameterMismatch);
}
// These are the packages that we need to look at for potential updates.
ILookup<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList, includePrerelease)
.ToList()
.ToLookup(package => package.Id, StringComparer.OrdinalIgnoreCase);
var results = new List<IPackage>();
for (int i = 0; i < packageList.Count; i++)
{
var package = packageList[i];
var constraint = versionConstraintList[i];
var updates = from candidate in sourcePackages[package.Id]
where (candidate.Version > package.Version) &&
SupportsTargetFrameworks(targetFramework, candidate) &&
(constraint == null || constraint.Satisfies(candidate.Version))
select candidate;
results.AddRange(updates);
}
if (!includeAllVersions)
{
return results.CollapseById();
}
return results;
}
private static bool SupportsTargetFrameworks(IEnumerable<FrameworkName> targetFramework, IPackage package)
{
return targetFramework.IsEmpty() || targetFramework.Any(t => VersionUtility.IsCompatible(t, package.GetSupportedFrameworks()));
}
public static IPackageRepository Clone(this IPackageRepository repository)
{
var cloneableRepository = repository as ICloneableRepository;
if (cloneableRepository != null)
{
return cloneableRepository.Clone();
}
return repository;
}
/// <summary>
/// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of candidates for updates.
/// </summary>
private static IEnumerable<IPackage> GetUpdateCandidates(
IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease)
{
var query = FindPackages(repository, packages, GetFilterExpression);
if (!includePrerelease)
{
query = query.Where(p => p.IsReleaseVersion());
}
// for updates, we never consider unlisted packages
query = query.Where(PackageExtensions.IsListed);
return query;
}
/// <summary>
/// For the list of input packages generate an expression like:
/// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n
/// </summary>
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackageName> packages)
{
return GetFilterExpression(packages.Select(p => p.Id));
}
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")]
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids)
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageName));
Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower()))
.Aggregate(Expression.OrElse);
return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression);
}
/// <summary>
/// Builds the expression: package.Id.ToLower() == "somepackageid"
/// </summary>
private static Expression GetCompareExpression(Expression parameterExpression, object value)
{
// package.Id
Expression propertyExpression = Expression.Property(parameterExpression, "Id");
// .ToLower()
Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes));
// == localPackage.Id
return Expression.Equal(toLowerExpression, Expression.Constant(value));
}
private static IEnumerable<IPackage> FilterPackagesByConstraints(
IPackageConstraintProvider constraintProvider,
IEnumerable<IPackage> packages,
string packageId,
bool allowPrereleaseVersions)
{
constraintProvider = constraintProvider ?? NullConstraintProvider.Instance;
// Filter packages by this constraint
IVersionSpec constraint = constraintProvider.GetConstraint(packageId);
if (constraint != null)
{
packages = packages.FindByVersion(constraint);
}
if (!allowPrereleaseVersions)
{
packages = packages.Where(p => p.IsReleaseVersion());
}
return packages;
}
/// <summary>
/// Selects the dependency package from the list of candidate packages
/// according to <paramref name="dependencyVersion"/>.
/// </summary>
/// <param name="packages">The list of candidate packages.</param>
/// <param name="dependencyVersion">The rule used to select the package from
/// <paramref name="packages"/> </param>
/// <returns>The selected package.</returns>
/// <remarks>Precondition: <paramref name="packages"/> are ordered by ascending version.</remarks>
internal static IPackage SelectDependency(this IEnumerable<IPackage> packages, DependencyVersion dependencyVersion)
{
if (packages == null || !packages.Any())
{
return null;
}
if (dependencyVersion == DependencyVersion.Lowest)
{
return packages.FirstOrDefault();
}
else if (dependencyVersion == DependencyVersion.Highest)
{
return packages.LastOrDefault();
}
else if (dependencyVersion == DependencyVersion.HighestPatch)
{
var groups = from p in packages
group p by new { p.Version.Version.Major, p.Version.Version.Minor } into g
orderby g.Key.Major, g.Key.Minor
select g;
return (from p in groups.First()
orderby p.Version descending
select p).FirstOrDefault();
}
else if (dependencyVersion == DependencyVersion.HighestMinor)
{
var groups = from p in packages
group p by new { p.Version.Version.Major } into g
orderby g.Key.Major
select g;
return (from p in groups.First()
orderby p.Version descending
select p).FirstOrDefault();
}
throw new ArgumentOutOfRangeException("dependencyVersion");
}
}
}
| |
namespace Nancy.Tests.Functional.Tests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Nancy.Cookies;
using Nancy.ErrorHandling;
using Nancy.IO;
using Nancy.Responses.Negotiation;
using Nancy.Testing;
using Nancy.Tests.Functional.Modules;
using Nancy.Tests.xUnitExtensions;
using Xunit;
using Xunit.Extensions;
public class ContentNegotiationFixture
{
[Fact]
public async Task Should_return_int_value_from_get_route_as_response_with_status_code_set_to_value()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/int", (x,m) => 200);
});
var browser = new Browser(with =>
{
with.Module(module);
});
// When
var response = await browser.Get("/int");
// Then
Assert.Equal((HttpStatusCode)200, response.StatusCode);
}
[Fact]
public async Task Should_return_string_value_from_get_route_as_response_with_content_set_as_value()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/string", (x, m) => "hello");
});
var browser = new Browser(with =>
{
with.Module(module);
});
// When
var response = await browser.Get("/string");
// Then
Assert.Equal("hello", response.Body.AsString());
}
[Fact]
public async Task Should_return_httpstatuscode_value_from_get_route_as_response_with_content_set_as_value()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/httpstatuscode", (x, m) => HttpStatusCode.Accepted);
});
var browser = new Browser(with =>
{
with.Module(module);
});
// When
var response = await browser.Get("/httpstatuscode");
// Then
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
}
[Fact]
public async Task Should_return_action_value_as_response_with_content_set_as_value()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/action", (x, m) =>
{
Action<Stream> result = stream =>
{
var wrapper = new UnclosableStreamWrapper(stream);
using (var writer = new StreamWriter(wrapper))
{
writer.Write("Hiya Nancy!");
}
};
return result;
});
});
var browser = new Browser(with =>
{
with.Module(module);
});
// When
var response = await browser.Get("/action");
// Then
Assert.Equal("Hiya Nancy!", response.Body.AsString());
}
[Fact]
public async Task Should_add_negotiated_headers_to_response()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/headers", (x, m) =>
{
var context =
new NancyContext();
var negotiator =
new Negotiator(context);
negotiator.WithHeader("foo", "bar");
return negotiator;
});
});
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(module);
});
// When
var response = await browser.Get("/headers");
// Then
Assert.True(response.Headers.ContainsKey("foo"));
Assert.Equal("bar", response.Headers["foo"]);
}
[Fact]
public async Task Should_set_reason_phrase_on_response()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/customPhrase", (x, m) =>
{
var context =
new NancyContext();
var negotiator =
new Negotiator(context);
negotiator.WithReasonPhrase("The test is passing!").WithStatusCode(404);
return negotiator;
});
});
var browser = new Browser(with =>
{
with.StatusCodeHandler<DefaultStatusCodeHandler>();
with.ResponseProcessor<TestProcessor>();
with.Module(module);
});
// When
var response = await browser.Get("/customPhrase");
// Then
Assert.Equal("The test is passing!", response.ReasonPhrase);
}
[Fact]
public async Task Should_add_negotiated_content_headers_to_response()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/headers", (x, m) =>
{
var context =
new NancyContext();
var negotiator =
new Negotiator(context);
negotiator.WithContentType("text/xml");
return negotiator;
});
});
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(module);
});
// When
var response = await browser.Get("/headers");
// Then
Assert.Equal("text/xml", response.Context.Response.ContentType);
}
[Fact]
public async Task Should_apply_default_accept_when_no_accept_header_sent()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", (parameters, module) =>
{
var context =
new NancyContext();
var negotiator =
new Negotiator(context);
return negotiator;
});
}));
});
// When
var response = await browser.Get("/");
// Then
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task Should_boost_html_priority_if_set_to_the_same_priority_as_others()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", (parameters, module) =>
{
var context =
new NancyContext();
var negotiator =
new Negotiator(context);
negotiator.WithAllowedMediaRange("application/xml");
negotiator.WithAllowedMediaRange("text/html");
return negotiator;
});
}));
});
// When
var response = await browser.Get("/", with =>
{
with.Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru-RU) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4");
with.Accept("application/xml", 0.9m);
with.Accept("text/html", 0.9m);
});
// Then
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(response.Body.AsString().Contains("text/html"), "Media type mismatch");
}
[Fact]
public async Task Should_override_with_extension()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/test", (parameters, module) =>
{
var context =
new NancyContext();
var negotiator =
new Negotiator(context);
return negotiator;
});
}));
});
// When
var response = await browser.Get("/test.foo", with =>
{
with.Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru-RU) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4");
with.Accept("application/xml", 0.9m);
with.Accept("text/html", 0.9m);
});
// Then
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(response.Body.AsString().Contains("foo/bar"), "Media type mismatch");
}
[Fact]
public async Task Should_response_with_notacceptable_when_route_does_not_allow_any_of_the_accepted_formats()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/test", CreateNegotiatedResponse(config =>
{
config.WithAllowedMediaRange("application/xml");
}));
}));
});
// When
var response = await browser.Get("/test", with =>
{
with.Accept("foo/bar", 0.9m);
});
// Then
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task Should_respond_with_notacceptable_when_no_processor_can_process_media_range()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<NullProcessor>();
with.Module<NegotiationModule>();
});
// When
var response = await browser.Get("/invalid-view-name", with => with.Accept("foo/bar"));
// Then
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task Should_return_that_contains_default_model_when_no_media_range_specific_model_was_declared()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<ModelProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse(config =>
{
config.WithModel("the model");
config.WithAllowedMediaRange("test/test");
}));
}));
});
// When
var response = await browser.Get("/", with =>
{
with.Accept("test/test", 0.9m);
});
// Then
Assert.Equal("the model", response.Body.AsString());
}
[Fact]
public async Task Should_return_media_range_specific_model_when_declared()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<ModelProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse(config =>
{
config.WithModel("the model");
config.WithAllowedMediaRange("test/test");
config.WithMediaRangeModel("test/test", "media model");
}));
}));
});
// When
var response = await browser.Get("/", with =>
{
with.Accept("test/test", 0.9m);
});
// Then
Assert.Equal("media model", response.Body.AsString());
}
[Fact]
public async Task Should_add_vary_accept_header()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor));
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse());
}));
});
// When
var response = await browser.Get("/", with => with.Header("Accept", "application/json"));
// Then
Assert.True(response.Headers.ContainsKey("Vary"));
Assert.True(response.Headers["Vary"].Contains("Accept"));
}
[Fact]
public async Task Should_add_link_header_for_matching_response_processors()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor));
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse());
}));
});
// When
var response = await browser.Get("/");
// Then
Assert.True(response.Headers["Link"].Contains(@"</.foo>; rel=""alternate""; type=""foo/bar"""));
Assert.True(response.Headers["Link"].Contains(@"</.json>; rel=""alternate""; type=""application/json"""));
Assert.True(response.Headers["Link"].Contains(@"</.xml>; rel=""alternate""; type=""application/xml"""));
}
[Fact]
public async Task Should_preserve_existing_link_header()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonLdProcessor));
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse());
}));
});
// When
var response = await browser.Get("/");
// Then
Assert.True(response.Headers["Link"].Contains(@"</context.jsonld>; rel=""http://www.w3.org/ns/json-ld#context""; type=""application/ld+json"""));
Assert.True(response.Headers["Link"].Contains(@"</.xml>; rel=""alternate""; type=""application/xml"""));
}
[Fact]
public async Task Should_set_negotiated_status_code_to_response_when_set_as_integer()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse(config =>
{
config.WithStatusCode(507);
}));
}));
});
// When
var response = await browser.Get("/", with =>
{
with.Accept("test/test", 0.9m);
});
// Then
Assert.Equal(HttpStatusCode.InsufficientStorage, response.StatusCode);
}
[Fact]
public async Task Should_set_negotiated_status_code_to_response_when_set_as_httpstatuscode()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse(config =>
{
config.WithStatusCode(HttpStatusCode.InsufficientStorage);
}));
}));
});
// When
var response = await browser.Get("/", with =>
{
with.Accept("test/test", 0.9m);
});
// Then
Assert.Equal(HttpStatusCode.InsufficientStorage, response.StatusCode);
}
[Fact]
public async Task Should_set_negotiated_cookies_to_response()
{
// Given
var negotiatedCookie =
new NancyCookie("test", "test");
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse(config =>
{
config.WithCookie(negotiatedCookie);
}));
}));
});
// When
var response = await browser.Get("/", with =>
{
with.Accept("test/test", 0.9m);
});
// Then
Assert.Same(negotiatedCookie, response.Cookies.First());
}
[Fact]
public async Task Should_throw_exception_if_view_location_fails()
{
var browser = new Browser(with =>
{
with.ResponseProcessor<ViewProcessor>();
with.Module(new ConfigurableNancyModule(x => x.Get("/FakeModuleInvalidViewName", CreateNegotiatedResponse(neg => neg.WithView("blahblahblah")))));
});
// When
var result = await RecordAsync.Exception(() => browser.Get(
"/FakeModuleInvalidViewName", with =>
{ with.Accept("text/html", 1.0m); })
);
// Then
Assert.NotNull(result);
Assert.Contains("Unable to locate view", result.ToString());
}
[Fact]
public async Task Should_use_next_processor_if_processor_returns_null()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessors(typeof(NullProcessor), typeof(TestProcessor));
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/test", CreateNegotiatedResponse(config =>
{
config.WithAllowedMediaRange("application/xml");
}));
}));
});
// When
var response = await browser.Get("/test", with =>
{
with.Accept("application/xml", 0.9m);
});
// Then
var bodyResult = response.Body.AsString();
Assert.True(bodyResult.StartsWith("application/xml"), string.Format("Body should have started with 'application/xml' but was actually '{0}'", bodyResult));
}
[Theory]
[InlineData("application/xhtml+xml; profile=\"http://www.wapforum. org/xhtml\"")]
[InlineData("application/xhtml+xml; q=1; profile=\"http://www.wapforum. org/xhtml\"")]
public async Task Should_not_throw_exception_because_of_uncommon_accept_header(string header)
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor));
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", CreateNegotiatedResponse());
}));
});
// When
var response = await browser.Get("/", with =>
{
with.Header("Accept", header);
});
// Then
Assert.Equal((HttpStatusCode)200, response.StatusCode);
}
[Fact]
public async Task Should_not_try_and_serve_view_with_invalid_name()
{
// Given
var browser = new Browser(with => with.Module<NegotiationModule>());
// When
var result = await RecordAsync.Exception(() => browser.Get("/invalid-view-name"));
// Then
Assert.True(result.ToString().Contains("Unable to locate view"));
}
[Fact]
public async Task Should_return_response_negotiated_based_on_media_range()
{
// Given
var browser = new Browser(with => with.Module<NegotiationModule>());
// When
var result = await browser.Get("/negotiate", with =>
{
with.Accept("text/html");
});
// Then
Assert.Equal(HttpStatusCode.SeeOther, result.StatusCode);
}
[Fact]
public async Task Can_negotiate_in_status_code_handler()
{
// Given
var browser = new Browser(with => with.StatusCodeHandler<NotFoundStatusCodeHandler>());
// When
var result = await browser.Get("/not-found", with => with.Accept("application/json"));
var response = result.Body.DeserializeJson<NotFoundStatusCodeHandlerResult>();
// Then
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("Not Found.", response.Message);
}
[Fact]
public async Task Can_negotiate_in_error_pipeline()
{
// Given
var browser = new Browser(with => with.Module<ThrowingModule>());
// When
var jsonResult = await browser.Get("/", with => with.Accept("application/json"));
var xmlResult = await browser.Get("/", with => with.Accept("application/xml"));
var jsonResponse = jsonResult.Body.DeserializeJson<ThrowingModule.Error>();
var xmlResponse = xmlResult.Body.DeserializeXml<ThrowingModule.Error>();
// Then
Assert.Equal("Oh noes!", jsonResponse.Message);
Assert.Equal("Oh noes!", xmlResponse.Message);
}
[Fact]
public async Task Should_return_negotiated_not_found_response_when_accept_header_is_html()
{
// Given
var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>());
var contentType = "text/html";
// When
var result = await browser.Get("/not-found", with => with.Accept(contentType));
// Then
Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
Assert.Equal(contentType, result.ContentType);
}
[Fact]
public async Task Should_return_negotiated_not_found_response_when_accept_header_is_json()
{
// Given
var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>());
var contentType = "application/json";
// When
var result = await browser.Get("/not-found", with => with.Accept(contentType));
// Then
Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
Assert.Equal(string.Format("{0}; charset=utf-8", contentType), result.ContentType);
}
[Fact]
public async Task Should_return_negotiated_not_found_response_when_accept_header_is_xml()
{
// Given
var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>());
var contentType = "application/xml";
// When
var result = await browser.Get("/not-found", with => with.Accept(contentType));
// Then
Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
Assert.Equal(contentType, result.ContentType);
}
private static Func<dynamic, LegacyNancyModule, dynamic> CreateNegotiatedResponse(Action<Negotiator> action = null)
{
return (parameters, module) =>
{
var negotiator = new Negotiator(module.Context);
if (action != null)
{
action.Invoke(negotiator);
}
return negotiator;
};
}
/// <summary>
/// Test response processor that will accept any type
/// and put the content type and model type into the
/// response body for asserting against.
/// Hacky McHackmeister but it works :-)
/// </summary>
public class TestProcessor : IResponseProcessor
{
private const string ResponseTemplate = "{0}\n{1}";
public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings
{
get
{
yield return new Tuple<string, MediaRange>("foo", "foo/bar");
}
}
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
return new ProcessorMatch
{
RequestedContentTypeResult = MatchResult.DontCare,
ModelResult = MatchResult.DontCare
};
}
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
return string.Format(ResponseTemplate, requestedMediaRange, model == null ? "None" : model.GetType());
}
}
public class NullProcessor : IResponseProcessor
{
public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings
{
get
{
yield break;
}
}
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
return new ProcessorMatch
{
RequestedContentTypeResult = MatchResult.ExactMatch,
ModelResult = MatchResult.ExactMatch
};
}
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
return null;
}
}
public class ModelProcessor : IResponseProcessor
{
public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings
{
get
{
yield return new Tuple<string, MediaRange>("foo", "foo/bar");
}
}
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
return new ProcessorMatch
{
RequestedContentTypeResult = MatchResult.DontCare,
ModelResult = MatchResult.DontCare
};
}
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
return (string) model;
}
}
private class NegotiationModule : LegacyNancyModule
{
public NegotiationModule()
{
Get["/invalid-view-name"] = _ =>
{
return this.GetModel();
};
Get["/negotiate"] = parameters =>
{
return Negotiate
.WithMediaRangeResponse("text/html", Response.AsRedirect("/"))
.WithMediaRangeModel("application/json", new { Name = "Nancy" });
};
}
private IEnumerable<Foo> GetModel()
{
yield return new Foo();
}
private class Foo
{
}
}
private class NotFoundStatusCodeHandler : IStatusCodeHandler
{
private readonly IResponseNegotiator responseNegotiator;
public NotFoundStatusCodeHandler(IResponseNegotiator responseNegotiator)
{
this.responseNegotiator = responseNegotiator;
}
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
return statusCode == HttpStatusCode.NotFound;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
var error = new NotFoundStatusCodeHandlerResult
{
StatusCode = statusCode,
Message = "Not Found."
};
context.Response = this.responseNegotiator.NegotiateResponse(error, context);
}
}
private class NotFoundStatusCodeHandlerResult
{
public HttpStatusCode StatusCode { get; set; }
public string Message { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
/*=================================TaiwanCalendar==========================
**
** Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar.
** That is,
** Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1912/01/01 9999/12/31
** Taiwan 01/01/01 8088/12/31
============================================================================*/
[Serializable]
public class TaiwanCalendar : Calendar
{
//
// The era value for the current era.
//
// Since
// Gregorian Year = Era Year + yearOffset
// When Gregorian Year 1912 is year 1, so that
// 1912 = 1 + yearOffset
// So yearOffset = 1911
//m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911);
// Initialize our era info.
internal static EraInfo[] taiwanEraInfo = new EraInfo[] {
new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
};
internal static volatile Calendar s_defaultInstance;
internal GregorianCalendarHelper helper;
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of TaiwanCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance()
{
if (s_defaultInstance == null)
{
s_defaultInstance = new TaiwanCalendar();
}
return (s_defaultInstance);
}
internal static readonly DateTime calendarMinValue = new DateTime(1912, 1, 1);
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
// Return the type of the Taiwan calendar.
//
public TaiwanCalendar()
{
try
{
new CultureInfo("zh-TW");
}
catch (ArgumentException e)
{
throw new TypeInitializationException(this.GetType().ToString(), e);
}
helper = new GregorianCalendarHelper(this, taiwanEraInfo);
}
internal override CalendarId ID
{
get
{
return CalendarId.TAIWAN;
}
}
public override DateTime AddMonths(DateTime time, int months)
{
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years)
{
return (helper.AddYears(time, years));
}
public override int GetDaysInMonth(int year, int month, int era)
{
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era)
{
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time)
{
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era)
{
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time)
{
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time)
{
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era)
{
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era)
{
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
// For Taiwan calendar, four digit year is not used.
// Therefore, for any two digit number, we just return the original number.
public override int ToFourDigitYear(int year)
{
if (year <= 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.EndContractBlock();
if (year > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
helper.MaxYear));
}
return (year);
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.Data;
using System.Linq;
using Umbraco.Core.Cache;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.PropertyEditors;
using umbraco.DataLayer;
using System.Xml;
using umbraco.cms.businesslogic.media;
using umbraco.interfaces;
using PropertyType = umbraco.cms.businesslogic.propertytype.PropertyType;
using Umbraco.Core;
namespace umbraco.cms.businesslogic.datatype
{
/// <summary>
/// Datatypedefinitions is the basic buildingblocks of umbraco's documents/medias/members generic datastructure
///
/// A datatypedefinition encapsulates an object which implements the interface IDataType, and are used when defining
/// the properties of a document in the documenttype. This extra layer between IDataType and a documenttypes propertytype
/// are used amongst other for enabling shared prevalues.
///
/// </summary>
[Obsolete("This class is no longer used and will be removed from the codebase in the future.")]
public class DataTypeDefinition : CMSNode
{
#region Private fields
internal string PropertyEditorAlias { get; private set; }
private static readonly Guid ObjectType = new Guid(Constants.ObjectTypes.DataType);
private string _text1;
#endregion
#region Constructors
/// <summary>
/// Initialization of the datatypedefinition
/// </summary>
/// <param name="id">Datattypedefininition id</param>
public DataTypeDefinition(int id) : base(id) { }
/// <summary>
/// Initialization of the datatypedefinition
/// </summary>
/// <param name="id">Datattypedefininition id</param>
public DataTypeDefinition(Guid id) : base(id) { }
#endregion
#region Public Properties
public override string Text
{
get { return _text1 ?? (_text1 = base.Text); }
set { _text1 = value; }
}
/// <summary>
/// The associated datatype, which delivers the methods for editing data, editing prevalues see: umbraco.interfaces.IDataType
/// </summary>
public IDataType DataType
{
get
{
if (PropertyEditorAlias.IsNullOrWhiteSpace())
return null;
//Attempt to resolve a legacy control id from the alias. If one is not found we'll generate one -
// the reason one will not be found is if there's a new v7 property editor created that doesn't have a legacy
// property editor predecessor.
//So, we'll generate an id for it based on the alias which will remain consistent, but then we'll try to resolve a legacy
// IDataType which of course will not exist. In this case we'll have to create a new one on the fly for backwards compatibility but
// this instance will have limited capabilities and will really only work for saving data so the legacy APIs continue to work.
var controlId = LegacyPropertyEditorIdToAliasConverter.GetLegacyIdFromAlias(PropertyEditorAlias, LegacyPropertyEditorIdToAliasConverter.NotFoundLegacyIdResponseBehavior.GenerateId);
var dt = DataTypesResolver.Current.GetById(controlId.Value);
if (dt != null)
{
dt.DataTypeDefinitionId = Id;
}
else
{
//Ok so it was not found, we can only assume that this is because this is a new property editor that does not have a legacy predecessor.
//we'll have to attempt to generate one at runtime.
dt = BackwardsCompatibleDataType.Create(PropertyEditorAlias, controlId.Value, Id);
}
return dt;
}
set
{
if (SqlHelper == null)
throw new InvalidOperationException("Cannot execute a SQL command when the SqlHelper is null");
if (value == null)
throw new InvalidOperationException("The value passed in is null. The DataType property cannot be set to a null value");
var alias = LegacyPropertyEditorIdToAliasConverter.GetAliasFromLegacyId(value.Id, true);
SqlHelper.ExecuteNonQuery("update cmsDataType set propertyEditorAlias = @alias where nodeID = " + this.Id,
SqlHelper.CreateParameter("@alias", alias));
PropertyEditorAlias = alias;
}
}
internal string DbType { get; private set; }
#endregion
#region Public methods
public override void delete()
{
var e = new DeleteEventArgs();
FireBeforeDelete(e);
if (e.Cancel == false)
{
//first clear the prevalues
PreValues.DeleteByDataTypeDefinition(this.Id);
//next clear out the property types
var propTypes = PropertyType.GetByDataTypeDefinition(this.Id);
foreach (var p in propTypes)
{
p.delete();
}
//delete the cmsDataType role, then the umbracoNode
SqlHelper.ExecuteNonQuery("delete from cmsDataType where nodeId=@nodeId",
SqlHelper.CreateParameter("@nodeId", this.Id));
base.delete();
FireAfterDelete(e);
}
}
[Obsolete("Use the standard delete() method instead")]
public void Delete()
{
delete();
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public override void Save()
{
//Cannot change to a duplicate alias
var exists = Database.ExecuteScalar<int>(@"SELECT COUNT(*) FROM cmsDataType
INNER JOIN umbracoNode ON cmsDataType.nodeId = umbracoNode.id
WHERE umbracoNode." + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("text") + @"= @name
AND umbracoNode.id <> @id",
new { id = this.Id, name = this.Text });
if (exists > 0)
{
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(
string.Format("{0}{1}", CacheKeys.DataTypeCacheKey, this.Id));
throw new DuplicateNameException("A data type with the name " + this.Text + " already exists");
}
//this actually does the persisting.
base.Text = _text1;
OnSaving(EventArgs.Empty);
}
public XmlElement ToXml(XmlDocument xd)
{
//here we need to get the property editor alias from it's id
var alias = LegacyPropertyEditorIdToAliasConverter.GetAliasFromLegacyId(DataType.Id, true);
var dt = xd.CreateElement("DataType");
dt.Attributes.Append(xmlHelper.addAttribute(xd, "Name", Text));
//The 'ID' when exporting is actually the property editor alias (in pre v7 it was the IDataType GUID id)
dt.Attributes.Append(xmlHelper.addAttribute(xd, "Id", alias));
dt.Attributes.Append(xmlHelper.addAttribute(xd, "Definition", UniqueId.ToString()));
dt.Attributes.Append(xmlHelper.addAttribute(xd, "DatabaseType", DbType));
// templates
var prevalues = xd.CreateElement("PreValues");
foreach (DictionaryEntry item in PreValues.GetPreValues(Id))
{
var prevalue = xd.CreateElement("PreValue");
prevalue.Attributes.Append(xmlHelper.addAttribute(xd, "Id", ((PreValue)item.Value).Id.ToString(CultureInfo.InvariantCulture)));
prevalue.Attributes.Append(xmlHelper.addAttribute(xd, "Value", ((PreValue)item.Value).Value));
prevalue.Attributes.Append(xmlHelper.addAttribute(xd, "Alias", ((PreValue)item.Value).Alias));
prevalues.AppendChild(prevalue);
}
dt.AppendChild(prevalues);
return dt;
}
#endregion
#region Static methods
[Obsolete("Do not use this method, it will not function correctly because legacy property editors are not supported in v7")]
public static DataTypeDefinition Import(XmlNode xmlData)
{
var name = xmlData.Attributes["Name"].Value;
var id = xmlData.Attributes["Id"].Value;
var def = xmlData.Attributes["Definition"].Value;
//Make sure that the dtd is not already present
if (IsNode(new Guid(def)) == false)
{
var u = BusinessLogic.User.GetCurrent() ?? BusinessLogic.User.GetUser(0);
var dtd = MakeNew(u, name, new Guid(def));
var dataType = DataTypesResolver.Current.GetById(new Guid(id));
if (dataType == null)
throw new NullReferenceException("Could not resolve a data type with id " + id);
dtd.DataType = dataType;
dtd.Save();
//add prevalues
foreach (XmlNode xmlPv in xmlData.SelectNodes("PreValues/PreValue"))
{
var val = xmlPv.Attributes["Value"];
if (val != null)
{
var p = new PreValue(0, 0, val.Value);
p.DataTypeId = dtd.Id;
p.Save();
}
}
return dtd;
}
return null;
}
/// <summary>
/// Retrieves a list of all datatypedefinitions
/// </summary>
/// <returns>A list of all datatypedefinitions</returns>
public static DataTypeDefinition[] GetAll()
{
var retvalSort = new SortedList();
var tmp = getAllUniquesFromObjectType(ObjectType);
var retval = new DataTypeDefinition[tmp.Length];
for (var i = 0; i < tmp.Length; i++)
{
var dt = GetDataTypeDefinition(tmp[i]);
retvalSort.Add(dt.Text + "|||" + Guid.NewGuid(), dt);
}
var ide = retvalSort.GetEnumerator();
var counter = 0;
while (ide.MoveNext())
{
retval[counter] = (DataTypeDefinition)ide.Value;
counter++;
}
return retval;
}
/// <summary>
/// Creates a new datatypedefinition given its name and the user which creates it.
/// </summary>
/// <param name="u">The user who creates the datatypedefinition</param>
/// <param name="Text">The name of the DataTypeDefinition</param>
/// <returns></returns>
public static DataTypeDefinition MakeNew(BusinessLogic.User u, string Text)
{
return MakeNew(u, Text, Guid.NewGuid());
}
/// <summary>
/// Creates a new datatypedefinition given its name and the user which creates it.
/// </summary>
/// <param name="u">The user who creates the datatypedefinition</param>
/// <param name="Text">The name of the DataTypeDefinition</param>
/// <param name="UniqueId">Overrides the CMSnodes uniqueID</param>
/// <returns></returns>
public static DataTypeDefinition MakeNew(BusinessLogic.User u, string Text, Guid UniqueId)
{
//Cannot add a duplicate data type
var exists = Database.ExecuteScalar<int>(@"SELECT COUNT(*) FROM cmsDataType
INNER JOIN umbracoNode ON cmsDataType.nodeId = umbracoNode.id
WHERE umbracoNode." + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("text") + "= @name", new { name = Text });
if (exists > 0)
{
throw new DuplicateNameException("A data type with the name " + Text + " already exists");
}
var newId = MakeNew(-1, ObjectType, u.Id, 1, Text, UniqueId).Id;
//insert empty prop ed alias
SqlHelper.ExecuteNonQuery("Insert into cmsDataType (nodeId, propertyEditorAlias, dbType) values (" + newId + ",'','Ntext')");
var dtd = new DataTypeDefinition(newId);
dtd.OnNew(EventArgs.Empty);
return dtd;
}
/// <summary>
/// Retrieve a list of datatypedefinitions which share the same IDataType datatype
/// </summary>
/// <param name="DataTypeId">The unique id of the IDataType</param>
/// <returns>A list of datatypedefinitions which are based on the IDataType specified</returns>
public static DataTypeDefinition GetByDataTypeId(Guid DataTypeId)
{
var dfId = 0;
// When creating a datatype and not saving it, it will be null, so we need this check
foreach (var df in GetAll().Where(x => x.DataType != null))
{
if (df.DataType.Id == DataTypeId)
{
dfId = df.Id;
break;
}
}
return dfId == 0 ? null : new DataTypeDefinition(dfId);
}
/// <summary>
/// Analyzes an object to see if its basetype is umbraco.editorControls.DefaultData
/// </summary>
/// <param name="Data">The Data object to analyze</param>
/// <returns>True if the basetype is the DefaultData class</returns>
public static bool IsDefaultData(object Data)
{
Type typeOfData = Data.GetType();
while (typeOfData.BaseType != new Object().GetType())
{
typeOfData = typeOfData.BaseType;
}
return (typeOfData.FullName == "umbraco.cms.businesslogic.datatype.DefaultData");
}
public static DataTypeDefinition GetDataTypeDefinition(int id)
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
string.Format("{0}{1}", CacheKeys.DataTypeCacheKey, id),
() => new DataTypeDefinition(id));
}
[Obsolete("Use GetDataTypeDefinition(int id) instead", false)]
public static DataTypeDefinition GetDataTypeDefinition(Guid id)
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
string.Format("{0}{1}", CacheKeys.DataTypeCacheKey, id),
() => new DataTypeDefinition(id));
}
#endregion
#region Protected methods
protected override void setupNode()
{
base.setupNode();
using (var dr = SqlHelper.ExecuteReader("select dbType, propertyEditorAlias from cmsDataType where nodeId = '" + this.Id.ToString() + "'"))
{
if (dr.Read())
{
PropertyEditorAlias = dr.GetString("propertyEditorAlias");
DbType = dr.GetString("dbType");
}
else
throw new ArgumentException("No dataType with id = " + this.Id.ToString() + " found");
}
}
#endregion
#region Events
//EVENTS
public delegate void SaveEventHandler(DataTypeDefinition sender, EventArgs e);
public delegate void NewEventHandler(DataTypeDefinition sender, EventArgs e);
public delegate void DeleteEventHandler(DataTypeDefinition sender, EventArgs e);
/// <summary>
/// Occurs when a data type is saved.
/// </summary>
public static event SaveEventHandler Saving;
protected virtual void OnSaving(EventArgs e)
{
if (Saving != null)
Saving(this, e);
}
public static event NewEventHandler New;
protected virtual void OnNew(EventArgs e)
{
if (New != null)
New(this, e);
}
[Obsolete("This event is not used! Use the BeforeDelete or AfterDelete events")]
public static event DeleteEventHandler Deleting;
protected virtual void OnDeleting(EventArgs e)
{
if (Deleting != null)
Deleting(this, e);
}
/// <summary>
/// Occurs when [before delete].
/// </summary>
public new static event DeleteEventHandler BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected new virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
/// <summary>
/// Occurs when [after delete].
/// </summary>
public new static event DeleteEventHandler AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected new virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareScalarNotLessThanDouble()
{
var test = new SimpleBinaryOpTest__CompareScalarNotLessThanDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareScalarNotLessThanDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarNotLessThanDouble testClass)
{
var result = Sse2.CompareScalarNotLessThan(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarNotLessThanDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarNotLessThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareScalarNotLessThanDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__CompareScalarNotLessThanDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareScalarNotLessThan(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareScalarNotLessThan(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareScalarNotLessThan(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareScalarNotLessThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareScalarNotLessThan(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareScalarNotLessThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarNotLessThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarNotLessThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareScalarNotLessThanDouble();
var result = Sse2.CompareScalarNotLessThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareScalarNotLessThanDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.CompareScalarNotLessThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareScalarNotLessThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarNotLessThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareScalarNotLessThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareScalarNotLessThan(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] < right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareScalarNotLessThan)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Chirper.Grains.Models;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Concurrency;
using Orleans.Runtime;
namespace Chirper.Grains
{
[Serializable]
public class ChirperAccountState
{
/// <summary>
/// The list of publishers who this user is following.
/// </summary>
public Dictionary<string, IChirperPublisher> Subscriptions { get; set; }
/// <summary>
/// The list of subscribers who are following this user.
/// </summary>
public Dictionary<string, IChirperSubscriber> Followers { get; set; }
/// <summary>
/// Chirp messages recently received by this user.
/// </summary>
public Queue<ChirperMessage> RecentReceivedMessages { get; set; }
/// <summary>
/// Chirp messages recently published by this user.
/// </summary>
public Queue<ChirperMessage> MyPublishedMessages { get; set; }
}
[Reentrant]
public class ChirperAccount : Grain, IChirperAccount
{
/// <summary>
/// Size for the recently received message cache.
/// </summary>
private const int ReceivedMessagesCacheSize = 100;
/// <summary>
/// Size for the published message cache.
/// </summary>
private const int PublishedMessagesCacheSize = 100;
/// <summary>
/// Max length of each chirp.
/// </summary>
private const int MAX_MESSAGE_LENGTH = 280;
/// <summary>
/// Holds the transient list of viewers.
/// This list is not part of state and will not survive grain deactivation.
/// </summary>
private readonly HashSet<IChirperViewer> _viewers = new();
private readonly ILogger<ChirperAccount> _logger;
private readonly IPersistentState<ChirperAccountState> _state;
/// <summary>
/// Allows state writing to happen in the background.
/// </summary>
private Task _outstandingWriteStateOperation;
public ChirperAccount(
[PersistentState(stateName: "account", storageName: "AccountState")] IPersistentState<ChirperAccountState> state,
ILogger<ChirperAccount> logger)
{
_logger = logger;
_state = state;
}
private static string GrainType => nameof(ChirperAccount);
private string GrainKey => this.GetPrimaryKeyString();
public override Task OnActivateAsync()
{
// initialize state as needed
if (_state.State.RecentReceivedMessages == null) _state.State.RecentReceivedMessages = new Queue<ChirperMessage>(ReceivedMessagesCacheSize);
if (_state.State.MyPublishedMessages == null) _state.State.MyPublishedMessages = new Queue<ChirperMessage>(PublishedMessagesCacheSize);
if (_state.State.Followers == null) _state.State.Followers = new Dictionary<string, IChirperSubscriber>();
if (_state.State.Subscriptions == null) _state.State.Subscriptions = new Dictionary<string, IChirperPublisher>();
_logger.LogInformation("{GrainType} {GrainKey} activated.", GrainType, GrainKey);
return Task.CompletedTask;
}
public async Task PublishMessageAsync(string message)
{
var chirp = CreateNewChirpMessage(message);
_logger.LogInformation("{GrainType} {GrainKey} publishing new chirp message '{Chirp}'.",
GrainType, GrainKey, chirp);
_state.State.MyPublishedMessages.Enqueue(chirp);
while (_state.State.MyPublishedMessages.Count > PublishedMessagesCacheSize)
{
_state.State.MyPublishedMessages.Dequeue();
}
await WriteStateAsync();
// notify viewers of new message
_logger.LogInformation("{GrainType} {GrainKey} sending new chirp message to {ViewerCount} viewers.",
GrainType, GrainKey, _viewers.Count);
_viewers.ForEach(_ => _.NewChirp(chirp));
// notify followers of a new message
_logger.LogInformation("{GrainType} {GrainKey} sending new chirp message to {FollowerCount} followers.",
GrainType, GrainKey, _state.State.Followers.Count);
await Task.WhenAll(_state.State.Followers.Values.Select(_ => _.NewChirpAsync(chirp)).ToArray());
}
public Task<ImmutableList<ChirperMessage>> GetReceivedMessagesAsync(int n, int start)
{
if (start < 0) start = 0;
if ((start + n) > _state.State.RecentReceivedMessages.Count)
{
n = _state.State.RecentReceivedMessages.Count - start;
}
return Task.FromResult(_state.State.RecentReceivedMessages.Skip(start).Take(n).ToImmutableList());
}
public async Task FollowUserIdAsync(string username)
{
_logger.LogInformation(
"{GrainType} {UserName} > FollowUserName({TargetUserName}).",
GrainType,
GrainKey,
username);
var userToFollow = GrainFactory.GetGrain<IChirperPublisher>(username);
await userToFollow.AddFollowerAsync(GrainKey, this.AsReference<IChirperSubscriber>());
_state.State.Subscriptions[username] = userToFollow;
await WriteStateAsync();
// notify any viewers that a subscription has been added for this user
_viewers.ForEach(_ => _.SubscriptionAdded(username));
}
public async Task UnfollowUserIdAsync(string username)
{
_logger.LogInformation(
"{GrainType} {GrainKey} > UnfollowUserName({TargetUserName}).",
GrainType,
GrainKey,
username);
// ask the publisher to remove this grain as a follower
await GrainFactory.GetGrain<IChirperPublisher>(username)
.RemoveFollowerAsync(GrainKey);
// remove this publisher from the subscriptions list
_state.State.Subscriptions.Remove(username);
// save now
await WriteStateAsync();
// notify event subscribers
_viewers.ForEach(_ => _.SubscriptionRemoved(username));
}
public Task<ImmutableList<string>> GetFollowingListAsync() => Task.FromResult(_state.State.Subscriptions.Keys.ToImmutableList());
public Task<ImmutableList<string>> GetFollowersListAsync() => Task.FromResult(_state.State.Followers.Keys.ToImmutableList());
public Task SubscribeAsync(IChirperViewer viewer)
{
_viewers.Add(viewer);
return Task.CompletedTask;
}
public Task UnsubscribeAsync(IChirperViewer viewer)
{
_viewers.Remove(viewer);
return Task.CompletedTask;
}
public Task<ImmutableList<ChirperMessage>> GetPublishedMessagesAsync(int n, int start)
{
if (start < 0) start = 0;
if ((start + n) > _state.State.MyPublishedMessages.Count) n = _state.State.MyPublishedMessages.Count - start;
return Task.FromResult(_state.State.MyPublishedMessages.Skip(start).Take(n).ToImmutableList());
}
public async Task AddFollowerAsync(string username, IChirperSubscriber follower)
{
_state.State.Followers[username] = follower;
await WriteStateAsync();
_viewers.ForEach(_ => _.NewFollower(username));
}
public async Task RemoveFollowerAsync(string username)
{
_state.State.Followers.Remove(username);
await WriteStateAsync();
}
public async Task NewChirpAsync(ChirperMessage chirp)
{
_logger.LogInformation(
"{GrainType} {GrainKey} received chirp message = {Chirp}",
GrainType,
GrainKey,
chirp);
_state.State.RecentReceivedMessages.Enqueue(chirp);
// only relevant when not using fixed queue
while (_state.State.MyPublishedMessages.Count > PublishedMessagesCacheSize) // to keep not more than the max number of messages
{
_state.State.MyPublishedMessages.Dequeue();
}
await WriteStateAsync();
// notify any viewers that a new chirp has been received
_logger.LogInformation(
"{GrainType} {GrainKey} sending received chirp message to {ViewerCount} viewers",
GrainType,
GrainKey,
_viewers.Count);
_viewers.ForEach(_ => _.NewChirp(chirp));
}
private ChirperMessage CreateNewChirpMessage(string message) => new ChirperMessage(message, DateTimeOffset.UtcNow, GrainKey);
// When reentrant grain is doing WriteStateAsync, etag violations are possible due to concurrent writes.
// The solution is to serialize and batch writes, and make sure only a single write is outstanding at any moment in time.
private async Task WriteStateAsync()
{
var currentWriteStateOperation = _outstandingWriteStateOperation;
if (currentWriteStateOperation != null)
{
try
{
// await the outstanding write, but ignore it since it doesn't include our changes
await currentWriteStateOperation;
}
catch
{
// Ignore all errors from this in-flight write operation, since the original caller(s) of it will observe it.
}
finally
{
if (_outstandingWriteStateOperation == currentWriteStateOperation)
{
// only null out the outstanding operation if it's the same one as the one we awaited, otherwise
// another request might have already done so.
_outstandingWriteStateOperation = null;
}
}
}
if (_outstandingWriteStateOperation == null)
{
// If after the initial write is completed, no other request initiated a new write operation, do it now.
currentWriteStateOperation = _state.WriteStateAsync();
_outstandingWriteStateOperation = currentWriteStateOperation;
}
else
{
// If there were many requests enqueued to persist state, there is no reason to enqueue a new write
// operation for each, since any write (after the initial one that we already awaited) will have cumulative
// changes including the one requested by our caller. Just await the new outstanding write.
currentWriteStateOperation = _outstandingWriteStateOperation;
}
try
{
await currentWriteStateOperation;
}
finally
{
if (_outstandingWriteStateOperation == currentWriteStateOperation)
{
// only null out the outstanding operation if it's the same one as the one we awaited, otherwise
// another request might have already done so.
_outstandingWriteStateOperation = null;
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ProviderSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration
{
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using System.Text;
using System.Globalization;
public sealed class ProviderSettings : ConfigurationElement
{
private readonly ConfigurationProperty _propName =
new ConfigurationProperty( "name",
typeof( string ),
null, // no reasonable default
null, // use default converter
ConfigurationProperty.NonEmptyStringValidator,
ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey);
private readonly ConfigurationProperty _propType = new ConfigurationProperty("type", typeof(String), "",
ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsTypeStringTransformationRequired);
private ConfigurationPropertyCollection _properties;
private NameValueCollection _PropertyNameCollection = null;
public ProviderSettings()
{
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propName);
_properties.Add(_propType);
_PropertyNameCollection = null;
}
public ProviderSettings(String name, String type) : this()
{
Name = name;
Type = type;
}
protected internal override ConfigurationPropertyCollection Properties
{
get
{
UpdatePropertyCollection();
return _properties;
}
}
protected internal override void Unmerge(ConfigurationElement sourceElement,
ConfigurationElement parentElement,
ConfigurationSaveMode saveMode)
{
ProviderSettings parentProviders = parentElement as ProviderSettings;
if (parentProviders != null)
parentProviders.UpdatePropertyCollection(); // before reseting make sure the bag is filled in
ProviderSettings sourceProviders = sourceElement as ProviderSettings;
if (sourceProviders != null)
sourceProviders.UpdatePropertyCollection(); // before reseting make sure the bag is filled in
base.Unmerge(sourceElement, parentElement, saveMode);
UpdatePropertyCollection();
}
protected internal override void Reset(ConfigurationElement parentElement)
{
ProviderSettings parentProviders = parentElement as ProviderSettings;
if (parentProviders != null)
parentProviders.UpdatePropertyCollection(); // before reseting make sure the bag is filled in
base.Reset(parentElement);
}
internal bool UpdatePropertyCollection()
{
bool bIsModified = false;
ArrayList removeList = null;
if (_PropertyNameCollection != null)
{
// remove any data that has been delete from the collection
foreach (ConfigurationProperty prop in _properties)
{
if (prop.Name != "name" && prop.Name != "type")
{
if (_PropertyNameCollection.Get(prop.Name) == null)
{
// _properties.Remove(prop.Name);
if (removeList == null)
removeList = new ArrayList();
if ((Values.GetConfigValue(prop.Name).ValueFlags & ConfigurationValueFlags.Locked) == 0) {
removeList.Add(prop.Name);
bIsModified = true;
}
}
}
}
if (removeList != null)
{
foreach (string propName in removeList)
{
_properties.Remove(propName);
}
}
// then copy any data that has been changed in the collection
foreach (string Key in _PropertyNameCollection)
{
string valueInCollection = _PropertyNameCollection[Key];
string valueInBag = GetProperty(Key);
if (valueInBag == null || valueInCollection != valueInBag) // add new property
{
SetProperty(Key, valueInCollection);
bIsModified = true;
}
}
}
_PropertyNameCollection = null;
return bIsModified;
}
protected internal override bool IsModified()
{
return UpdatePropertyCollection() || base.IsModified();
}
[ConfigurationProperty("name", IsRequired = true, IsKey=true)]
public String Name
{
get
{
return (String)base[_propName];
}
set
{
base[_propName] = value;
}
}
[ConfigurationProperty("type", IsRequired = true)]
public String Type
{
get
{
return (String)base[_propType];
}
set
{
base[_propType] = value;
}
}
public NameValueCollection Parameters
{
get
{
if (_PropertyNameCollection == null)
{
lock (this)
{
if (_PropertyNameCollection == null)
{
_PropertyNameCollection = new NameValueCollection(StringComparer.Ordinal);
foreach (object de in _properties)
{
ConfigurationProperty prop = (ConfigurationProperty)de;
if (prop.Name != "name" && prop.Name != "type")
_PropertyNameCollection.Add(prop.Name, (string)base[prop]);
}
}
}
}
return (NameValueCollection)_PropertyNameCollection;
}
}
private string GetProperty(string PropName)
{
if (_properties.Contains(PropName))
{
ConfigurationProperty prop = _properties[PropName];
if(prop != null)
return (string)base[prop];
}
return null;
}
private bool SetProperty(string PropName,string value)
{
ConfigurationProperty SetPropName = null;
if (_properties.Contains(PropName))
SetPropName = _properties[PropName];
else
{
SetPropName = new ConfigurationProperty(PropName, typeof(string), null);
_properties.Add(SetPropName);
}
if (SetPropName != null)
{
base[SetPropName] = value;
// Parameters[PropName] = value;
return true;
}
else
return false;
}
protected override bool OnDeserializeUnrecognizedAttribute(String name, String value)
{
ConfigurationProperty _propName = new ConfigurationProperty(name, typeof(string), value);
_properties.Add(_propName);
base[_propName] = value; // Add them to the property bag
Parameters[name] = value;
return true;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Terminal
File: TerminalCommandService.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
using StockSharp.Terminal.Interfaces;
namespace StockSharp.Terminal.Services
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Xaml;
using StockSharp.Logging;
using StockSharp.Studio.Core;
using StockSharp.Studio.Core.Commands;
using StockSharp.Localization;
using CommandTuple = System.Tuple<System.Action<StockSharp.Studio.Core.Commands.IStudioCommand>, System.Func<StockSharp.Studio.Core.Commands.IStudioCommand, bool>, bool>;
public class TerminalCommandService : ITerminalCommandService
{
private sealed class Scope : IStudioCommandScope
{
public string Name {get;}
public Scope(string name)
{
Name = name;
}
public override string ToString() => Name;
}
private readonly IStudioCommandScope _globalScope = new Scope("global");
private readonly IStudioCommandScope _undefinedScope = new Scope("undefined");
private readonly SynchronizedDictionary<Type, Dictionary<IStudioCommandScope, CachedSynchronizedDictionary<object, CommandTuple>>> _handlers = new SynchronizedDictionary<Type, Dictionary<IStudioCommandScope, CachedSynchronizedDictionary<object, CommandTuple>>>();
private readonly SynchronizedPairSet<object, IStudioCommandScope> _binds = new SynchronizedPairSet<object, IStudioCommandScope>();
private readonly SynchronizedDictionary<object, IStudioCommandScope> _scopes = new SynchronizedDictionary<object, IStudioCommandScope>();
private readonly BlockingQueue<Tuple<IStudioCommand, IStudioCommandScope>> _queue = new BlockingQueue<Tuple<IStudioCommand, IStudioCommandScope>>();
public TerminalCommandService()
{
ThreadingHelper
.Thread(Process)
.Background(true)
.Culture(CultureInfo.InvariantCulture)
.Name("Terminal command service thread")
.Launch();
}
bool IStudioCommandService.CanProcess(object sender, IStudioCommand command)
{
var handlers = TryGetHandlers(command);
if (handlers == null)
return false;
var scope = sender is IStudioCommandScope ? _globalScope : GetScope(sender);
if (scope == _undefinedScope)
return false;
var scopeHandlers = handlers.TryGetValue(scope) ?? (command.CanRouteToGlobalScope ? handlers.TryGetValue(_globalScope) : null);
return scopeHandlers != null && scopeHandlers.CachedValues.All(tuple => tuple.Item2 == null || tuple.Item2(command));
}
void IStudioCommandService.Process(object sender, IStudioCommand command, bool isSyncProcess)
{
if (TryGetHandlers(command) == null)
return;
var scope = sender is IStudioCommandScope ? _globalScope : GetScope(sender);
if (scope == _undefinedScope)
return;
if (isSyncProcess)
{
if (Thread.CurrentThread != GuiDispatcher.GlobalDispatcher.Dispatcher.Thread)
throw new ArgumentException(LocalizedStrings.Str3596);
ProcessCommand(command, scope);
return;
}
_queue.Enqueue(Tuple.Create(command, scope));
}
private void Process()
{
while (true)
{
try
{
Tuple<IStudioCommand, IStudioCommandScope> item;
if (!_queue.TryDequeue(out item))
break;
ProcessCommand(item.Item1, item.Item2);
}
catch (Exception ex)
{
OnError(ex);
}
}
}
private static void OnError(Exception error)
{
error.LogError();
GuiDispatcher.GlobalDispatcher.Dispatcher.GuiAsync(() =>
{
MessageBox.Show(MainWindow.Instance, error.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
});
}
private void ProcessCommand(IStudioCommand command, IStudioCommandScope scope)
{
var handlers = TryGetHandlers(command);
if (handlers == null)
return;
var scopeHandlers = handlers.TryGetValue(scope) ?? (command.CanRouteToGlobalScope ? handlers.TryGetValue(_globalScope) : null);
if (scopeHandlers == null)
return;
var guiAsyncActions = new List<Tuple<CommandTuple, IStudioCommand>>();
foreach (var tuple in scopeHandlers.CachedValues)
{
if (!tuple.Item3)
{
ProcessCommand(tuple, command);
}
else
guiAsyncActions.Add(Tuple.Create(tuple, command));
}
if (!guiAsyncActions.IsEmpty())
GuiDispatcher.GlobalDispatcher.AddAction(() => guiAsyncActions.ForEach(t => ProcessCommand(t.Item1, t.Item2)));
}
private static void ProcessCommand(CommandTuple tuple, IStudioCommand command)
{
try
{
tuple.Item1(command);
}
catch (Exception ex)
{
OnError(ex);
}
}
void IStudioCommandService.Register<TCommand>(object listener, bool guiAsync, Action<TCommand> handler)
{
_handlers.SafeAdd(typeof(TCommand)).SafeAdd(GetScope(listener))[listener] = new CommandTuple(cmd => handler((TCommand)cmd), null, guiAsync);
}
void IStudioCommandService.Register<TCommand>(object listener, bool guiAsync, Action<TCommand> handler, Func<TCommand, bool> canExecute)
{
_handlers.SafeAdd(typeof(TCommand)).SafeAdd(GetScope(listener))[listener] = new CommandTuple(cmd => handler((TCommand)cmd), cmd => canExecute((TCommand)cmd), guiAsync);
}
void IStudioCommandService.UnRegister<TCommand>(object listener)
{
_handlers.TryGetValue(typeof(TCommand))
?.TryGetValue(GetScope(listener))
?.Remove(listener);
}
void IStudioCommandService.Bind(object sender, IStudioCommandScope scope)
{
if (sender == null)
throw new ArgumentNullException(nameof(sender));
if (scope == null)
throw new ArgumentNullException(nameof(scope));
_binds.Add(sender, scope);
var s = _scopes.TryGetValue(sender);
if (s != null)
{
ReplaceHandlersScope(sender, s, scope);
}
_scopes[sender] = scope;
}
void IStudioCommandService.UnBind(object sender)
{
if (sender == null)
throw new ArgumentNullException(nameof(sender));
_binds.Remove(sender);
_scopes.Remove(sender);
}
private IStudioCommandScope GetScope(object listener)
{
if (listener == null)
throw new ArgumentNullException(nameof(listener));
return _scopes.SafeAdd(listener, InternalGetScope);
}
private IStudioCommandScope InternalGetScope(object listener)
{
if (listener == null)
throw new ArgumentNullException(nameof(listener));
var scope = listener as IStudioCommandScope;
if (scope != null)
return scope;
scope = _binds.TryGetValue(listener);
if (scope != null)
return scope;
return _globalScope; // todo fix problem with undefined scope
var ctrl = listener as DependencyObject;
if (ctrl == null || ctrl is Window)
return _globalScope;
var parent = LogicalTreeHelper.GetParent(ctrl);
if (parent == null)
{
((FrameworkElement)ctrl).Loaded += OnUserControlLoaded;
return _undefinedScope;
}
return InternalGetScope(parent);
}
private void OnUserControlLoaded(object sender, RoutedEventArgs e)
{
var studioControl = sender as IStudioControl;
var contentControl = sender as ContentControl;
while (contentControl != null && studioControl == null)
{
studioControl = contentControl.Content as IStudioControl;
contentControl = contentControl.Content as ContentControl;
}
if (studioControl == null)
throw new InvalidOperationException(LocalizedStrings.Str3597Params.Put(sender));
var scope = _scopes[studioControl];
if (scope != _undefinedScope)
return;
scope = InternalGetScope(LogicalTreeHelper.GetParent((DependencyObject)studioControl));
_scopes[sender] = scope;
ReplaceHandlersScope(sender, _undefinedScope, scope);
}
private void ReplaceHandlersScope(object sender, IStudioCommandScope oldScope, IStudioCommandScope newScope)
{
lock (_handlers.SyncRoot)
{
foreach (var handlers in _handlers)
{
var scopeHandlers = handlers.Value.TryGetValue(oldScope);
if (scopeHandlers == null)
continue;
var handler = scopeHandlers.TryGetValue(sender);
if (handler != null)
{
scopeHandlers.Remove(sender);
handlers.Value.SafeAdd(newScope)[sender] = handler;
}
}
}
}
private Dictionary<IStudioCommandScope, CachedSynchronizedDictionary<object, CommandTuple>> TryGetHandlers(IStudioCommand command)
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var commandType = command.GetType();
var handlers = _handlers.TryGetValue(commandType);
if (handlers != null)
return handlers;
var baseType = _handlers.Keys.FirstOrDefault(commandType.IsSubclassOf);
return baseType != null
? _handlers.TryGetValue(baseType)
: null;
}
}
}
| |
/*
* Copyright (c) 2009, Stefan Simek
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace TriAxis.RunSharp
{
using Operands;
interface IMemberInfo
{
MemberInfo Member { get; }
string Name { get; }
Type ReturnType { get; }
Type[] ParameterTypes { get; }
bool IsParameterArray { get; }
bool IsStatic { get; }
bool IsOverride { get; }
}
interface ITypeInfoProvider
{
IEnumerable<IMemberInfo> GetConstructors();
IEnumerable<IMemberInfo> GetFields();
IEnumerable<IMemberInfo> GetProperties();
IEnumerable<IMemberInfo> GetEvents();
IEnumerable<IMemberInfo> GetMethods();
string DefaultMember { get; }
}
static class TypeInfo
{
static Dictionary<Type, ITypeInfoProvider> providers = new Dictionary<Type, ITypeInfoProvider>();
static Dictionary<Type, WeakReference> cache = new Dictionary<Type, WeakReference>();
class CacheEntry
{
Type t;
IMemberInfo[] constructors, fields, properties, events, methods;
static string nullStr = "$NULL";
string defaultMember = nullStr;
public CacheEntry(Type t)
{
this.t = t;
if (t.GetType() != typeof(object).GetType())
{
// not a runtime type, TypeInfoProvider missing - return nothing
constructors = fields = properties = events = methods = empty;
defaultMember = null;
}
}
~CacheEntry()
{
lock (cache)
{
WeakReference wr;
if (cache.TryGetValue(t, out wr) && (wr.Target == this || wr.Target == null))
cache.Remove(t);
}
}
static IMemberInfo[] empty = { };
public IMemberInfo[] Constructors
{
get
{
if (constructors == null)
{
ConstructorInfo[] ctors = t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);
constructors = Array.ConvertAll<ConstructorInfo, IMemberInfo>(ctors, delegate(ConstructorInfo ci) { return new StdMethodInfo(ci); });
}
return constructors;
}
}
public IMemberInfo[] Fields
{
get
{
if (fields == null)
{
FieldInfo[] fis = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static);
fields = Array.ConvertAll<FieldInfo, IMemberInfo>(fis, delegate(FieldInfo fi) { return new StdFieldInfo(fi); });
}
return fields;
}
}
public IMemberInfo[] Properties
{
get
{
if (properties == null)
{
PropertyInfo[] pis = t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static);
properties = Array.ConvertAll<PropertyInfo, IMemberInfo>(pis, delegate(PropertyInfo pi) { return new StdPropertyInfo(pi); });
}
return properties;
}
}
public IMemberInfo[] Events
{
get
{
if (events == null)
{
EventInfo[] eis = t.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static);
events = Array.ConvertAll<EventInfo, IMemberInfo>(eis, delegate(EventInfo ei) { return new StdEventInfo(ei); });
}
return events;
}
}
public IMemberInfo[] Methods
{
get
{
if (methods == null)
{
MethodInfo[] mis = t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static);
methods = Array.ConvertAll<MethodInfo, IMemberInfo>(mis, delegate(MethodInfo mi) { return new StdMethodInfo(mi); });
}
return methods;
}
}
public string DefaultMember
{
get
{
if (defaultMember == nullStr)
{
foreach (DefaultMemberAttribute dma in Attribute.GetCustomAttributes(t, typeof(DefaultMemberAttribute)))
return defaultMember = dma.MemberName;
defaultMember = null;
}
return defaultMember;
}
}
}
public static void RegisterProvider(Type t, ITypeInfoProvider prov)
{
providers[t] = prov;
}
public static void UnregisterProvider(Type t)
{
providers.Remove(t);
}
static CacheEntry GetCacheEntry(Type t)
{
if (t is TypeBuilder)
t = t.UnderlyingSystemType;
lock (cache)
{
CacheEntry ce;
WeakReference wr;
if (cache.TryGetValue(t, out wr))
{
ce = wr.Target as CacheEntry;
if (ce != null)
return ce;
}
ce = new CacheEntry(t);
cache[t] = new WeakReference(ce);
return ce;
}
}
public static IEnumerable<IMemberInfo> GetConstructors(Type t)
{
ITypeInfoProvider prov;
if (providers.TryGetValue(t, out prov))
return prov.GetConstructors();
return GetCacheEntry(t).Constructors;
}
public static IEnumerable<IMemberInfo> GetFields(Type t)
{
ITypeInfoProvider prov;
if (providers.TryGetValue(t, out prov))
return prov.GetFields();
return GetCacheEntry(t).Fields;
}
public static IEnumerable<IMemberInfo> GetProperties(Type t)
{
ITypeInfoProvider prov;
if (providers.TryGetValue(t, out prov))
return prov.GetProperties();
return GetCacheEntry(t).Properties;
}
public static IEnumerable<IMemberInfo> GetEvents(Type t)
{
ITypeInfoProvider prov;
if (providers.TryGetValue(t, out prov))
return prov.GetEvents();
return GetCacheEntry(t).Events;
}
public static IEnumerable<IMemberInfo> GetMethods(Type t)
{
ITypeInfoProvider prov;
if (providers.TryGetValue(t, out prov))
return prov.GetMethods();
return GetCacheEntry(t).Methods;
}
public static string GetDefaultMember(Type t)
{
ITypeInfoProvider prov;
if (providers.TryGetValue(t, out prov))
return prov.DefaultMember;
return GetCacheEntry(t).DefaultMember;
}
public static IEnumerable<IMemberInfo> Filter(IEnumerable<IMemberInfo> source, string name, bool ignoreCase, bool isStatic, bool allowOverrides)
{
foreach (IMemberInfo mi in source)
{
if (mi.IsStatic != isStatic)
continue;
if (!allowOverrides && mi.IsOverride)
continue;
if (name != null)
{
if (ignoreCase)
{
if (!mi.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
continue;
}
else
{
if (mi.Name != name)
continue;
}
}
yield return mi;
}
}
public static ApplicableFunction FindConstructor(Type t, Operand[] args)
{
ApplicableFunction ctor = OverloadResolver.Resolve(GetConstructors(t), args);
if (ctor == null)
throw new MissingMemberException(Properties.Messages.ErrMissingConstructor);
return ctor;
}
public static IMemberInfo FindField(Type t, string name, bool @static)
{
for (; t != null; t = t.BaseType)
{
foreach (IMemberInfo mi in GetFields(t))
{
if (mi.Name == name && mi.IsStatic == @static)
return mi;
}
}
throw new MissingFieldException(Properties.Messages.ErrMissingField);
}
public static ApplicableFunction FindProperty(Type t, string name, Operand[] indexes, bool @static)
{
if (name == null)
name = GetDefaultMember(t);
for (; t != null; t = t.BaseType)
{
ApplicableFunction af = OverloadResolver.Resolve(Filter(GetProperties(t), name, false, @static, false), indexes);
if (af != null)
return af;
}
throw new MissingMemberException(Properties.Messages.ErrMissingProperty);
}
public static IMemberInfo FindEvent(Type t, string name, bool @static)
{
for (; t != null; t = t.BaseType)
{
foreach (IMemberInfo mi in GetEvents(t))
{
if (mi.Name == name && mi.IsStatic == @static)
return mi;
}
}
throw new MissingMemberException(Properties.Messages.ErrMissingEvent);
}
public static ApplicableFunction FindMethod(Type t, string name, Operand[] args, bool @static)
{
for (; t != null; t = t.BaseType)
{
ApplicableFunction af = OverloadResolver.Resolve(Filter(GetMethods(t), name, false, @static, false), args);
if (af != null)
return af;
}
throw new MissingMethodException(Properties.Messages.ErrMissingMethod);
}
class StdMethodInfo : IMemberInfo
{
MethodBase mb;
MethodInfo mi;
string name;
Type returnType;
Type[] parameterTypes;
bool hasVar;
public StdMethodInfo(MethodInfo mi)
: this((MethodBase)mi)
{
this.mi = mi;
}
public StdMethodInfo(ConstructorInfo ci)
: this((MethodBase)ci)
{
this.returnType = typeof(void);
}
public StdMethodInfo(MethodBase mb)
{
this.mb = mb;
}
void RequireParameters()
{
if (parameterTypes == null)
{
ParameterInfo[] pis = mb.GetParameters();
parameterTypes = ArrayUtils.GetTypes(pis);
hasVar = pis.Length > 0 &&
pis[pis.Length - 1].GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;
}
}
public MemberInfo Member { get { return mb; } }
public string Name
{
get
{
if (name == null)
name = mb.Name;
return name;
}
}
public Type ReturnType
{
get
{
if (returnType == null)
returnType = mi.ReturnType;
return returnType;
}
}
public Type[] ParameterTypes
{
get
{
RequireParameters();
return parameterTypes;
}
}
public bool IsParameterArray
{
get
{
RequireParameters();
return hasVar;
}
}
public bool IsStatic { get { return mb.IsStatic; } }
public bool IsOverride { get { return Utils.IsOverride(mb.Attributes); } }
public override string ToString()
{
return mb.ToString();
}
}
class StdPropertyInfo : IMemberInfo
{
PropertyInfo pi;
string name;
MethodInfo mi;
Type returnType;
Type[] parameterTypes;
bool hasVar;
public StdPropertyInfo(PropertyInfo pi)
{
this.pi = pi;
this.mi = pi.GetGetMethod();
if (mi == null)
mi = pi.GetSetMethod();
// mi will remain null for abstract properties
}
void RequireParameters()
{
if (parameterTypes == null)
{
ParameterInfo[] pis = pi.GetIndexParameters();
parameterTypes = ArrayUtils.GetTypes(pis);
hasVar = pis.Length > 0 &&
pis[pis.Length - 1].GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;
}
}
public MemberInfo Member { get { return pi; } }
public string Name
{
get
{
if (name == null)
name = pi.Name;
return name;
}
}
public Type ReturnType
{
get
{
if (returnType == null)
returnType = pi.PropertyType;
return returnType;
}
}
public Type[] ParameterTypes
{
get
{
RequireParameters();
return parameterTypes;
}
}
public bool IsParameterArray
{
get
{
RequireParameters();
return hasVar;
}
}
public bool IsOverride { get { return mi == null ? false : Utils.IsOverride(mi.Attributes); } }
public bool IsStatic { get { return mi == null ? false : mi.IsStatic; } }
public override string ToString()
{
return pi.ToString();
}
}
class StdEventInfo : IMemberInfo
{
EventInfo ei;
string name;
MethodInfo mi;
public StdEventInfo(EventInfo ei)
{
this.ei = ei;
this.name = ei.Name;
this.mi = ei.GetAddMethod();
if (mi == null)
mi = ei.GetRemoveMethod();
// mi will remain null for abstract properties
}
public MemberInfo Member { get { return ei; } }
public string Name { get { return name; } }
public Type ReturnType { get { return ei.EventHandlerType; } }
public Type[] ParameterTypes { get { return Type.EmptyTypes; } }
public bool IsParameterArray { get { return false; } }
public bool IsOverride { get { return mi == null ? false : Utils.IsOverride(mi.Attributes); } }
public bool IsStatic { get { return mi == null ? false : mi.IsStatic; } }
public override string ToString()
{
return ei.ToString();
}
}
class StdFieldInfo : IMemberInfo
{
FieldInfo fi;
string name;
public StdFieldInfo(FieldInfo fi)
{
this.fi = fi;
this.name = fi.Name;
}
public MemberInfo Member { get { return fi; } }
public string Name { get { return name; } }
public Type ReturnType { get { return fi.FieldType; } }
public Type[] ParameterTypes { get { return Type.EmptyTypes; } }
public bool IsParameterArray { get { return false; } }
public bool IsOverride { get { return false; } }
public bool IsStatic { get { return fi.IsStatic; } }
public override string ToString()
{
return fi.ToString();
}
}
}
/* public Operand Invoke(string name, params Operand[] args)
{
Operand target = Target;
for (Type src = this; src != null; src = src.Base)
{
ApplicableFunction match = OverloadResolver.Resolve(Type.FilterMethods(src.GetMethods(), name, false, (object)target == null, false), args);
if (match != null)
return new Invocation(match, Target, args);
}
throw new MissingMethodException(Properties.Messages.ErrMissingMethod);
}*/
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Reflection;
using Sensus.Probes;
using Sensus.Probes.User.Scripts;
using Sensus.Probes.User.Scripts.ProbeTriggerProperties;
using Xamarin.Forms;
namespace Sensus.UI
{
/// <summary>
/// Allows the user to add a script trigger to a script runner.
/// </summary>
public class AddScriptTriggerPage : ContentPage
{
private ScriptRunner _scriptRunner;
private Probe _selectedProbe;
private PropertyInfo _selectedDatumProperty;
private TriggerValueCondition _selectedCondition;
private object _conditionValue;
/// <summary>
/// Initializes a new instance of the <see cref="AddScriptTriggerPage"/> class.
/// </summary>
/// <param name="scriptRunner">Script runner to add trigger to.</param>
public AddScriptTriggerPage(ScriptRunner scriptRunner)
{
_scriptRunner = scriptRunner;
Title = "Add Trigger";
var enabledProbes = _scriptRunner.Probe.Protocol.Probes.Where(p => p != _scriptRunner.Probe && p.Enabled).ToArray();
if (!enabledProbes.Any())
{
Content = new Label { Text = "No enabled probes. Please enable them before creating triggers.", FontSize = 20 };
return;
}
var contentLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.FillAndExpand
};
var probeLabel = new Label { Text = "Probe:", FontSize = 20 };
Picker probePicker = new Picker { Title = "Select Probe", HorizontalOptions = LayoutOptions.FillAndExpand };
foreach (Probe enabledProbe in enabledProbes)
{
probePicker.Items.Add(enabledProbe.DisplayName);
}
contentLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { probeLabel, probePicker }
});
StackLayout triggerDefinitionLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.Start
};
contentLayout.Children.Add(triggerDefinitionLayout);
Switch changeSwitch = new Switch();
Switch regexSwitch = new Switch();
Switch fireRepeatedlySwitch = new Switch();
TimePicker startTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand };
TimePicker endTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand };
probePicker.SelectedIndexChanged += (o, e) =>
{
_selectedProbe = null;
_selectedDatumProperty = null;
_conditionValue = null;
triggerDefinitionLayout.Children.Clear();
if (probePicker.SelectedIndex < 0)
return;
_selectedProbe = enabledProbes[probePicker.SelectedIndex];
PropertyInfo[] datumProperties = _selectedProbe.DatumType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttributes<ProbeTriggerProperty>().Any()).ToArray();
if (datumProperties.Length == 0)
return;
#region datum property picker
Label datumPropertyLabel = new Label
{
Text = "Property:",
FontSize = 20
};
Picker datumPropertyPicker = new Picker { Title = "Select Datum Property", HorizontalOptions = LayoutOptions.FillAndExpand };
foreach (PropertyInfo datumProperty in datumProperties)
{
var triggerProperty = datumProperty.GetCustomAttributes<ProbeTriggerProperty>().First();
datumPropertyPicker.Items.Add(triggerProperty.Name ?? datumProperty.Name);
}
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { datumPropertyLabel, datumPropertyPicker }
});
#endregion
#region condition picker (same for all datum types)
Label conditionLabel = new Label
{
Text = "Condition:",
FontSize = 20
};
Picker conditionPicker = new Picker { Title = "Select Condition", HorizontalOptions = LayoutOptions.FillAndExpand };
TriggerValueCondition[] conditions = Enum.GetValues(typeof(TriggerValueCondition)) as TriggerValueCondition[];
foreach (TriggerValueCondition condition in conditions)
{
conditionPicker.Items.Add(condition.ToString());
}
conditionPicker.SelectedIndexChanged += (oo, ee) =>
{
if (conditionPicker.SelectedIndex < 0)
{
return;
}
_selectedCondition = conditions[conditionPicker.SelectedIndex];
};
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { conditionLabel, conditionPicker }
});
#endregion
#region condition value for comparison, based on selected datum property -- includes change calculation (for double datum) and regex (for string datum)
StackLayout conditionValueStack = new StackLayout
{
Orientation = StackOrientation.Vertical,
HorizontalOptions = LayoutOptions.FillAndExpand
};
triggerDefinitionLayout.Children.Add(conditionValueStack);
datumPropertyPicker.SelectedIndexChanged += (oo, ee) =>
{
_selectedDatumProperty = null;
_conditionValue = null;
conditionValueStack.Children.Clear();
if (datumPropertyPicker.SelectedIndex < 0)
{
return;
}
_selectedDatumProperty = datumProperties[datumPropertyPicker.SelectedIndex];
ProbeTriggerProperty datumTriggerAttribute = _selectedDatumProperty.GetCustomAttribute<ProbeTriggerProperty>();
View conditionValueStackView = null;
bool allowChangeCalculation = false;
bool allowRegularExpression = false;
if (datumTriggerAttribute is ListProbeTriggerProperty)
{
Picker conditionValuePicker = new Picker { Title = "Select Condition Value", HorizontalOptions = LayoutOptions.FillAndExpand };
object[] items = (datumTriggerAttribute as ListProbeTriggerProperty).Items;
foreach (object item in items)
{
conditionValuePicker.Items.Add(item.ToString());
}
conditionValuePicker.SelectedIndexChanged += (ooo, eee) =>
{
if (conditionValuePicker.SelectedIndex < 0)
{
return;
}
_conditionValue = items[conditionValuePicker.SelectedIndex];
};
conditionValueStackView = conditionValuePicker;
}
else if (datumTriggerAttribute is DoubleProbeTriggerProperty)
{
Entry entry = new Entry
{
Keyboard = Keyboard.Numeric,
HorizontalOptions = LayoutOptions.FillAndExpand
};
entry.TextChanged += (ooo, eee) =>
{
double value;
if (double.TryParse(eee.NewTextValue, out value))
{
_conditionValue = value;
}
};
conditionValueStackView = entry;
allowChangeCalculation = true;
}
else if (datumTriggerAttribute is StringProbeTriggerProperty)
{
Entry entry = new Entry
{
Keyboard = Keyboard.Default,
HorizontalOptions = LayoutOptions.FillAndExpand
};
entry.TextChanged += (ooo, eee) => _conditionValue = eee.NewTextValue;
conditionValueStackView = entry;
allowRegularExpression = true;
}
else if (datumTriggerAttribute is BooleanProbeTriggerProperty)
{
Switch booleanSwitch = new Switch();
booleanSwitch.Toggled += (ooo, eee) => _conditionValue = eee.Value;
conditionValueStackView = booleanSwitch;
}
Label conditionValueStackLabel = new Label
{
Text = "Value:",
FontSize = 20
};
conditionValueStack.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { conditionValueStackLabel, conditionValueStackView }
});
#region change calculation
if (allowChangeCalculation)
{
Label changeLabel = new Label
{
Text = "Change:",
FontSize = 20
};
changeSwitch.IsToggled = false;
conditionValueStack.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { changeLabel, changeSwitch }
});
}
#endregion
#region regular expression
if (allowRegularExpression)
{
Label regexLabel = new Label
{
Text = "Regular Expression:",
FontSize = 20
};
regexSwitch.IsToggled = false;
conditionValueStack.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { regexLabel, regexSwitch }
});
}
#endregion
};
datumPropertyPicker.SelectedIndex = 0;
#endregion
#region fire repeatedly
Label fireRepeatedlyLabel = new Label
{
Text = "Fire Repeatedly:",
FontSize = 20
};
fireRepeatedlySwitch.IsToggled = false;
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { fireRepeatedlyLabel, fireRepeatedlySwitch }
});
#endregion
#region start/end times
Label startTimeLabel = new Label
{
Text = "Start Time:",
FontSize = 20
};
startTimePicker.Time = new TimeSpan(0, 0, 0);
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { startTimeLabel, startTimePicker }
});
Label endTimeLabel = new Label
{
Text = "End Time:",
FontSize = 20
};
endTimePicker.Time = new TimeSpan(23, 59, 59);
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { endTimeLabel, endTimePicker }
});
#endregion
};
probePicker.SelectedIndex = 0;
Button okButton = new Button
{
Text = "OK",
FontSize = 20,
VerticalOptions = LayoutOptions.Start
};
okButton.Clicked += async (o, e) =>
{
try
{
_scriptRunner.Triggers.Add(new Probes.User.Scripts.Trigger(_selectedProbe, _selectedDatumProperty, _selectedCondition, _conditionValue, changeSwitch.IsToggled, fireRepeatedlySwitch.IsToggled, regexSwitch.IsToggled, startTimePicker.Time, endTimePicker.Time));
await Navigation.PopAsync();
}
catch (Exception ex)
{
await SensusServiceHelper.Get().FlashNotificationAsync($"Failed to add trigger: {ex.Message}");
SensusServiceHelper.Get().Logger.Log($"Failed to add trigger: {ex.Message}", LoggingLevel.Normal, GetType());
}
};
contentLayout.Children.Add(okButton);
Content = new ScrollView
{
Content = contentLayout
};
}
}
}
| |
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using Tao.OpenGl;
using Tao.Sdl;
using Behemoth.Util;
using Behemoth.Apps;
using Behemoth.TaoUtil;
namespace Shooter
{
abstract class Entity
{
public virtual void Display(Shooter shooter, int xOffset, int yOffset)
{
shooter.DrawSprite((int)X + xOffset, (int)Y + yOffset, Frame);
}
public virtual void Update(EntityManager context)
{
}
public void SetHitBox(int x, int y, int w, int h)
{
hitBoxX = x;
hitBoxY = y;
hitBoxW = w;
hitBoxH = h;
}
public bool Intersects(Entity other)
{
return Geom.RectanglesIntersect(
hitBoxX + X, hitBoxY + Y, hitBoxW, hitBoxH,
other.hitBoxX + other.X, other.hitBoxY + other.Y, other.hitBoxW, other.hitBoxH);
}
public double X;
public double Y;
public int Frame;
private int hitBoxX = 0;
private int hitBoxY = 0;
private int hitBoxW = Shooter.spriteWidth;
private int hitBoxH = Shooter.spriteHeight;
}
class Explosion : Entity
{
public Explosion(double x, double y)
{
X = x;
Y = y;
Frame = startFrame;
cooldown = rate;
}
public override void Update(EntityManager context)
{
if (cooldown-- <= 0)
{
cooldown = rate;
Frame++;
if (Frame == endFrame)
{
context.Remove(this);
}
}
}
private const int rate = 4;
private const int startFrame = 8;
private const int endFrame = 12;
private int cooldown;
}
class Avatar : Entity
{
public Avatar()
{
Y = 8.0;
X = Shooter.pixelWidth / 2 - Shooter.spriteWidth / 2;
Frame = 16;
SetHitBox(6, 5, 4, 7);
}
public override void Update(EntityManager context)
{
if (!IsAlive)
{
return;
}
if (IsShooting)
{
if (cooldown-- <= 0)
{
Fire(context);
}
}
if (IsMovingLeft && !IsMovingRight)
{
X = Math.Max(minX, X - speed);
}
else if (IsMovingRight && !IsMovingLeft)
{
X = Math.Min(maxX, X + speed);
}
}
public override void Display(Shooter shooter, int xOff, int yOff)
{
if (!IsAlive)
{
return;
}
base.Display(shooter, xOff, yOff);
}
public void Fire(EntityManager context)
{
Media.PlaySound(Shooter.playerShotFx);
context.Add(new AvatarShot(X - 4, Y + 3));
context.Add(new AvatarShot(X + 5, Y + 3));
cooldown = firingRate;
}
public void Die(EntityManager context)
{
if (!IsAlive)
{
return;
}
Media.PlaySound(Shooter.playerExplodeFx);
isAlive = false;
context.StartGameOver();
context.Add(new Explosion(X, Y));
}
public bool IsMovingLeft;
public bool IsMovingRight;
public bool IsShooting
{
get { return isShooting; }
set
{
isShooting = value;
cooldown = 0;
}
}
public bool IsAlive { get { return isAlive; } }
private bool isAlive = true;
private bool isShooting;
private int cooldown = 0;
private const double speed = 4.0;
private const int firingRate = 2;
private const double minX = 0.0;
private const double maxX = Shooter.pixelWidth - Shooter.spriteWidth;
}
class AvatarShot : Entity
{
public AvatarShot(double x, double y)
{
X = x;
Y = y;
Frame = 12;
SetHitBox(6, 6, 3, 4);
}
public override void Update(EntityManager context)
{
foreach (Entity o in new List<Entity>(context.Entities))
{
var enemy = o as Enemy;
if (enemy != null && this.Intersects(enemy))
{
enemy.Hurt(context);
}
}
Y += speed;
if (Y > Shooter.pixelHeight + Shooter.spriteHeight)
{
context.Remove(this);
}
}
private const double speed = 5.0;
}
class Enemy : Entity
{
public Enemy(double x, double y, double dx, double dy)
{
X = x;
Y = y;
DX = dx;
DY = dy;
}
public override void Display(Shooter shooter, int xOffset, int yOffset)
{
shooter.DrawSprite(
(int)X + xOffset, (int)Y + yOffset,
damageBlink > 1 ? blinkFrame : Frame);
if (damageBlink > 0)
{
damageBlink--;
}
}
public override void Update(EntityManager context)
{
// Collision detection.
// XXX: Wasteful iterating through all, could optimize by having
// collision groups as sublists.
// XXX: Repeating the iteration pattern from EntityManager...
foreach (Entity o in new List<Entity>(context.Entities))
{
var avatar = o as Avatar;
if (avatar != null && this.Intersects(avatar))
{
avatar.Die(context);
}
}
X += DX;
Y += DY;
if (HasLeftStage) {
context.Remove(this);
}
frameCount = (frameCount + 1) % (numFrames * frameDelay);
Frame = startFrame + (frameCount / frameDelay);
}
public void Hurt(EntityManager context)
{
if (life-- < 0)
{
Die(context);
}
if (damageBlink == 0)
{
damageBlink = 2;
}
}
public void Die(EntityManager context)
{
Media.PlaySound(Shooter.enemyExplodeFx);
context.Add(new Explosion(X, Y));
context.Remove(this);
}
bool HasLeftStage { get { return Y < -Shooter.spriteHeight; } }
public double DX;
public double DY;
private int frameCount = 0;
private int life = 10;
private int damageBlink = 0;
const int startFrame = 0;
const int numFrames = 8;
const int frameDelay = 4;
const int blinkFrame = 14;
}
class EntityManager
{
public EntityManager(Shooter shooter)
{
ShooterApp = shooter;
}
public void Update()
{
// Clone the entity list so the update operations can modify the
// original list without breaking iteration.
foreach (Entity e in new List<Entity>(Entities))
{
e.Update(this);
}
}
public void Display(Shooter shooter, int xOff, int yOff)
{
foreach (Entity e in Entities)
{
e.Display(shooter, xOff, yOff);
}
}
public void Add(Entity entity)
{
Entities.Add(entity);
}
public void Remove(Entity entity)
{
Entities.Remove(entity);
}
public void StartGameOver()
{
ShooterApp.StartGameOver();
}
public IList<Entity> Entities = new List<Entity>();
public Shooter ShooterApp;
}
public class Shooter : IScreen
{
public const int pixelWidth = 240;
public const int pixelHeight = 320;
public const int spriteWidth = 16;
public const int spriteHeight = 16;
public const string playerShotFx = "pew.wav";
public const string playerExplodeFx = "player_explode.wav";
public const string enemyExplodeFx = "enemy_explode.wav";
const string spriteTexture = "sprites.png";
EntityManager entities;
Avatar avatar = new Avatar();
bool isGameOver = false;
// How many ticks does the game keep going after game over.
int gameOverCounter = 40;
Random rng = new Random();
List<Vec3> starfield = new List<Vec3>();
App App;
public static void Main(string[] args)
{
var app = new TaoApp(pixelWidth, pixelHeight, "Behemoth Shooter");
app.RegisterService(typeof(IScreen), new Shooter());
app.Run();
}
public void Init()
{
Media.AddPhysFsPath("Shooter.zip");
// Make the zip file found from build subdir too, so that it's easy to
// run the exe from the project root dir.
Media.AddPhysFsPath("build", "Shooter.zip");
entities = new EntityManager(this);
entities.Add(avatar);
InitStarfield();
App = App.Instance;
}
public void Uninit() {}
void InitStarfield()
{
for (int i = 0; i < 1000; i++)
{
starfield.Add(new Vec3(rng.Next(-pixelWidth, pixelWidth), rng.Next(1000), rng.Next(100)));
}
}
public void StartGameOver()
{
isGameOver = true;
}
public void KeyPressed(int keycode, int keyMod, char ch)
{
switch (keycode)
{
case Sdl.SDLK_ESCAPE:
App.Exit();
break;
case Sdl.SDLK_LEFT:
avatar.IsMovingLeft = true;
break;
case Sdl.SDLK_RIGHT:
avatar.IsMovingRight = true;
break;
case Sdl.SDLK_SPACE:
avatar.IsShooting = true;
break;
}
}
public void KeyReleased(int keycode)
{
switch (keycode)
{
case Sdl.SDLK_LEFT:
avatar.IsMovingLeft = false;
break;
case Sdl.SDLK_RIGHT:
avatar.IsMovingRight = false;
break;
case Sdl.SDLK_SPACE:
avatar.IsShooting = false;
break;
}
}
public void Update(double timeElapsed)
{
entities.Update();
if (isGameOver) {
if (gameOverCounter-- <= 0) {
App.Exit();
}
}
if (rng.Next(5) == 0)
{
SpawnEnemy();
}
}
public void Draw(double timeElapsed)
{
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glLoadIdentity();
Gfx.DrawStarfield(starfield, TimeUtil.CurrentSeconds * 100,
App.Service<ITaoService>().PixelScale,
App.Service<ITaoService>().PixelWidth);
entities.Display(this, 0, 0);
Sdl.SDL_GL_SwapBuffers();
}
public void RandomPoint(out int x, out int y)
{
x = rng.Next(0, pixelWidth - spriteWidth);
y = rng.Next(0, pixelHeight - spriteHeight);
}
public void SpawnEnemy()
{
double x = pixelWidth / 2 - spriteWidth / 2;
x += (rng.NextDouble() - 0.5) * pixelWidth * 2.0;
double dx = 6.0 * (rng.NextDouble() - 0.5);
entities.Add(new Enemy(x, pixelHeight + spriteHeight, dx, -4.0));
}
public void DrawSprite(float x, float y, int frame)
{
Gfx.DrawSprite(
x, y, frame, spriteWidth, spriteHeight,
App.Service<ITaoService>().Textures[spriteTexture], 8, 8);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using EditorMiniMap.Localization;
namespace EditorMiniMap
{
public delegate void SettingsChangesEvent();
[Serializable]
public class Settings
{
[field: NonSerialized]
public event SettingsChangesEvent OnSettingsChanged;
private const int DEFAULT_FONT_SIZE = 2;
private const bool DEFAULT_IS_VISIBLE = true;
private const int DEFAULT_WIDTH = 125;
private const MiniMapPosition DEFAULT_POSITION = MiniMapPosition.Right;
private const bool DEFAULT_ONLY_UPDATE_ON_TIMER = false;
private const int DEFAULT_MAX_LINE_LIMIT = 5000;
private const bool DEFAULT_SHOW_CODE_PREVIEW = true;
private const bool DEFAULT_SHOW_VERTICAL_SCROLLBAR = false;
private Color highlightColor = Color.LightGray;
private Color splitHighlightColor = Color.LightPink;
private int fontSize = DEFAULT_FONT_SIZE;
private bool isVisible = DEFAULT_IS_VISIBLE;
private int width = DEFAULT_WIDTH;
private MiniMapPosition position = DEFAULT_POSITION;
private bool onlyUpdateOnTimer = DEFAULT_ONLY_UPDATE_ON_TIMER;
private int _maxLineLimit = DEFAULT_MAX_LINE_LIMIT;
private bool showCodePreview = DEFAULT_SHOW_CODE_PREVIEW;
private bool showVerticalScrollbar = DEFAULT_SHOW_VERTICAL_SCROLLBAR;
[LocalizedCategory("EditorMiniMap.Category.UI")]
[LocalizedDisplayName("EditorMiniMap.Label.HighlightColor")]
[LocalizedDescription("EditorMiniMap.Description.HighlightColor")]
[DefaultValue(typeof(Color), "LightGray")]
public Color HighlightColor
{
get { return highlightColor; }
set
{
if (highlightColor != value)
{
highlightColor = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.UI")]
[LocalizedDisplayName("EditorMiniMap.Label.SplitHighlightColor")]
[LocalizedDescription("EditorMiniMap.Description.SplitHighlightColor")]
[DefaultValue(typeof(Color), "LightPink")]
public Color SplitHighlightColor
{
get { return splitHighlightColor; }
set
{
if (splitHighlightColor != value)
{
splitHighlightColor = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.UI")]
[LocalizedDisplayName("EditorMiniMap.Label.FontSize")]
[LocalizedDescription("EditorMiniMap.Description.FontSize")]
[DefaultValue(DEFAULT_FONT_SIZE)]
public int FontSize
{
get { return fontSize; }
set
{
if (value < 2)
value = DEFAULT_FONT_SIZE;
if (fontSize != value)
{
fontSize = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.UI")]
[LocalizedDisplayName("EditorMiniMap.Label.Width")]
[LocalizedDescription("EditorMiniMap.Description.Width")]
[DefaultValue(DEFAULT_WIDTH)]
public int Width
{
get { return width; }
set
{
if (value < 1)
value = DEFAULT_WIDTH;
if (width != value)
{
width = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.UI")]
[LocalizedDisplayName("EditorMiniMap.Label.Position")]
[LocalizedDescription("EditorMiniMap.Description.Position")]
[DefaultValue(DEFAULT_POSITION)]
public MiniMapPosition Position
{
get { return position; }
set
{
if (position != value)
{
position = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.Performance")]
[LocalizedDisplayName("EditorMiniMap.Label.UpdateOnTimer")]
[LocalizedDescription("EditorMiniMap.Description.UpdateOnTimer")]
[DefaultValue(DEFAULT_ONLY_UPDATE_ON_TIMER)]
public bool OnlyUpdateOnTimer
{
get { return onlyUpdateOnTimer; }
set
{
if (onlyUpdateOnTimer != value)
{
onlyUpdateOnTimer = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.Performance")]
[LocalizedDisplayName("EditorMiniMap.Label.MaxLineLimit")]
[LocalizedDescription("EditorMiniMap.Description.MaxLineLimit")]
[DefaultValue(DEFAULT_MAX_LINE_LIMIT)]
public int MaxLineLimit
{
get { return _maxLineLimit; }
set
{
if (value < 1)
value = DEFAULT_MAX_LINE_LIMIT;
if (_maxLineLimit != value)
{
_maxLineLimit = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.Visibility")]
[LocalizedDisplayName("EditorMiniMap.Label.IsVisible")]
[LocalizedDescription("EditorMiniMap.Description.IsVisible")]
[DefaultValue(DEFAULT_IS_VISIBLE)]
public bool IsVisible
{
get { return isVisible; }
set
{
if (isVisible != value)
{
isVisible = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.Visibility")]
[LocalizedDisplayName("EditorMiniMap.Label.ShowCodePreview")]
[LocalizedDescription("EditorMiniMap.Description.ShowCodePreview")]
[DefaultValue(DEFAULT_SHOW_CODE_PREVIEW)]
public bool ShowCodePreview
{
get { return showCodePreview; }
set
{
if (showCodePreview != value)
{
showCodePreview = value;
FireChanged();
}
}
}
[LocalizedCategory("EditorMiniMap.Category.Visibility")]
[LocalizedDisplayName("EditorMiniMap.Label.ShowVerticalScrollbar")]
[LocalizedDescription("EditorMiniMap.Description.ShowVerticalScrollbar")]
[DefaultValue(DEFAULT_SHOW_VERTICAL_SCROLLBAR)]
public bool ShowVerticalScrollbar
{
get { return showVerticalScrollbar; }
set
{
if (showVerticalScrollbar != value)
{
showVerticalScrollbar = value;
FireChanged();
}
}
}
private void FireChanged()
{
if (OnSettingsChanged != null) OnSettingsChanged();
}
}
public enum MiniMapPosition
{
Right,
Left
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Drawing;
namespace VisualWget
{
public class UserAgentItem
{
public string name;
public string value;
public UserAgentItem(string name, string value)
{
this.name = name;
this.value = value;
}
public override string ToString()
{
return this.name;
}
}
[StructLayout(LayoutKind.Sequential)]
struct HDITEM
{
public uint mask;
public int cxy;
public string pszText;
public IntPtr hbm;
public int cchTextMax;
public int fmt;
public uint lParam;
public int iImage;
public int iOrder;
public uint type;
public IntPtr pvFilter;
}
struct OptCat
{
public string name;
public OptCat(string name)
{
this.name = name;
}
}
struct Opt
{
public int i;
public int j;
public string name;
public bool needArg;
public string argumentLabel;
public string action;
public string description;
public Opt(int i, int j, string name, bool needArg, string argumentLabel, string action, string description)
{
this.i = i;
this.j = j;
this.name = name;
this.needArg = needArg;
this.argumentLabel = argumentLabel;
this.action = action;
this.description = description;
}
}
class WindowWrapper : IWin32Window
{
IntPtr handle;
public WindowWrapper(IntPtr handle)
{
this.handle = handle;
}
public IntPtr Handle
{
get
{
return handle;
}
}
}
static class Util
{
static MainForm mainForm = null;
public static MainForm MainForm
{
get
{
return mainForm;
}
set
{
mainForm = value;
}
}
static int listeningPort = -1;
public static int ListeningPort
{
get
{
return listeningPort;
}
set
{
listeningPort = value;
PutSetting("ListeningPort", listeningPort.ToString(), true);
}
}
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool AllowSetForegroundWindow(uint dwProcessId);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr GetLastActivePopup(IntPtr hWnd);
static string appDataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "KhomsanPh\\VisualWget\\2.0");
public static string AppDataDir
{
get
{
return appDataDir;
}
}
const string browserExtGuid = "{4b31ac95-6066-4d20-be12-c947eacafe2e}";
static List<OptCat> optCats = new List<OptCat>();
static List<Opt> opts = new List<Opt>();
static string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
public static string AppDir
{
get
{
return appDir;
}
}
static string wgetPath = Path.Combine(appDir, "wget.exe");
public static string WgetPath
{
get
{
return wgetPath;
}
}
public static bool InitOpts()
{
List<OptCat> optCatsTemp = new List<OptCat>();
List<Opt> optsTemp = new List<Opt>();
string optFile = Path.Combine(langFolder, string.Format("wget_{0}.opt", Util.GetSetting("Lang")));
if (!File.Exists(optFile))
{
optFile = Path.Combine(appDir, "wget.opt");
}
string[] optLines;
try
{
optLines = File.ReadAllLines(optFile);
}
catch (Exception ex)
{
MsgBox(ex.Message, MessageBoxIcon.Error);
return false;
}
int i = -2;
int j = -1;
for (int l = 0; l < optLines.Length; l++)
{
string optLine = optLines[l];
optLine = optLine.Trim();
if (optLine.StartsWith("#"))
{
continue;
}
if (optLine == "")
{
i++;
j = 0;
continue;
}
string[] optCols = optLine.Split('|');
for (int c = 0; c < optCols.Length; c++)
{
optCols[c] = optCols[c].Replace("{p}", "|");
optCols[c] = optCols[c].Trim();
}
if (optCols.Length == 1 && i == -1)
{
optCatsTemp.Add(new OptCat(optCols[0]));
j++;
}
else if (optCols.Length == 5)
{
optsTemp.Add(new Opt(
i,
j,
optCols[0],
bool.Parse(optCols[1]),
optCols[2],
optCols[3],
optCols[4]));
j++;
}
else
{
MsgBox(string.Format(Util.translationList["000187"], optFile), MessageBoxIcon.Error);
return false;
}
}
optCats = optCatsTemp;
opts = optsTemp;
return true;
}
public static OptCat GetOptCatByIndex(int i)
{
Debug.Assert(i < optCats.Count);
return optCats[i];
}
public static Opt GetOptByIndex(int i)
{
Debug.Assert(i < opts.Count);
return opts[i];
}
public static Opt GetOptByName(string name)
{
for (int index = 0; index < opts.Count; index++)
{
if (GetOptByIndex(index).name == name)
{
return opts[index];
}
}
return new Opt(-1, -1, "", false, "", "", "");
}
public static int GetOptIndex(int i, int j)
{
for (int index = 0; index < opts.Count; index++)
{
if (GetOptByIndex(index).i == i && GetOptByIndex(index).j == j)
{
return index;
}
}
return -1;
}
public static string[] GetArrayOfOpts(int i)
{
List<string> list = new List<string>();
for (int index = 0; index < opts.Count; index++)
{
if (GetOptByIndex(index).i == i)
{
string s = "--" + GetOptByIndex(index).name;
if (GetOptByIndex(index).needArg)
{
s += "=" + GetOptByIndex(index).argumentLabel;
}
list.Add(s);
}
}
return list.ToArray();
}
public static string[] GetArrayOfOptCats()
{
List<string> list = new List<string>();
for (int index = 0; index < optCats.Count; index++)
{
list.Add(GetOptCatByIndex(index).name);
}
return list.ToArray();
}
public static bool IsDownloadUIEnabled()
{
object value = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer", "DownloadUI", "");
return (value == null) ? false : (value.ToString() == browserExtGuid);
}
static bool extIsEnabling = false;
public static bool ExtIsEnabling
{
get
{
return extIsEnabling;
}
}
#if false // removed
public static void EnableDownloadUI(bool enable)
{
extIsEnabling = true;
if (enable)
{
if (!IsBrowserExtRegistered(custDMExtPath))
{
if (!RegisterBrowserExt())
{
MsgBox(Util.translationList["000183"], MessageBoxIcon.Error);
return;
}
}
}
RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Internet Explorer", true);
if (rk != null)
{
object value = rk.GetValue("DownloadUI");
if (value != null)
{
if (value.ToString() == browserExtGuid)
{
if (!enable)
{
rk.DeleteValue("DownloadUI");
}
}
else
{
if (enable)
{
if (Util.MsgBox(Util.translationList["000193"],
MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
== DialogResult.Yes)
{
rk.SetValue("DownloadUI", browserExtGuid);
}
}
}
}
else
{
if (enable)
{
rk.SetValue("DownloadUI", browserExtGuid);
}
}
rk.Close();
}
extIsEnabling = false;
}
#endif
public static void GetOpt(string cmdLineArgs, out StringCollection urls, out StringDictionary opts)
{
urls = new StringCollection();
opts = new StringDictionary();
string[] args = Util.CmdLineArgsToArgs(cmdLineArgs);
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
if (arg.StartsWith("--"))
{
string optName, optArg;
int index = arg.IndexOf("=");
if (index != -1)
{
optName = arg.Substring(2, index - 2);
optArg = arg.Substring(index + 1);
}
else
{
optName = arg.Substring(2);
optArg = null;
}
Opt opt = GetOptByName(optName);
if (opt.i == -1
|| opt.needArg && optArg == null
|| !opt.needArg && optArg != null)
{
continue;
}
opts.Add(optName, optArg);
}
else
{
urls.Add(arg);
}
}
}
public static string GetFileName(string path)
{
if (path == null || path == "")
{
return path;
}
int nLast = path.LastIndexOf(Path.DirectorySeparatorChar);
if (nLast >= 0)
{
return path.Substring(nLast + 1);
}
return path;
}
public static string GetAssemblyTitle()
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyTitleAttribute)attributes[0]).Title;
}
public static string GetAssemblyCopyright()
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
public static DialogResult MsgBox(string text, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
{
if (mainForm != null)
{
if (!mainForm.Visible)
{
mainForm.Show();
}
if (mainForm.WindowState == FormWindowState.Minimized)
{
ShowWindow(mainForm.Handle, 9 /* SW_RESTORE */);
}
mainForm.SetAsForegroundWindow();
return MessageBox.Show(new WindowWrapper(GetLastActivePopup(mainForm.Handle)), text, Application.ProductName, buttons, icon, defaultButton);
}
else
{
return MessageBox.Show(text, Application.ProductName, buttons, icon, defaultButton);
}
}
public static DialogResult MsgBox(string text, MessageBoxButtons buttons, MessageBoxIcon icon)
{
return MsgBox(text, buttons, icon, MessageBoxDefaultButton.Button1);
}
public static DialogResult MsgBox(string text, MessageBoxIcon icon)
{
return MsgBox(text, MessageBoxButtons.OK, icon);
}
public static DialogResult MsgBox(string text)
{
return MsgBox(text, MessageBoxIcon.Information);
}
#if false // removed
static string appVer = "2.4a3u1";
public static string AppVer
{
get
{
return appVer;
}
}
static string releaseDate = "July 29, 2010";
public static string ReleaseDate
{
get
{
return releaseDate;
}
}
#endif
public static int GetTimeBetweenRetryAttempts()
{
int[] times = { 1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600 };
int index = int.Parse(Util.GetSetting("TimeBetweenRetryAttempts"));
Debug.Assert(index >= 0 && index < 10);
if (index >= 0 && index < 10)
{
return times[index];
}
return times[2];
}
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint Msg, uint wParam, ref HDITEM lParam);
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint Msg, uint wParam, IntPtr lParam);
public static void SetListViewHeaderArrow(ListView listView, int columnIndex, bool isAscending)
{
IntPtr header = (IntPtr)SendMessage(listView.Handle, 0x1000 + 31 /* LVM_GETHEADER */, 0, 0);
for (int i = 0; i < listView.Columns.Count; i++)
{
HDITEM hdi = new HDITEM();
hdi.mask = 0x0004 /* HDI_FORMAT */;
SendMessage(header, 0x1200 + 11 /* HDM_GETITEM */, (uint)i, ref hdi);
hdi.fmt &= ~(0x0200 /* HDF_SORTDOWN */ | 0x0400 /* HDF_SORTUP */);
if (i == columnIndex)
{
hdi.fmt |= isAscending ? 0x0400 /* HDF_SORTUP */ : 0x0200 /* HDF_SORTDOWN */;
}
SendMessage(header, 0x1200 + 12 /* HDM_SETITEM */, (uint)i, ref hdi);
}
SendMessage(listView.Handle, 0x1000 + 140 /* LVM_SETSELECTEDCOLUMN */, (uint)columnIndex, 0);
}
public static bool SetListViewColumnOrder(ListView listView, int[] columnOrderArray)
{
IntPtr buffer = Marshal.AllocHGlobal(sizeof(Int32) * columnOrderArray.Length);
for (int i = 0; i < columnOrderArray.Length; i++)
{
Marshal.WriteInt32(buffer, i * sizeof(Int32), columnOrderArray[i]);
}
bool success = (SendMessage(listView.Handle, 0x1000 + 58 /* LVM_SETCOLUMNORDERARRAY */, (uint)listView.Columns.Count, buffer) != 0);
Marshal.FreeHGlobal(buffer);
return success;
}
public static bool GetListViewColumnOrder(ListView listView, out int[] columnOrderArray)
{
List<int> columnOrderList = new List<int>();
IntPtr buffer = Marshal.AllocHGlobal(sizeof(Int32) * listView.Columns.Count);
bool success = (SendMessage(listView.Handle, 0x1000 + 59 /* LVM_GETCOLUMNORDERARRAY */, (uint)listView.Columns.Count, buffer) != 0);
if (success)
{
for (int i = 0; i < listView.Columns.Count; i++)
{
columnOrderList.Add(Marshal.ReadInt32(buffer, i * sizeof(Int32)));
}
columnOrderArray = columnOrderList.ToArray();
}
else
{
columnOrderArray = null;
}
Marshal.FreeHGlobal(buffer);
return success;
}
public static string GetSizeText(long size)
{
string sizeUnit = Util.GetSetting("SizeUnit");
string text;
if (sizeUnit == "B")
{
if (size < 0)
{
text = "";
}
else if (size == 0)
{
text = Util.translationList["000149"];
}
else
{
text = string.Format("{0} {1}", size, Util.translationList["000150"]);
}
}
else if (sizeUnit == "KB")
{
if (size < 0)
{
text = "";
}
else if (size == 0)
{
text = Util.translationList["000149"];
}
else
{
double value = size / 1024.0;
text = string.Format("{0:F0} {1}", value, Util.translationList["000151"]);
}
}
else if (sizeUnit == "MB")
{
if (size < 0)
{
text = "";
}
else if (size == 0)
{
text = Util.translationList["000149"];
}
else
{
double value = size / (1024.0 * 1024.0);
text = string.Format("{0:F0} {1}", value, Util.translationList["000152"]);
}
}
else if (sizeUnit == "GB")
{
if (size < 0)
{
text = "";
}
else if (size == 0)
{
text = Util.translationList["000149"];
}
else
{
double value = size / (1024.0 * 1024.0 * 1024.0);
text = string.Format("{0:F0} {1}", value, Util.translationList["000153"]);
}
}
else if (sizeUnit == "TB")
{
if (size < 0)
{
text = "";
}
else if (size == 0)
{
text = Util.translationList["000149"];
}
else
{
double value = size / (1024.0 * 1024.0 * 1024.0 * 1024.0);
text = string.Format("{0:F0} {1}", value, Util.translationList["000154"]);
}
}
else
{
if (size < 0)
{
text = "";
}
else if (size == 0)
{
text = Util.translationList["000149"];
}
else if (size < 1024)
{
text = string.Format("{0} {1}", size, Util.translationList["000150"]);
}
else if (size < 1024 * 1024)
{
double value = size / 1024.0;
if (value < 9.995)
{
text = string.Format("{0:F} {1}", value, Util.translationList["000151"]);
}
else if (value < 99.95)
{
text = string.Format("{0:F1} {1}", value, Util.translationList["000151"]);
}
else
{
text = string.Format("{0:F0} {1}", value, Util.translationList["000151"]);
}
}
else if (size < 1024 * 1024 * 1024)
{
double value = size / (1024.0 * 1024.0);
if (value < 9.995)
{
text = string.Format("{0:F} {1}", value, Util.translationList["000152"]);
}
else if (value < 99.95)
{
text = string.Format("{0:F1} {1}", value, Util.translationList["000152"]);
}
else
{
text = string.Format("{0:F0} {1}", value, Util.translationList["000152"]);
}
}
else if (size < 1024.0 * 1024 * 1024 * 1024)
{
double value = size / (1024.0 * 1024.0 * 1024.0);
if (value < 9.995)
{
text = string.Format("{0:F} {1}", value, Util.translationList["000153"]);
}
else if (value < 99.95)
{
text = string.Format("{0:F1} {1}", value, Util.translationList["000153"]);
}
else
{
text = string.Format("{0:F0} {1}", value, Util.translationList["000153"]);
}
}
else
{
double value = size / (1024.0 * 1024.0 * 1024.0 * 1024.0);
if (value < 9.995)
{
text = string.Format("{0:F} {1}", value, Util.translationList["000154"]);
}
else if (value < 99.95)
{
text = string.Format("{0:F1} {1}", value, Util.translationList["000154"]);
}
else
{
text = string.Format("{0:F0} {1}", value, Util.translationList["000154"]);
}
}
}
return text;
}
public static string GetSpeedText(long speed)
{
string text;
if (speed < 0)
{
text = "";
}
else if (speed < 1024)
{
text = string.Format("{0} {1}", speed, Util.translationList["000161"]);
}
else if (speed < 1024 * 1024)
{
double value = speed / 1024.0;
if (value < 9.995)
{
text = string.Format("{0:F} {1}", value, Util.translationList["000162"]);
}
else if (value < 99.95)
{
text = string.Format("{0:F1} {1}", value, Util.translationList["000162"]);
}
else
{
text = string.Format("{0:F0} {1}", value, Util.translationList["000162"]);
}
}
else if (speed < 1024 * 1024 * 1024)
{
double value = speed / (1024.0 * 1024.0);
if (value < 9.995)
{
text = string.Format("{0:F} {1}", value, Util.translationList["000163"]);
}
else if (value < 99.95)
{
text = string.Format("{0:F1} {1}", value, Util.translationList["000163"]);
}
else
{
text = string.Format("{0:F0} {1}", value, Util.translationList["000163"]);
}
}
else
{
double value = speed / (1024.0 * 1024.0 * 1024.0);
if (value < 9.995)
{
text = string.Format("{0:F} {1}", value, Util.translationList["000164"]);
}
else if (value < 99.95)
{
text = string.Format("{0:F1} {1}", value, Util.translationList["000164"]);
}
else
{
text = string.Format("{0:F0} {1}", value, Util.translationList["000164"]);
}
}
return text;
}
public static string GetHexString(byte[] bytes)
{
string hashString = "";
for (int i = 0; i < bytes.Length; i++)
{
hashString += string.Format("{0:x2}", bytes[i]);
}
return hashString;
}
public static string ComputeMD5Hash(string path)
{
return GetHexString((new MD5CryptoServiceProvider()).ComputeHash(File.OpenRead(path)));
}
public static string ComputeSHA1Hash(string path)
{
return GetHexString((new SHA1CryptoServiceProvider()).ComputeHash(File.OpenRead(path)));
}
static string regSubKeyName = "Software\\KhomsanPh\\VisualWget\\2.0";
static string regKeyName = "HKEY_CURRENT_USER\\" + regSubKeyName;
static string vwgetCfgPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "VisualWget.cfg");
struct Setting
{
public string name;
public string value;
public string defaultValue;
public Setting(string name, string defaultValue)
{
this.name = name;
value = null;
this.defaultValue = defaultValue;
}
}
static bool settingsNeedToSave = false;
static Setting[] settings =
{
new Setting("AlwaysShowTrayIcon", bool.TrueString),
new Setting("AutoRemoveFinishedJob", bool.FalseString),
new Setting("CheckForUpdates", bool.FalseString),
new Setting("CheckForUpdatesInterval", "1"),
new Setting("CheckForUpdatesTime", "-1"),
new Setting("CloseToTray", bool.FalseString),
new Setting("DefDlAutoStartNumDays", "0"),
new Setting("DefDlAutoStartNumHours", "0"),
new Setting("DefDlOptions", "--continue --directory-prefix=" + AddQuotes(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)) + " --timestamping"),
new Setting("DetectClipboard", bool.FalseString),
new Setting("DirPrefix0", ""),
new Setting("DirPrefix1", ""),
new Setting("DirPrefix2", ""),
new Setting("DirPrefix3", ""),
new Setting("DirPrefix4", ""),
new Setting("DirPrefix5", ""),
new Setting("DirPrefix6", ""),
new Setting("DirPrefix7", ""),
new Setting("FirstTimeRunning", bool.TrueString),
new Setting("FtpProxy", ""),
new Setting("FontName", "Tahoma"),
new Setting("FontSize", (8.25F).ToString()),
new Setting("FontStyle", "Regular"),
new Setting("FontGdiCharSet", "0"),
new Setting("Lang", "en"),
new Setting("ListeningPort", "-1"),
new Setting("LogHeight", "172"),
new Setting("Height", "600"),
new Setting("HideConsole", bool.TrueString),
new Setting("HttpProxy", ""),
new Setting("HttpsProxy", ""),
new Setting("JobDialogStartOnOk", bool.TrueString),
new Setting("JobsListViewColumnOrderArray", "0,1,2,3,4,5,6,7"),
new Setting("JobsListViewColumnWidthArray", "170,35,75,75,80,80,75,170"),
new Setting("JobsListViewSortAsc", bool.TrueString),
new Setting("JobsListViewSortCol", "1"),
new Setting("ListViewDoubleClickOpen", bool.TrueString),
new Setting("MaxRunningJobs", "5"),
new Setting("MinimizeToTray", bool.FalseString),
new Setting("NoPromptOnNewJob", bool.FalseString),
new Setting("NoProxy", ""),
new Setting("PlayDownloadFinishedSound", bool.FalseString),
new Setting("PlayAllDownloadsFinishedSound", bool.FalseString),
new Setting("PromptWhenOpenFileTypes", "exe,com,pif,bat,scr"),
new Setting("RedirectOutput", bool.TrueString),
new Setting("Retry", bool.TrueString),
new Setting("RetryAttempts", "30"),
new Setting("ShowBalloonTip", bool.TrueString),
new Setting("ShowLog", bool.TrueString),
new Setting("ShowStatusBar", bool.TrueString),
new Setting("ShowToolbar", bool.TrueString),
new Setting("SizeUnit", "Auto"),
new Setting("SpeedLimit", "0"),
new Setting("SpeedLimitList", "4096,2048,1024,512,256,128,64,32,16,8,4,2"),
new Setting("TimeBetweenRetryAttempts", "2"),
new Setting("WhenDownloadsFinishedFreeze", bool.FalseString),
new Setting("WhenDownloadsFinishedFreezedValue", AutoShutdownAction.None.ToString()),
new Setting("WhenDownloadsFinishedCancelable", bool.TrueString),
new Setting("Width", "800"),
new Setting("WindowState", "Normal"),
new Setting("X", "20"),
new Setting("Y", "15")
};
static string LoadCfgSetting(string settingName, string defaultValue, string cfgPath)
{
string[] lines = File.ReadAllLines(cfgPath);
foreach (string line in lines)
{
string[] segments = line.Split(new char[] { '=' }, 2);
if (segments.Length == 2)
{
string name = segments[0].Trim();
if (string.Compare(name, settingName, true) == 0)
{
string value = segments[1].Trim();
return value;
}
}
}
return defaultValue;
}
static string LoadVisualWgetCfgSetting(string settingName, string defaultValue)
{
return LoadCfgSetting(settingName, defaultValue, vwgetCfgPath);
}
static void LoadVisualWgetCfg()
{
StringDictionary sd = new StringDictionary();
string[] lines = File.ReadAllLines(vwgetCfgPath);
foreach (string line in lines)
{
string[] segments = line.Split(new char[] { '=' }, 2);
if (segments.Length == 2)
{
string name = segments[0].Trim();
string value = segments[1].Trim();
sd.Add(name, value);
}
}
for (int i = 0; i < settings.Length; i++)
{
Setting setting = settings[i];
if (sd.ContainsKey(setting.name))
{
setting.value = sd[setting.name];
}
else
{
setting.value = setting.defaultValue;
}
settings[i] = setting;
}
}
static void SaveVisualWgetCfg()
{
List<string> lines = new List<string>();
for (int i = 0; i < settings.Length; i++)
{
Setting setting = settings[i];
if (setting.value != null
&& setting.value != setting.defaultValue)
{
lines.Add(setting.name + " = " + setting.value);
}
}
File.WriteAllLines(vwgetCfgPath, lines.ToArray());
}
public static void LoadSettings()
{
if (IsPortableApp())
{
LoadVisualWgetCfg();
}
else
{
foreach (Setting setting in settings)
{
GetSetting(setting.name);
}
}
}
public static string GetDefaultSetting(string settingName)
{
for (int i = 0; i < settings.Length; i++)
{
Setting setting = settings[i];
if (string.Compare(setting.name, settingName, true) == 0)
{
return setting.defaultValue;
}
}
return "";
}
public static string GetSetting(string settingName, bool load)
{
for (int i = 0; i < settings.Length; i++)
{
Setting setting = settings[i];
if (string.Compare(setting.name, settingName, true) == 0)
{
if (setting.value != null && !load)
{
return setting.value;
}
if (IsPortableApp())
{
setting.value = LoadVisualWgetCfgSetting(setting.name, setting.defaultValue);
}
else
{
object value = Registry.GetValue(regKeyName, settingName, setting.defaultValue);
setting.value = ((value == null) ? setting.defaultValue : value.ToString());
}
settings[i] = setting;
return setting.value;
}
}
Debug.Assert(false);
return "";
}
public static string GetSetting(string settingName)
{
return GetSetting(settingName, false);
}
public static void PutSetting(string settingName, string settingValue, bool save)
{
for (int i = 0; i < settings.Length; i++)
{
Setting setting = settings[i];
if (setting.name == settingName)
{
setting.value = settingValue;
settings[i] = setting;
if (save)
{
if (IsPortableApp())
{
try
{
SaveVisualWgetCfg();
}
catch
{
}
}
else
{
Registry.SetValue(regKeyName, settingName, settingValue);
}
}
else
{
settingsNeedToSave = true;
}
break;
}
}
}
public static void PutSetting(string settingName, string settingValue)
{
//Console.Write(settingName);
//Console.Write("=");
//Console.WriteLine(settingValue);
PutSetting(settingName, settingValue, false);
}
public static void SaveSettings()
{
if (settingsNeedToSave == false) return;
settingsNeedToSave = false;
//Console.WriteLine("SaveSettings");
if (IsPortableApp())
{
try
{
SaveVisualWgetCfg();
}
catch (Exception ex)
{
Util.MsgBox(string.Format(Util.translationList["000190"], ex.Message), MessageBoxIcon.Error);
}
}
else
{
try
{
Registry.CurrentUser.DeleteSubKeyTree(regSubKeyName);
}
catch
{
}
for (int i = 0; i < settings.Length; i++)
{
Setting setting = settings[i];
if (setting.value != null
&& setting.value != setting.defaultValue)
{
Registry.SetValue(regKeyName, setting.name, setting.value);
}
}
}
}
public static bool IsPortableApp()
{
return true;
//return File.Exists(vwgetCfgPath);
}
public static string AddQuotes(string s)
{
string result = "\"";
string t = s;
int i = t.IndexOf("\"");
int j;
while (i != -1)
{
result += t.Substring(0, i);
for (j = i - 1; j >= 0; j--)
{
if (t[j] == '\\')
{
result += "\\";
}
else
{
break;
}
}
result += "\\\"";
t = t.Substring(i + 1);
if (t == "")
{
break;
}
i = t.IndexOf("\"");
}
result += t;
for (j = t.Length - 1; j >= 0; j--)
{
if (t[j] == '\\')
{
result += "\\";
}
else
{
break;
}
}
result += "\"";
return result;
}
[DllImport("shell32.dll")]
static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);
public static string[] CmdLineArgsToArgs(string cmdLineArgs)
{
string executableName;
return CommandLineToArgs("executableName " + cmdLineArgs, out executableName);
}
static string[] CommandLineToArgs(string commandLine, out string executableName)
{
int argCount;
IntPtr result = CommandLineToArgvW(commandLine, out argCount);
if (result == IntPtr.Zero)
{
throw new Win32Exception();
}
else
{
try
{
executableName = Marshal.PtrToStringUni(Marshal.ReadIntPtr(result, 0 * IntPtr.Size));
string[] args = new string[argCount - 1];
for (int i = 0; i < args.Length; i++)
{
args[i] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(result, (i + 1) * IntPtr.Size));
}
return args;
}
finally
{
Marshal.FreeHGlobal(result);
}
}
}
public static string ArgsToCmdLineArgs(string[] args)
{
string s = "";
for (int i = 0; i < args.Length; i++)
{
s += AddQuotes(args[i]) + " ";
}
return s.Trim();
}
[DllImport("kernel32.dll")]
static extern bool SetProcessWorkingSetSize(IntPtr hProcess, uint dwMinimumWorkingSetSize, uint dwMaximumWorkingSetSize);
public static bool TrimCurrentProcessWorkingSet()
{
return SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, unchecked((uint)-1), unchecked((uint)-1));
}
static Random rand = new Random();
public static int Rand(int max)
{
return rand.Next(max);
}
static string cmdLineArgs = "";
public static string CmdLineArgs
{
get
{
return cmdLineArgs;
}
set
{
cmdLineArgs = value;
}
}
static bool startInTray = false;
public static bool StartInTray
{
get
{
return startInTray;
}
set
{
startInTray = value;
}
}
[DllImport("user32.dll")]
public static extern bool GetUpdateRect(IntPtr hWnd, out RECT lpRect, bool bErase);
[DllImport("wtsapi32.dll")]
public static extern bool WTSShutdownSystem(IntPtr hServer, uint ShutdownFlag);
[DllImport("wtsapi32.dll")]
public static extern bool WTSLogoffSession(IntPtr hServer, uint SessionId, bool bWait);
[DllImport("user32.dll")]
public static extern bool LockWorkStation();
public static StringDictionary translationList = new StringDictionary();
static string langFolder = Path.Combine(appDir, "Lang");
public static string LangFolder
{
get
{
return langFolder;
}
}
public static void LoadLang()
{
Util.translationList.Clear();
string lang = Util.GetSetting("Lang");
string path = Path.Combine(Util.LangFolder, lang + ".txt");
if (lang != "en" && !File.Exists(path))
{
lang = "en";
path = Path.Combine(Util.LangFolder, lang + ".txt");
}
string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (line.StartsWith("#") || line == "")
{
continue;
}
string[] cols = line.Split(new char[] { '=' }, 2);
Util.translationList.Add(cols[0].Trim(), cols[1].Trim().Replace("\\n", "\n"));
}
}
static string checkForUpdatesTemp = null;
public static string CheckForUpdatesTemp
{
get
{
return checkForUpdatesTemp;
}
set
{
checkForUpdatesTemp = value;
}
}
static string currentClipboardText = null;
public static string CurrentClipboardText
{
get
{
return currentClipboardText;
}
set
{
currentClipboardText = value;
}
}
public static void SetToolTip(ToolTip tt, Control.ControlCollection col)
{
//
// not used now
//
#if false
foreach (Control ctl in col) {
if (ctl.HasChildren) {
SetToolTip(tt, ctl.Controls);
}
//Console.WriteLine(ctl.GetType().ToString());
if (ctl is Label || ctl is CheckBox || ctl is Button) {
StringBuilder sb = new StringBuilder(ctl.Text);
for (int i = 0; i < sb.Length; i++) {
if (sb[i] == '&') {
sb.Remove(i, 1);
}
}
tt.SetToolTip(ctl, sb.ToString());
}
}
#endif
}
public static bool IsRunWhenLogOn()
{
object temp = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
false
).GetValue("QuickPrint");
if (temp == null)
{
return false;
}
string value1 = temp.ToString();
string value2 = string.Format("\"{0}\" --start-in-tray", Path.Combine(Util.AppDir, "QuickPrint.exe"));
return (string.Compare(value1, value2, true) == 0);
}
public static Font GetInterfaceFont()
{
string fontName = Util.GetSetting("FontName");
float fontSize = float.Parse(Util.GetSetting("FontSize"));
FontStyle fontStyle = (FontStyle)(Enum.Parse(typeof(FontStyle), Util.GetSetting("FontStyle")));
byte fontGdiCharSet = byte.Parse(Util.GetSetting("FontGdiCharSet"));
return new Font(fontName, fontSize, fontStyle, GraphicsUnit.Point, fontGdiCharSet);
}
public static bool IsDefaultFont()
{
string fontName = Util.GetSetting("FontName");
float fontSize = float.Parse(Util.GetSetting("FontSize"));
FontStyle fontStyle = (FontStyle)(Enum.Parse(typeof(FontStyle), Util.GetSetting("FontStyle")));
byte fontGdiCharSet = byte.Parse(Util.GetSetting("FontGdiCharSet"));
if (fontName != "Tahoma")
{
return false;
}
if (fontSize != 8.25F)
{
return false;
}
if (fontStyle != FontStyle.Regular)
{
return false;
}
if (fontGdiCharSet.ToString() != "0")
{
return false;
}
return true;
}
public static string GetTextFromClipboard()
{
//
// http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.aspx
//
string clipboardText = "";
// Declares an IDataObject to hold the data returned from the clipboard.
// Retrieves the data from the clipboard.
IDataObject iData = Clipboard.GetDataObject();
// Determines whether the data is in a format you can use.
if (iData.GetDataPresent(DataFormats.Text))
{
// Yes it is.
clipboardText = (String)iData.GetData(DataFormats.Text);
}
else
{
// No it is not.
}
return clipboardText;
}
public static bool IsDownloadable(string text)
{
if (text.StartsWith("http://"))
{
return true;
}
if (text.StartsWith("https://"))
{
return true;
}
if (text.StartsWith("ftp://"))
{
return true;
}
return false;
}
public static void DoAutoShutdown(AutoShutdownAction action)
{
if (action == AutoShutdownAction.Quit)
{
Application.Exit();
}
else if (action == AutoShutdownAction.StandBy)
{
Application.SetSuspendState(PowerState.Suspend, false, false);
}
else if (action == AutoShutdownAction.Hibernate)
{
Application.SetSuspendState(PowerState.Hibernate, false, false);
}
else if (action == AutoShutdownAction.TurnOff)
{
Util.WTSShutdownSystem(IntPtr.Zero, 0x00000008 /* WTS_WSD_POWEROFF */);
}
else if (action == AutoShutdownAction.Restart)
{
Util.WTSShutdownSystem(IntPtr.Zero, 0x00000004 /* WTS_WSD_REBOOT */);
}
else if (action == AutoShutdownAction.LogOff)
{
Util.WTSLogoffSession(IntPtr.Zero, unchecked((uint)-1), false);
}
else if (action == AutoShutdownAction.LockComputer)
{
Util.LockWorkStation();
}
else
{
Debug.Assert(false);
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: System.Threading.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace System.Threading
{
/// <summary>
/// <para>A <c> Thread </c> is a concurrent unit of execution. It has its own call stack for methods being invoked, their arguments and local variables. Each application has at least one thread running when it is started, the main thread, in the main ThreadGroup. The runtime keeps its own threads in the system thread group.</para><para>There are two ways to execute code in a new thread. You can either subclass <c> Thread </c> and overriding its run() method, or construct a new <c> Thread </c> and pass a Runnable to the constructor. In either case, the start() method must be called to actually execute the new <c> Thread </c> .</para><para>Each <c> Thread </c> has an integer priority that affect how the thread is scheduled by the OS. A new thread inherits the priority of its parent. A thread's priority can be set using the setPriority(int) method. </para>
/// </summary>
/// <java-name>
/// java/lang/Thread
/// </java-name>
[Dot42.DexImport("java/lang/Thread", AccessFlags = 33)]
public partial class Thread : global::Java.Lang.IRunnable
/* scope: __dot42__ */
{
/// <summary>
/// <para>The maximum priority value allowed for a thread. This corresponds to (but does not have the same value as) <c> android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY </c> . </para>
/// </summary>
/// <java-name>
/// MAX_PRIORITY
/// </java-name>
[Dot42.DexImport("MAX_PRIORITY", "I", AccessFlags = 25)]
public const int MAX_PRIORITY = 10;
/// <summary>
/// <para>The minimum priority value allowed for a thread. This corresponds to (but does not have the same value as) <c> android.os.Process.THREAD_PRIORITY_LOWEST </c> . </para>
/// </summary>
/// <java-name>
/// MIN_PRIORITY
/// </java-name>
[Dot42.DexImport("MIN_PRIORITY", "I", AccessFlags = 25)]
public const int MIN_PRIORITY = 1;
/// <summary>
/// <para>The normal (default) priority value assigned to the main thread. This corresponds to (but does not have the same value as) <c> android.os.Process.THREAD_PRIORITY_DEFAULT </c> . </para>
/// </summary>
/// <java-name>
/// NORM_PRIORITY
/// </java-name>
[Dot42.DexImport("NORM_PRIORITY", "I", AccessFlags = 25)]
public const int NORM_PRIORITY = 5;
/// <summary>
/// <para>Constructs a new <c> Thread </c> with no <c> Runnable </c> object and a newly generated name. The new <c> Thread </c> will belong to the same <c> ThreadGroup </c> as the <c> Thread </c> calling this constructor.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Thread() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new <c> Thread </c> with a <c> Runnable </c> object and a newly generated name. The new <c> Thread </c> will belong to the same <c> ThreadGroup </c> as the <c> Thread </c> calling this constructor.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Runnable;)V", AccessFlags = 1)]
public Thread(global::Java.Lang.IRunnable runnable) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new <c> Thread </c> with a <c> Runnable </c> object and name provided. The new <c> Thread </c> will belong to the same <c> ThreadGroup </c> as the <c> Thread </c> calling this constructor.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Runnable;Ljava/lang/String;)V", AccessFlags = 1)]
public Thread(global::Java.Lang.IRunnable runnable, string threadName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new <c> Thread </c> with a <c> Runnable </c> object and a newly generated name. The new <c> Thread </c> will belong to the same <c> ThreadGroup </c> as the <c> Thread </c> calling this constructor.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public Thread(string runnable) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new <c> Thread </c> with a <c> Runnable </c> object and name provided. The new <c> Thread </c> will belong to the same <c> ThreadGroup </c> as the <c> Thread </c> calling this constructor.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/Runnable;)V", AccessFlags = 1)]
public Thread(global::Java.Lang.ThreadGroup runnable, global::Java.Lang.IRunnable threadName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new <c> Thread </c> with a <c> Runnable </c> object, the given name and belonging to the <c> ThreadGroup </c> passed as parameter.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/Runnable;Ljava/lang/String;)V", AccessFlags = 1)]
public Thread(global::Java.Lang.ThreadGroup group, global::Java.Lang.IRunnable runnable, string threadName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new <c> Thread </c> with a <c> Runnable </c> object and name provided. The new <c> Thread </c> will belong to the same <c> ThreadGroup </c> as the <c> Thread </c> calling this constructor.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V", AccessFlags = 1)]
public Thread(global::Java.Lang.ThreadGroup runnable, string threadName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new <c> Thread </c> with a <c> Runnable </c> object, the given name and belonging to the <c> ThreadGroup </c> passed as parameter.</para><para><para>java.lang.ThreadGroup </para><simplesectsep></simplesectsep><para>java.lang.Runnable </para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/Runnable;Ljava/lang/String;J)V", AccessFlags = 1)]
public Thread(global::Java.Lang.ThreadGroup group, global::Java.Lang.IRunnable runnable, string threadName, long stackSize) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the number of active <c> Thread </c> s in the running <c> Thread </c> 's group and its subgroups.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of <c> Thread </c> s </para>
/// </returns>
/// <java-name>
/// activeCount
/// </java-name>
[Dot42.DexImport("activeCount", "()I", AccessFlags = 9)]
public static int ActiveCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Does nothing. </para>
/// </summary>
/// <java-name>
/// checkAccess
/// </java-name>
[Dot42.DexImport("checkAccess", "()V", AccessFlags = 17)]
public void CheckAccess() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the number of stack frames in this thread.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>The results of this call were never well defined. To make things worse, it would depend on whether the Thread was suspended or not, and suspend was deprecated too. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Number of stack frames </para>
/// </returns>
/// <java-name>
/// countStackFrames
/// </java-name>
[Dot42.DexImport("countStackFrames", "()I", AccessFlags = 1)]
public virtual int CountStackFrames() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the Thread of the caller, that is, the current Thread.</para><para></para>
/// </summary>
/// <returns>
/// <para>the current Thread. </para>
/// </returns>
/// <java-name>
/// currentThread
/// </java-name>
[Dot42.DexImport("currentThread", "()Ljava/lang/Thread;", AccessFlags = 9)]
public static global::System.Threading.Thread GetCurrentThread() /* MethodBuilder.Create */
{
return default(global::System.Threading.Thread);
}
/// <summary>
/// <para>Throws <c> UnsupportedOperationException </c> . <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Not implemented. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// destroy
/// </java-name>
[Dot42.DexImport("destroy", "()V", AccessFlags = 1)]
public virtual void Destroy() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Prints to the standard error stream a text representation of the current stack for this Thread.</para><para><para>Throwable::printStackTrace() </para></para>
/// </summary>
/// <java-name>
/// dumpStack
/// </java-name>
[Dot42.DexImport("dumpStack", "()V", AccessFlags = 9)]
public static void DumpStack() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Copies an array with all Threads which are in the same ThreadGroup as the receiver - and subgroups - into the array <code>threads</code> passed as parameter. If the array passed as parameter is too small no exception is thrown - the extra elements are simply not copied.</para><para></para>
/// </summary>
/// <returns>
/// <para>How many Threads were copied over </para>
/// </returns>
/// <java-name>
/// enumerate
/// </java-name>
[Dot42.DexImport("enumerate", "([Ljava/lang/Thread;)I", AccessFlags = 9)]
public static int Enumerate(global::System.Threading.Thread[] threads) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns a map of all the currently live threads to their stack traces. </para>
/// </summary>
/// <java-name>
/// getAllStackTraces
/// </java-name>
[Dot42.DexImport("getAllStackTraces", "()Ljava/util/Map;", AccessFlags = 9, Signature = "()Ljava/util/Map<Ljava/lang/Thread;[Ljava/lang/StackTraceElement;>;")]
public static global::Java.Util.IMap<global::System.Threading.Thread, global::Java.Lang.StackTraceElement[]> GetAllStackTraces() /* MethodBuilder.Create */
{
return default(global::Java.Util.IMap<global::System.Threading.Thread, global::Java.Lang.StackTraceElement[]>);
}
/// <summary>
/// <para>Returns the context ClassLoader for this Thread.</para><para><para>java.lang.ClassLoader </para><simplesectsep></simplesectsep><para>getContextClassLoader() </para></para>
/// </summary>
/// <returns>
/// <para>ClassLoader The context ClassLoader </para>
/// </returns>
/// <java-name>
/// getContextClassLoader
/// </java-name>
[Dot42.DexImport("getContextClassLoader", "()Ljava/lang/ClassLoader;", AccessFlags = 1)]
public virtual global::Java.Lang.ClassLoader GetContextClassLoader() /* MethodBuilder.Create */
{
return default(global::Java.Lang.ClassLoader);
}
/// <summary>
/// <para>Returns the default exception handler that's executed when uncaught exception terminates a thread.</para><para></para>
/// </summary>
/// <returns>
/// <para>an UncaughtExceptionHandler or <code>null</code> if none exists. </para>
/// </returns>
/// <java-name>
/// getDefaultUncaughtExceptionHandler
/// </java-name>
[Dot42.DexImport("getDefaultUncaughtExceptionHandler", "()Ljava/lang/Thread$UncaughtExceptionHandler;", AccessFlags = 9)]
public static global::System.Threading.Thread.IUncaughtExceptionHandler GetDefaultUncaughtExceptionHandler() /* MethodBuilder.Create */
{
return default(global::System.Threading.Thread.IUncaughtExceptionHandler);
}
/// <summary>
/// <para>Returns the thread's identifier. The ID is a positive <code>long</code> generated on thread creation, is unique to the thread, and doesn't change during the lifetime of the thread; the ID may be reused after the thread has been terminated.</para><para></para>
/// </summary>
/// <returns>
/// <para>the thread's ID. </para>
/// </returns>
/// <java-name>
/// getId
/// </java-name>
[Dot42.DexImport("getId", "()J", AccessFlags = 1)]
public virtual long GetId() /* MethodBuilder.Create */
{
return default(long);
}
/// <summary>
/// <para>Returns the name of the Thread. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the priority of the Thread. </para>
/// </summary>
/// <java-name>
/// getPriority
/// </java-name>
[Dot42.DexImport("getPriority", "()I", AccessFlags = 17)]
public int GetPriority() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns an array of StackTraceElement representing the current thread's stack. </para>
/// </summary>
/// <java-name>
/// getStackTrace
/// </java-name>
[Dot42.DexImport("getStackTrace", "()[Ljava/lang/StackTraceElement;", AccessFlags = 1)]
public virtual global::Java.Lang.StackTraceElement[] GetStackTrace() /* MethodBuilder.Create */
{
return default(global::Java.Lang.StackTraceElement[]);
}
/// <summary>
/// <para>Returns the current state of the Thread. This method is useful for monitoring purposes.</para><para></para>
/// </summary>
/// <returns>
/// <para>a State value. </para>
/// </returns>
/// <java-name>
/// getState
/// </java-name>
[Dot42.DexImport("getState", "()Ljava/lang/Thread$State;", AccessFlags = 1)]
public virtual global::System.Threading.Thread.State GetState() /* MethodBuilder.Create */
{
return default(global::System.Threading.Thread.State);
}
/// <summary>
/// <para>Returns the ThreadGroup to which this Thread belongs.</para><para></para>
/// </summary>
/// <returns>
/// <para>the Thread's ThreadGroup </para>
/// </returns>
/// <java-name>
/// getThreadGroup
/// </java-name>
[Dot42.DexImport("getThreadGroup", "()Ljava/lang/ThreadGroup;", AccessFlags = 17)]
public global::Java.Lang.ThreadGroup GetThreadGroup() /* MethodBuilder.Create */
{
return default(global::Java.Lang.ThreadGroup);
}
/// <summary>
/// <para>Returns the thread's uncaught exception handler. If not explicitly set, then the ThreadGroup's handler is returned. If the thread is terminated, then <code>null</code> is returned.</para><para></para>
/// </summary>
/// <returns>
/// <para>an UncaughtExceptionHandler instance or <c> null </c> . </para>
/// </returns>
/// <java-name>
/// getUncaughtExceptionHandler
/// </java-name>
[Dot42.DexImport("getUncaughtExceptionHandler", "()Ljava/lang/Thread$UncaughtExceptionHandler;", AccessFlags = 1)]
public virtual global::System.Threading.Thread.IUncaughtExceptionHandler GetUncaughtExceptionHandler() /* MethodBuilder.Create */
{
return default(global::System.Threading.Thread.IUncaughtExceptionHandler);
}
/// <summary>
/// <para>Posts an interrupt request to this <c> Thread </c> . The behavior depends on the state of this <c> Thread </c> : <ul><li><para><c> Thread </c> s blocked in one of <c> Object </c> 's <c> wait() </c> methods or one of <c> Thread </c> 's <c> join() </c> or <c> sleep() </c> methods will be woken up, their interrupt status will be cleared, and they receive an InterruptedException. </para></li><li><para><c> Thread </c> s blocked in an I/O operation of an java.nio.channels.InterruptibleChannel will have their interrupt status set and receive an java.nio.channels.ClosedByInterruptException. Also, the channel will be closed. </para></li><li><para><c> Thread </c> s blocked in a java.nio.channels.Selector will have their interrupt status set and return immediately. They don't receive an exception in this case. <ul><li></li></ul>Thread::interrupted <para>Thread::isInterrupted </para></para></li></ul></para>
/// </summary>
/// <java-name>
/// interrupt
/// </java-name>
[Dot42.DexImport("interrupt", "()V", AccessFlags = 1)]
public virtual void Interrupt() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns a <code>boolean</code> indicating whether the current Thread ( <code>currentThread()</code>) has a pending interrupt request (<code> true</code>) or not (<code>false</code>). It also has the side-effect of clearing the flag.</para><para><para>Thread::currentThread </para><simplesectsep></simplesectsep><para>Thread::interrupt </para><simplesectsep></simplesectsep><para>Thread::isInterrupted </para></para>
/// </summary>
/// <returns>
/// <para>a <code>boolean</code> indicating the interrupt status </para>
/// </returns>
/// <java-name>
/// interrupted
/// </java-name>
[Dot42.DexImport("interrupted", "()Z", AccessFlags = 9)]
public static bool Interrupted() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns <code>true</code> if the receiver has already been started and still runs code (hasn't died yet). Returns <code>false</code> either if the receiver hasn't been started yet or if it has already started and run to completion and died.</para><para><para>Thread::start </para></para>
/// </summary>
/// <returns>
/// <para>a <code>boolean</code> indicating the liveness of the Thread </para>
/// </returns>
/// <java-name>
/// isAlive
/// </java-name>
[Dot42.DexImport("isAlive", "()Z", AccessFlags = 17)]
public bool IsAlive() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Tests whether this is a daemon thread. A daemon thread only runs as long as there are non-daemon threads running. When the last non-daemon thread ends, the runtime will exit. This is not normally relevant to applications with a UI. </para>
/// </summary>
/// <java-name>
/// isDaemon
/// </java-name>
[Dot42.DexImport("isDaemon", "()Z", AccessFlags = 17)]
public bool IsDaemon() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns a <code>boolean</code> indicating whether the receiver has a pending interrupt request (<code>true</code>) or not ( <code>false</code>)</para><para><para>Thread::interrupt </para><simplesectsep></simplesectsep><para>Thread::interrupted </para></para>
/// </summary>
/// <returns>
/// <para>a <code>boolean</code> indicating the interrupt status </para>
/// </returns>
/// <java-name>
/// isInterrupted
/// </java-name>
[Dot42.DexImport("isInterrupted", "()Z", AccessFlags = 1)]
public virtual bool IsInterrupted() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Blocks the current Thread (<code>Thread.currentThread()</code>) until the receiver finishes its execution and dies.</para><para><para>Object::notifyAll </para><simplesectsep></simplesectsep><para>java.lang.ThreadDeath </para></para>
/// </summary>
/// <java-name>
/// join
/// </java-name>
[Dot42.DexImport("join", "()V", AccessFlags = 17)]
public void Join() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Blocks the current Thread (<code>Thread.currentThread()</code>) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.</para><para><para>Object::notifyAll </para><simplesectsep></simplesectsep><para>java.lang.ThreadDeath </para></para>
/// </summary>
/// <java-name>
/// join
/// </java-name>
[Dot42.DexImport("join", "(J)V", AccessFlags = 17)]
public void Join(long millis) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Blocks the current Thread (<code>Thread.currentThread()</code>) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.</para><para><para>Object::notifyAll </para><simplesectsep></simplesectsep><para>java.lang.ThreadDeath </para></para>
/// </summary>
/// <java-name>
/// join
/// </java-name>
[Dot42.DexImport("join", "(JI)V", AccessFlags = 17)]
public void Join(long millis, int nanos) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Throws <c> UnsupportedOperationException </c> . <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Only useful in conjunction with deprecated method Thread#suspend. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// resume
/// </java-name>
[Dot42.DexImport("resume", "()V", AccessFlags = 17)]
public void Resume() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Calls the <code>run()</code> method of the Runnable object the receiver holds. If no Runnable is set, does nothing.</para><para><para>Thread::start </para></para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "()V", AccessFlags = 1)]
public virtual void Run() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the context ClassLoader for the receiver.</para><para><para>getContextClassLoader() </para></para>
/// </summary>
/// <java-name>
/// setContextClassLoader
/// </java-name>
[Dot42.DexImport("setContextClassLoader", "(Ljava/lang/ClassLoader;)V", AccessFlags = 1)]
public virtual void SetContextClassLoader(global::Java.Lang.ClassLoader cl) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Marks this thread as a daemon thread. A daemon thread only runs as long as there are non-daemon threads running. When the last non-daemon thread ends, the runtime will exit. This is not normally relevant to applications with a UI. </para>
/// </summary>
/// <java-name>
/// setDaemon
/// </java-name>
[Dot42.DexImport("setDaemon", "(Z)V", AccessFlags = 17)]
public void SetDaemon(bool isDaemon) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets the default uncaught exception handler. This handler is invoked in case any Thread dies due to an unhandled exception.</para><para></para>
/// </summary>
/// <java-name>
/// setDefaultUncaughtExceptionHandler
/// </java-name>
[Dot42.DexImport("setDefaultUncaughtExceptionHandler", "(Ljava/lang/Thread$UncaughtExceptionHandler;)V", AccessFlags = 9)]
public static void SetDefaultUncaughtExceptionHandler(global::System.Threading.Thread.IUncaughtExceptionHandler handler) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets the name of the Thread.</para><para><para>Thread::getName </para></para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 17)]
public void SetName(string threadName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets the priority of this thread. If the requested priority is greater than the parent thread group's java.lang.ThreadGroup#getMaxPriority, the group's maximum priority will be used instead.</para><para></para>
/// </summary>
/// <java-name>
/// setPriority
/// </java-name>
[Dot42.DexImport("setPriority", "(I)V", AccessFlags = 17)]
public void SetPriority(int priority) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets the uncaught exception handler. This handler is invoked in case this Thread dies due to an unhandled exception. </para><para></para>
/// </summary>
/// <java-name>
/// setUncaughtExceptionHandler
/// </java-name>
[Dot42.DexImport("setUncaughtExceptionHandler", "(Ljava/lang/Thread$UncaughtExceptionHandler;)V", AccessFlags = 1)]
public virtual void SetUncaughtExceptionHandler(global::System.Threading.Thread.IUncaughtExceptionHandler handler) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.</para><para><para>Thread::interrupt() </para></para>
/// </summary>
/// <java-name>
/// sleep
/// </java-name>
[Dot42.DexImport("sleep", "(J)V", AccessFlags = 9)]
public static void Sleep(long time) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds and nanoseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.</para><para><para>Thread::interrupt() </para></para>
/// </summary>
/// <java-name>
/// sleep
/// </java-name>
[Dot42.DexImport("sleep", "(JI)V", AccessFlags = 9)]
public static void Sleep(long millis, int nanos) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Starts the new Thread of execution. The <code>run()</code> method of the receiver will be called by the receiver Thread itself (and not the Thread calling <code>start()</code>).</para><para><para>Thread::run </para></para>
/// </summary>
/// <java-name>
/// start
/// </java-name>
[Dot42.DexImport("start", "()V", AccessFlags = 33)]
public virtual void Start() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Requests the receiver Thread to stop and throw ThreadDeath. The Thread is resumed if it was suspended and awakened if it was sleeping, so that it can proceed to throw ThreadDeath.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// stop
/// </java-name>
[Dot42.DexImport("stop", "()V", AccessFlags = 17)]
public void Stop() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Throws <c> UnsupportedOperationException </c> . <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// stop
/// </java-name>
[Dot42.DexImport("stop", "(Ljava/lang/Throwable;)V", AccessFlags = 49)]
public void Stop(global::System.Exception throwable) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Throws <c> UnsupportedOperationException </c> . <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>May cause deadlocks. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// suspend
/// </java-name>
[Dot42.DexImport("suspend", "()V", AccessFlags = 17)]
public void Suspend() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns a string containing a concise, human-readable description of the Thread. It includes the Thread's name, priority, and group name.</para><para></para>
/// </summary>
/// <returns>
/// <para>a printable representation for the receiver. </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Causes the calling Thread to yield execution time to another Thread that is ready to run. The actual scheduling is implementation-dependent. </para>
/// </summary>
/// <java-name>
/// yield
/// </java-name>
[Dot42.DexImport("yield", "()V", AccessFlags = 9)]
public static void Yield() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates whether the current Thread has a monitor lock on the specified object.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if the current thread has a monitor lock on the specified object; false otherwise </para>
/// </returns>
/// <java-name>
/// holdsLock
/// </java-name>
[Dot42.DexImport("holdsLock", "(Ljava/lang/Object;)Z", AccessFlags = 9)]
public static bool HoldsLock(object @object) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns the Thread of the caller, that is, the current Thread.</para><para></para>
/// </summary>
/// <returns>
/// <para>the current Thread. </para>
/// </returns>
/// <java-name>
/// currentThread
/// </java-name>
public static global::System.Threading.Thread CurrentThread
{
[Dot42.DexImport("currentThread", "()Ljava/lang/Thread;", AccessFlags = 9)]
get{ return GetCurrentThread(); }
}
/// <summary>
/// <para>Returns a map of all the currently live threads to their stack traces. </para>
/// </summary>
/// <java-name>
/// getAllStackTraces
/// </java-name>
public static global::Java.Util.IMap<global::System.Threading.Thread, global::Java.Lang.StackTraceElement[]> AllStackTraces
{
[Dot42.DexImport("getAllStackTraces", "()Ljava/util/Map;", AccessFlags = 9, Signature = "()Ljava/util/Map<Ljava/lang/Thread;[Ljava/lang/StackTraceElement;>;")]
get{ return GetAllStackTraces(); }
}
/// <summary>
/// <para>Returns the context ClassLoader for this Thread.</para><para><para>java.lang.ClassLoader </para><simplesectsep></simplesectsep><para>getContextClassLoader() </para></para>
/// </summary>
/// <returns>
/// <para>ClassLoader The context ClassLoader </para>
/// </returns>
/// <java-name>
/// getContextClassLoader
/// </java-name>
public global::Java.Lang.ClassLoader ContextClassLoader
{
[Dot42.DexImport("getContextClassLoader", "()Ljava/lang/ClassLoader;", AccessFlags = 1)]
get{ return GetContextClassLoader(); }
[Dot42.DexImport("setContextClassLoader", "(Ljava/lang/ClassLoader;)V", AccessFlags = 1)]
set{ SetContextClassLoader(value); }
}
/// <summary>
/// <para>Returns the default exception handler that's executed when uncaught exception terminates a thread.</para><para></para>
/// </summary>
/// <returns>
/// <para>an UncaughtExceptionHandler or <code>null</code> if none exists. </para>
/// </returns>
/// <java-name>
/// getDefaultUncaughtExceptionHandler
/// </java-name>
public static global::System.Threading.Thread.IUncaughtExceptionHandler DefaultUncaughtExceptionHandler
{
[Dot42.DexImport("getDefaultUncaughtExceptionHandler", "()Ljava/lang/Thread$UncaughtExceptionHandler;", AccessFlags = 9)]
get{ return GetDefaultUncaughtExceptionHandler(); }
[Dot42.DexImport("setDefaultUncaughtExceptionHandler", "(Ljava/lang/Thread$UncaughtExceptionHandler;)V", AccessFlags = 9)]
set{ SetDefaultUncaughtExceptionHandler(value); }
}
/// <summary>
/// <para>Returns the thread's identifier. The ID is a positive <code>long</code> generated on thread creation, is unique to the thread, and doesn't change during the lifetime of the thread; the ID may be reused after the thread has been terminated.</para><para></para>
/// </summary>
/// <returns>
/// <para>the thread's ID. </para>
/// </returns>
/// <java-name>
/// getId
/// </java-name>
public long Id
{
[Dot42.DexImport("getId", "()J", AccessFlags = 1)]
get{ return GetId(); }
}
/// <summary>
/// <para>Returns the name of the Thread. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 17)]
set{ SetName(value); }
}
/// <summary>
/// <para>Returns the priority of the Thread. </para>
/// </summary>
/// <java-name>
/// getPriority
/// </java-name>
public int Priority
{
[Dot42.DexImport("getPriority", "()I", AccessFlags = 17)]
get{ return GetPriority(); }
[Dot42.DexImport("setPriority", "(I)V", AccessFlags = 17)]
set{ SetPriority(value); }
}
/// <summary>
/// <para>Returns an array of StackTraceElement representing the current thread's stack. </para>
/// </summary>
/// <java-name>
/// getStackTrace
/// </java-name>
public global::Java.Lang.StackTraceElement[] StackTrace
{
[Dot42.DexImport("getStackTrace", "()[Ljava/lang/StackTraceElement;", AccessFlags = 1)]
get{ return GetStackTrace(); }
}
/// <summary>
/// <para>Returns the ThreadGroup to which this Thread belongs.</para><para></para>
/// </summary>
/// <returns>
/// <para>the Thread's ThreadGroup </para>
/// </returns>
/// <java-name>
/// getThreadGroup
/// </java-name>
public global::Java.Lang.ThreadGroup ThreadGroup
{
[Dot42.DexImport("getThreadGroup", "()Ljava/lang/ThreadGroup;", AccessFlags = 17)]
get{ return GetThreadGroup(); }
}
/// <summary>
/// <para>Returns the thread's uncaught exception handler. If not explicitly set, then the ThreadGroup's handler is returned. If the thread is terminated, then <code>null</code> is returned.</para><para></para>
/// </summary>
/// <returns>
/// <para>an UncaughtExceptionHandler instance or <c> null </c> . </para>
/// </returns>
/// <java-name>
/// getUncaughtExceptionHandler
/// </java-name>
public global::System.Threading.Thread.IUncaughtExceptionHandler UncaughtExceptionHandler
{
[Dot42.DexImport("getUncaughtExceptionHandler", "()Ljava/lang/Thread$UncaughtExceptionHandler;", AccessFlags = 1)]
get{ return GetUncaughtExceptionHandler(); }
[Dot42.DexImport("setUncaughtExceptionHandler", "(Ljava/lang/Thread$UncaughtExceptionHandler;)V", AccessFlags = 1)]
set{ SetUncaughtExceptionHandler(value); }
}
/// <summary>
/// <para>Implemented by objects that want to handle cases where a thread is being terminated by an uncaught exception. Upon such termination, the handler is notified of the terminating thread and causal exception. If there is no explicit handler set then the thread's group is the default handler. </para>
/// </summary>
/// <java-name>
/// java/lang/Thread$UncaughtExceptionHandler
/// </java-name>
[Dot42.DexImport("java/lang/Thread$UncaughtExceptionHandler", AccessFlags = 1545)]
public partial interface IUncaughtExceptionHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>The thread is being terminated by an uncaught exception. Further exceptions thrown in this method are prevent the remainder of the method from executing, but are otherwise ignored.</para><para></para>
/// </summary>
/// <java-name>
/// uncaughtException
/// </java-name>
[Dot42.DexImport("uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V", AccessFlags = 1025)]
void UncaughtException(global::System.Threading.Thread thread, global::System.Exception ex) /* MethodBuilder.Create */ ;
}
/// <java-name>
/// java/lang/Thread$State
/// </java-name>
[Dot42.DexImport("java/lang/Thread$State", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Ljava/lang/Thread$State;>;")]
public sealed class State
/* scope: __dot42__ */
{
/// <java-name>
/// BLOCKED
/// </java-name>
[Dot42.DexImport("BLOCKED", "Ljava/lang/Thread$State;", AccessFlags = 16409)]
public static readonly State BLOCKED;
/// <java-name>
/// NEW
/// </java-name>
[Dot42.DexImport("NEW", "Ljava/lang/Thread$State;", AccessFlags = 16409)]
public static readonly State NEW;
/// <java-name>
/// RUNNABLE
/// </java-name>
[Dot42.DexImport("RUNNABLE", "Ljava/lang/Thread$State;", AccessFlags = 16409)]
public static readonly State RUNNABLE;
/// <java-name>
/// TERMINATED
/// </java-name>
[Dot42.DexImport("TERMINATED", "Ljava/lang/Thread$State;", AccessFlags = 16409)]
public static readonly State TERMINATED;
/// <java-name>
/// TIMED_WAITING
/// </java-name>
[Dot42.DexImport("TIMED_WAITING", "Ljava/lang/Thread$State;", AccessFlags = 16409)]
public static readonly State TIMED_WAITING;
/// <java-name>
/// WAITING
/// </java-name>
[Dot42.DexImport("WAITING", "Ljava/lang/Thread$State;", AccessFlags = 16409)]
public static readonly State WAITING;
private State() /* TypeBuilder.AddPrivateDefaultCtor */
{
}
}
}
}
| |
//
// UnityOSC - Open Sound Control interface for the Unity3d game engine
//
// Copyright (c) 2012 Jorge Garcia Martin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace UnityOSC
{
public sealed class OSCMessage : OSCPacket
{
#region Constructors
public OSCMessage (string address)
{
_typeTag = DEFAULT.ToString();
this.Address = address;
}
public OSCMessage (string address, object msgvalue)
{
_typeTag = DEFAULT.ToString();
this.Address = address;
Append(msgvalue);
}
#endregion
#region Member Variables
private const char INTEGER = 'i';
private const char FLOAT = 'f';
private const char LONG = 'h';
private const char DOUBLE = 'd';
private const char STRING = 's';
private const char BYTE = 'b';
private const char DEFAULT = ',';
private string _typeTag;
#endregion
#region Properties
#endregion
#region Methods
/// <summary>
/// Specifies if the message is an OSC bundle.
/// </summary>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
override public bool IsBundle() { return false; }
/// <summary>
/// Packs the OSC message to binary data.
/// </summary>
override public void Pack()
{
List<byte> data = new List<byte>();
data.AddRange(OSCPacket.PackValue(_address));
OSCPacket.PadNull(data);
data.AddRange(OSCPacket.PackValue(_typeTag));
OSCPacket.PadNull(data);
foreach (object value in _data)
{
data.AddRange(OSCPacket.PackValue(value));
if (value is string || value is byte[])
{
OSCPacket.PadNull(data);
}
}
this._binaryData = data.ToArray();
}
/// <summary>
/// Unpacks an OSC message.
/// </summary>
/// <param name="data">
/// A <see cref="System.Byte[]"/>
/// </param>
/// <param name="start">
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="OSCMessage"/>
/// </returns>
public new static OSCMessage Unpack(byte[] data, ref int start)
{
string address = OSCPacket.UnpackValue<string>(data, ref start);
OSCMessage message = new OSCMessage(address);
char[] tags = OSCPacket.UnpackValue<string>(data, ref start).ToCharArray();
foreach (char tag in tags)
{
object value;
switch (tag)
{
case DEFAULT:
continue;
case INTEGER:
value = OSCPacket.UnpackValue<int>(data, ref start);
break;
case LONG:
value = OSCPacket.UnpackValue<long>(data, ref start);
break;
case FLOAT:
value = OSCPacket.UnpackValue<float>(data, ref start);
break;
case DOUBLE:
value = OSCPacket.UnpackValue<double>(data, ref start);
break;
case STRING:
value = OSCPacket.UnpackValue<string>(data, ref start);
break;
case BYTE:
value = OSCPacket.UnpackValue<byte[]>(data, ref start);
break;
default:
Console.WriteLine("Unknown tag: " + tag);
continue;
}
message.Append(value);
}
if(message.TimeStamp == 0)
{
message.TimeStamp = DateTime.Now.Ticks;
}
return message;
}
/// <summary>
/// Appends a value to an OSC message.
/// </summary>
/// <param name="value">
/// A <see cref="T"/>
/// </param>
public override void Append<T> (T value)
{
Type type = value.GetType();
char typeTag = DEFAULT;
switch (type.Name)
{
case "Int32":
typeTag = INTEGER;
break;
case "Int64":
typeTag = LONG;
break;
case "Single":
typeTag = FLOAT;
break;
case "Double":
typeTag = DOUBLE;
break;
case "String":
typeTag = STRING;
break;
case "Byte[]":
typeTag = BYTE;
break;
default:
throw new Exception("Unsupported data type.");
}
_typeTag += typeTag;
_data.Add(value);
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Mshtml;
using OpenLiveWriter.ApplicationFramework;
namespace OpenLiveWriter.HtmlEditor
{
public delegate IHtmlEditorComponentContext IHtmlEditorComponentContextDelegate();
public interface IHtmlEditorComponentContext : IUndoUnitFactory
{
/// <summary>
/// interface to the main frame window that hosts this component
/// </summary>
IMainFrameWindow MainFrameWindow
{
get;
}
IMshtmlDocumentEvents DocumentEvents { get; }
/// <summary>
/// Markup services for low level document examination/manipulation
/// </summary>
MshtmlMarkupServices MarkupServices { get; }
/// <summary>
/// Damage services for low level document damage notification
/// </summary>
IHTMLEditorDamageServices DamageServices { get; }
event EventHandler SelectionChanged;
bool IsEditFieldSelected { get; }
IHTMLElement SelectedEditField { get; }
/// <summary>
/// Allow components to perform fixups to edited html
/// prior to publishing or saving. These edits are
/// automatically reverted after publishing or saving
/// so that the editing experience is not affected
/// </summary>
event TemporaryFixupHandler PerformTemporaryFixupsToEditedHtml;
void EmptySelection();
void BeginSelectionChange();
IHtmlEditorSelection Selection { get; set; }
void EndSelectionChange();
event EventHandler BeforeInitialInsertion;
event EventHandler AfterInitialInsertion;
void FireSelectionChanged();
DragDropEffects DoDragDrop(IDataObject dataObject, DragDropEffects effects);
Point PointToScreen(Point clientPoint);
Point PointToClient(Point screenPoint);
IHTMLElement ElementFromClientPoint(Point clientPoint);
bool PointIsOverDocumentArea(Point clientPoint);
/// <summary>
/// Enable overriding of the default cursor
/// </summary>
bool OverrideCursor { set; }
/// <summary>
/// Execute an MSHTML command
/// </summary>
/// <param name="cmdID">command-d</param>
void ExecuteCommand(uint cmdID);
/// <summary>
/// Execute an MSHTML command
/// </summary>
/// <param name="cmdID">command id</param>
/// <param name="input">input parameter</param>
void ExecuteCommand(uint cmdID, object input);
/// <summary>
/// Execute an MSHTML command
/// </summary>
/// <param name="cmdID">command id</param>
/// <param name="input">input parameter</param>
/// <param name="output">out parameter</param>
void ExecuteCommand(uint cmdID, object input, ref object output);
/// <summary>
/// Clear the current selection
/// </summary>
void Clear();
/// <summary>
/// Provide the ability to filter editor events
/// </summary>
event HtmlEditDesignerEventHandler PreHandleEvent;
event MshtmlEditor.EditDesignerEventHandler PostEventNotify;
/// <summary>
/// Provide the ability to override accelerator processing
/// </summary>
event HtmlEditDesignerEventHandler TranslateAccelerator;
event EventHandler HtmlInserted;
/// <summary>
/// Provide the ability to override command key processing.
/// </summary>
event KeyEventHandler CommandKey;
/// <summary>
/// Provide the ability to process key down processing.
/// </summary>
event HtmlEventHandler KeyDown;
/// <summary>
/// Provide the ability to process key down processing.
/// </summary>
event HtmlEventHandler KeyUp;
/// <summary>
/// Provide the ability to process clipboard Copy
/// </summary>
event HtmlEditorSelectionOperationEventHandler HandleCopy;
/// <summary>
/// Provide the ability to process clipboard Cut
/// </summary>
///
event HtmlEditorSelectionOperationEventHandler HandleCut;
/// <summary>
/// Provide the ability to process clipboard Clear
/// </summary>
event HtmlEditorSelectionOperationEventHandler HandleClear;
/// <summary>
/// A unique identifier for this editor instance.
/// </summary>
string EditorId { get; }
/// <summary>
/// Returns true if the editor is in edit mode.
/// </summary>
bool EditMode { get; }
/// <summary>
/// Insert html into the editor
/// </summary>
/// <param name="html"></param>
void InsertHtml(string html, bool moveSelectionRight);
/// <summary>
/// Insert content into the editor
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="html"></param>
void InsertHtml(MarkupPointer start, MarkupPointer end, string html);
/// <summary>
/// Create an undo unit for the control
/// </summary>
/// <returns></returns>
IUndoUnit CreateInvisibleUndoUnit();
/// <summary>
/// Cookie bag which can be used for components to communicate
/// with eachother on a per editor-instance basis
/// </summary>
IDictionary Cookies { get; }
/// <summary>
/// Displays the editor context meny at the specific location.
/// </summary>
/// <param name="screenPoint"></param>
/// <returns></returns>
bool ShowContextMenu(Point screenPoint);
bool IsRTLTemplate { get; }
void ForceDirty();
CommandManager CommandManager { get; }
}
public delegate void TemporaryFixupHandler(TemporaryFixupArgs args);
public class TemporaryFixupArgs
{
public TemporaryFixupArgs(string html)
{
_html = html;
}
private string _html;
public string Html
{
get
{
return _html;
}
set
{
_html = value;
}
}
}
public interface IUndoUnitFactory
{
/// <summary>
/// Create an undo unit for the control
/// </summary>
/// <returns></returns>
IUndoUnit CreateUndoUnit();
}
public interface IUndoUnit : IDisposable
{
void Commit();
}
public class HtmlEditorSelectionOperationEventArgs : EventArgs
{
public HtmlEditorSelectionOperationEventArgs(IHtmlEditorSelection selection)
{
_selection = selection;
}
public IHtmlEditorSelection Selection
{
get { return _selection; }
}
private IHtmlEditorSelection _selection;
public bool Handled
{
get { return _handled; }
set { _handled = value; }
}
private bool _handled = false;
}
public delegate void HtmlEditorSelectionOperationEventHandler(HtmlEditorSelectionOperationEventArgs ea);
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenMetaverse
{
/// <summary>
/// A Name Value pair with additional settings, used in the protocol
/// primarily to transmit avatar names and active group in object packets
/// </summary>
public struct NameValue
{
#region Enums
/// <summary>Type of the value</summary>
public enum ValueType
{
/// <summary>Unknown</summary>
Unknown = -1,
/// <summary>String value</summary>
String,
/// <summary></summary>
F32,
/// <summary></summary>
S32,
/// <summary></summary>
VEC3,
/// <summary></summary>
U32,
/// <summary>Deprecated</summary>
[Obsolete]
CAMERA,
/// <summary>String value, but designated as an asset</summary>
Asset,
/// <summary></summary>
U64
}
/// <summary>
///
/// </summary>
public enum ClassType
{
/// <summary></summary>
Unknown = -1,
/// <summary></summary>
ReadOnly,
/// <summary></summary>
ReadWrite,
/// <summary></summary>
Callback
}
/// <summary>
///
/// </summary>
public enum SendtoType
{
/// <summary></summary>
Unknown = -1,
/// <summary></summary>
Sim,
/// <summary></summary>
DataSim,
/// <summary></summary>
SimViewer,
/// <summary></summary>
DataSimViewer
}
#endregion Enums
/// <summary></summary>
public string Name;
/// <summary></summary>
public ValueType Type;
/// <summary></summary>
public ClassType Class;
/// <summary></summary>
public SendtoType Sendto;
/// <summary></summary>
public object Value;
private static readonly string[] TypeStrings = new string[]
{
"STRING",
"F32",
"S32",
"VEC3",
"U32",
"ASSET",
"U64"
};
private static readonly string[] ClassStrings = new string[]
{
"R", // Read-only
"RW", // Read-write
"CB" // Callback
};
private static readonly string[] SendtoStrings = new string[]
{
"S", // Sim
"DS", // Data Sim
"SV", // Sim Viewer
"DSV" // Data Sim Viewer
};
private static readonly char[] Separators = new char[]
{
' ',
'\n',
'\t',
'\r'
};
/// <summary>
/// Constructor that takes all the fields as parameters
/// </summary>
/// <param name="name"></param>
/// <param name="valueType"></param>
/// <param name="classType"></param>
/// <param name="sendtoType"></param>
/// <param name="value"></param>
public NameValue(string name, ValueType valueType, ClassType classType, SendtoType sendtoType, object value)
{
Name = name;
Type = valueType;
Class = classType;
Sendto = sendtoType;
Value = value;
}
/// <summary>
/// Constructor that takes a single line from a NameValue field
/// </summary>
/// <param name="data"></param>
public NameValue(string data)
{
int i;
// Name
i = data.IndexOfAny(Separators);
if (i < 1)
{
Name = String.Empty;
Type = ValueType.Unknown;
Class = ClassType.Unknown;
Sendto = SendtoType.Unknown;
Value = null;
return;
}
Name = data.Substring(0, i);
data = data.Substring(i + 1);
// Type
i = data.IndexOfAny(Separators);
if (i > 0)
{
Type = GetValueType(data.Substring(0, i));
data = data.Substring(i + 1);
// Class
i = data.IndexOfAny(Separators);
if (i > 0)
{
Class = GetClassType(data.Substring(0, i));
data = data.Substring(i + 1);
// Sendto
i = data.IndexOfAny(Separators);
if (i > 0)
{
Sendto = GetSendtoType(data.Substring(0, 1));
data = data.Substring(i + 1);
}
}
}
// Value
Type = ValueType.String;
Class = ClassType.ReadOnly;
Sendto = SendtoType.Sim;
Value = null;
SetValue(data);
}
public static string NameValuesToString(NameValue[] values)
{
if (values == null)
return String.Empty;
if (values.Length == 0) return "\n";
StringBuilder output = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
NameValue value = values[i];
if (value.Value != null)
{
string newLine = (i < values.Length - 1) ? "\n" : String.Empty;
output.AppendFormat("{0} {1} {2} {3} {4}{5}", value.Name, TypeStrings[(int)value.Type],
ClassStrings[(int)value.Class], SendtoStrings[(int)value.Sendto], value.Value.ToString(), newLine);
}
}
return output.ToString();
}
public static NameValue[] ParseNameValues(string text)
{
// Parse the name values
if (text.Length > 0)
{
if (text == "\n") return new NameValue[0];
string[] lines = text.Split('\n');
var NameValues = new NameValue[lines.Length];
for (int j = 0; j < lines.Length; j++)
{
if (!String.IsNullOrEmpty(lines[j]))
{
NameValue nv = new NameValue(lines[j]);
NameValues[j] = nv;
}
}
return NameValues;
}
return null;
}
private void SetValue(string value)
{
switch (Type)
{
case ValueType.Asset:
case ValueType.String:
Value = value;
break;
case ValueType.F32:
{
float temp;
Utils.TryParseSingle(value, out temp);
Value = temp;
break;
}
case ValueType.S32:
{
int temp;
Int32.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.U32:
{
uint temp;
UInt32.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.U64:
{
ulong temp;
UInt64.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.VEC3:
{
Vector3 temp;
Vector3.TryParse(value, out temp);
Value = temp;
break;
}
default:
Value = null;
break;
}
}
private static ValueType GetValueType(string value)
{
ValueType type = ValueType.Unknown;
for (int i = 0; i < TypeStrings.Length; i++)
{
if (value == TypeStrings[i])
{
type = (ValueType)i;
break;
}
}
if (type == ValueType.Unknown)
type = ValueType.String;
return type;
}
private static ClassType GetClassType(string value)
{
ClassType type = ClassType.Unknown;
for (int i = 0; i < ClassStrings.Length; i++)
{
if (value == ClassStrings[i])
{
type = (ClassType)i;
break;
}
}
if (type == ClassType.Unknown)
type = ClassType.ReadOnly;
return type;
}
private static SendtoType GetSendtoType(string value)
{
SendtoType type = SendtoType.Unknown;
for (int i = 0; i < SendtoStrings.Length; i++)
{
if (value == SendtoStrings[i])
{
type = (SendtoType)i;
break;
}
}
if (type == SendtoType.Unknown)
type = SendtoType.Sim;
return type;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Share.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
// Portions of this task are based on the http://www.codeplex.com/sdctasks. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.FileSystem
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>CheckExists</i> (<b>Required: </b> ShareName <b>Output:</b> Exists)</para>
/// <para><i>Create</i> (<b>Required: </b> ShareName, SharePath <b>Optional: </b>Description, MaximumAllowed, CreateSharePath, AllowUsers, DenyUsers)</para>
/// <para><i>Delete</i> (<b>Required: </b> ShareName)</para>
/// <para><i>ModifyPermissions</i> (<b>Required: </b> ShareName <b>Optional: </b>AllowUsers, DenyUsers).</para>
/// <para><i>SetPermissions</i> (<b>Required: </b> ShareName <b>Optional: </b>AllowUsers, DenyUsers). SetPermissions will reset all existing permissions.</para>
/// <para><b>Remote Execution Support:</b> Yes</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <ItemGroup>
/// <Allow Include="ADomain\ADomainUser"/>
/// <Allow Include="AMachine\ALocalReadUser">
/// <Permission>Read</Permission>
/// </Allow>
/// <Allow Include="AMachine\ALocalChangeUser">
/// <Permission>Change</Permission>
/// </Allow>
/// </ItemGroup>
/// <!-- Delete shares -->
/// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Delete" ShareName="MSBEPS1"/>
/// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Delete" ShareName="MSBEPS2"/>
/// <!-- Create a share and specify users. The share path will be created if it doesnt exist. -->
/// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Create" AllowUsers="@(Allow)" CreateSharePath="true" SharePath="C:\fff1" ShareName="MSBEPS1" Description="A Description of MSBEPS1"/>
/// <!-- Create a share. Defaults to full permission for Everyone. -->
/// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Create" SharePath="C:\fffd" ShareName="MSBEPS2" Description="A Description of MSBEPS2"/>
/// <!-- Create a share on a remote server -->
/// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Create" AllowUsers="@(Allow)" CreateSharePath="true" MachineName="MyFileShareServer" ShareName="Temp" SharePath="D:\Temp" Description="Folder for shared files used." />
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class Share : BaseTask
{
private const string ModifyPermissionsTaskAction = "ModifyPermissions";
private const string CheckExistsTaskAction = "CheckExists";
private const string DeleteTaskAction = "Delete";
private const string CreateTaskAction = "Create";
private const string SetPermissionsTaskAction = "SetPermissions";
private int newPermissionCount;
#region enums
private enum ReturnCode : uint
{
/// <summary>
/// Success
/// </summary>
Success = 0,
/// <summary>
/// AccessDenied
/// </summary>
AccessDenied = 2,
/// <summary>
/// UnknownFailure
/// </summary>
UnknownFailure = 8,
/// <summary>
/// InvalidName
/// </summary>
InvalidName = 9,
/// <summary>
/// InvalidLevel
/// </summary>
InvalidLevel = 10,
/// <summary>
/// InvalidParameter
/// </summary>
InvalidParameter = 21,
/// <summary>
/// ShareAlreadyExists
/// </summary>
ShareAlreadyExists = 22,
/// <summary>
/// RedirectedPath
/// </summary>
RedirectedPath = 23,
/// <summary>
/// UnknownDeviceOrDirectory
/// </summary>
UnknownDeviceOrDirectory = 24,
/// <summary>
/// NetNameNotFound
/// </summary>
NetNameNotFound = 25
}
#endregion
/// <summary>
/// Sets the desctiption for the share
/// </summary>
public string Description { get; set; }
/// <summary>
/// Sets the share name
/// </summary>
[Required]
public string ShareName { get; set; }
/// <summary>
/// Sets the share path
/// </summary>
public string SharePath { get; set; }
/// <summary>
/// Sets the maximum number of allowed users for the share
/// </summary>
public int MaximumAllowed { get; set; }
/// <summary>
/// Sets whether to create the SharePath if it doesnt exist. Default is false
/// </summary>
public bool CreateSharePath { get; set; }
/// <summary>
/// Gets whether the share exists
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Sets a collection of users allowed to access the share. Use the Permission metadata tag to specify permissions. Default is Full.
/// <para/>
/// <code lang="xml"><![CDATA[
/// <Allow Include="AUser">
/// <Permission>Full, Read or Change etc</Permission>
/// </Allow>
/// ]]></code>
/// </summary>
public ITaskItem[] AllowUsers { get; set; }
/// <summary>
/// Sets a collection of users not allowed to access the share
/// </summary>
public ITaskItem[] DenyUsers { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case CreateTaskAction:
this.Create();
break;
case DeleteTaskAction:
this.Delete();
break;
case CheckExistsTaskAction:
this.CheckExists();
break;
case SetPermissionsTaskAction:
this.SetPermissions();
break;
case ModifyPermissionsTaskAction:
this.ModifyPermissions();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private static ManagementObject GetSecurityIdentifier(ManagementBaseObject account)
{
// get the sid
string sidString = (string)account.Properties["SID"].Value;
string sidPathString = string.Format(CultureInfo.InvariantCulture, "Win32_SID.SID='{0}'", sidString);
ManagementPath sidPath = new ManagementPath(sidPathString);
ManagementObject returnSid;
using (ManagementObject sid = new ManagementObject(sidPath))
{
try
{
sid.Get();
returnSid = sid;
}
catch (ManagementException ex)
{
throw new Exception(string.Format(CultureInfo.InvariantCulture, @"Could not find SID '{0}' for account '{1}\{2}'.", sidString, account.Properties["Domain"].Value, account.Properties["Name"].Value), ex);
}
}
return returnSid;
}
private void CheckExists()
{
this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Checking whether share: {0} exists on: {1}", this.ShareName, this.MachineName));
this.GetManagementScope(@"\root\cimv2");
ManagementPath fullSharePath = new ManagementPath("Win32_Share.Name='" + this.ShareName + "'");
using (ManagementObject shareObject = new ManagementObject(this.Scope, fullSharePath, null))
{
// try bind to the share to see if it exists
try
{
shareObject.Get();
this.Exists = true;
}
catch
{
this.Exists = false;
}
}
}
private void Delete()
{
this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Deleting share: {0} on: {1}", this.ShareName, this.MachineName));
this.GetManagementScope(@"\root\cimv2");
ManagementPath fullSharePath = new ManagementPath("Win32_Share.Name='" + this.ShareName + "'");
using (ManagementObject shareObject = new ManagementObject(this.Scope, fullSharePath, null))
{
// try bind to the share to see if it exists
try
{
shareObject.Get();
}
catch
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.InvariantCulture, "Did not find share: {0} on: {1}", this.ShareName, this.MachineName));
return;
}
// execute the method and check the return code
ManagementBaseObject outputParams = shareObject.InvokeMethod("Delete", null, null);
ReturnCode returnCode = (ReturnCode)Convert.ToUInt32(outputParams.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture);
if (returnCode != ReturnCode.Success)
{
this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Failed to delete the share. ReturnCode: {0}.", returnCode));
}
}
}
private void SetPermissions()
{
this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Set Permissions for share: {0} on: {1}", this.ShareName, this.MachineName));
this.GetManagementScope(@"\root\cimv2");
ManagementPath fullSharePath = new ManagementPath("Win32_Share.Name='" + this.ShareName + "'");
using (ManagementObject shareObject = new ManagementObject(this.Scope, fullSharePath, null))
{
// try bind to the share to see if it exists
try
{
shareObject.Get();
}
catch
{
this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Did not find share: {0} on: {1}", this.ShareName, this.MachineName));
return;
}
// Set the input parameters
ManagementBaseObject inParams = shareObject.GetMethodParameters("SetShareInfo");
inParams["Access"] = this.SetAccessPermissions();
// execute the method and check the return code
ManagementBaseObject outputParams = shareObject.InvokeMethod("SetShareInfo", inParams, null);
ReturnCode returnCode = (ReturnCode)Convert.ToUInt32(outputParams.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture);
if (returnCode != ReturnCode.Success)
{
this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Failed to set the share permissions. ReturnCode: {0}.", returnCode));
}
}
}
private void ModifyPermissions()
{
this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Modify permissions on share: {0} on: {1}", this.ShareName, this.MachineName));
this.GetManagementScope(@"\root\cimv2");
ManagementObject shareObject;
ObjectQuery query = new ObjectQuery("Select * from Win32_LogicalShareSecuritySetting where Name = '" + this.ShareName + "'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query))
{
ManagementObjectCollection moc = searcher.Get();
if (moc.Count > 0)
{
shareObject = moc.Cast<ManagementObject>().FirstOrDefault();
}
else
{
this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Did not find share: {0} on: {1}", this.ShareName, this.MachineName));
return;
}
}
ManagementBaseObject securityDescriptorObject = shareObject.InvokeMethod("GetSecurityDescriptor", null, null);
if (securityDescriptorObject == null)
{
this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Error extracting security descriptor from: {0}.", this.ShareName));
return;
}
ManagementBaseObject[] newaccessControlList = this.BuildAccessControlList();
ManagementBaseObject securityDescriptor = securityDescriptorObject.Properties["Descriptor"].Value as ManagementBaseObject;
int existingAcessControlEntriesCount = 0;
ManagementBaseObject[] accessControlList = securityDescriptor.Properties["DACL"].Value as ManagementBaseObject[];
if (accessControlList == null)
{
accessControlList = new ManagementBaseObject[this.newPermissionCount];
}
else
{
existingAcessControlEntriesCount = accessControlList.Length;
Array.Resize(ref accessControlList, accessControlList.Length + this.newPermissionCount);
}
for (int i = 0; i < newaccessControlList.Length; i++)
{
accessControlList[existingAcessControlEntriesCount + i] = newaccessControlList[i];
}
securityDescriptor.Properties["DACL"].Value = accessControlList;
ManagementBaseObject parameterForSetSecurityDescriptor = shareObject.GetMethodParameters("SetSecurityDescriptor");
parameterForSetSecurityDescriptor["Descriptor"] = securityDescriptor;
shareObject.InvokeMethod("SetSecurityDescriptor", parameterForSetSecurityDescriptor, null);
}
private void Create()
{
this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Creating share: {0} on: {1}", this.ShareName, this.MachineName));
this.GetManagementScope(@"\root\cimv2");
ManagementPath path = new ManagementPath("Win32_Share");
if (!this.TargetingLocalMachine(true))
{
// we need to operate remotely
string fullQuery = @"Select * From Win32_Directory Where Name = '" + this.SharePath.Replace("\\", "\\\\") + "'";
ObjectQuery query1 = new ObjectQuery(fullQuery);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query1))
{
ManagementObjectCollection queryCollection = searcher.Get();
if (queryCollection.Count == 0)
{
if (this.CreateSharePath)
{
this.LogTaskMessage(MessageImportance.Low, "Attempting to create remote folder for share");
ManagementPath path2 = new ManagementPath("Win32_Process");
ManagementClass managementClass2 = new ManagementClass(this.Scope, path2, null);
ManagementBaseObject inParams1 = managementClass2.GetMethodParameters("Create");
string tex = "cmd.exe /c md \"" + this.SharePath + "\"";
inParams1["CommandLine"] = tex;
ManagementBaseObject outParams1 = managementClass2.InvokeMethod("Create", inParams1, null);
uint rc = Convert.ToUInt32(outParams1.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture);
if (rc != 0)
{
this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Non-zero return code attempting to create remote share location: {0}", rc));
return;
}
// adding a sleep as it may take a while to register.
System.Threading.Thread.Sleep(1000);
}
else
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SharePath not found: {0}. Set CreateSharePath to true to create a SharePath that does not exist.", this.SharePath));
return;
}
}
}
}
else
{
if (!Directory.Exists(this.SharePath))
{
if (this.CreateSharePath)
{
Directory.CreateDirectory(this.SharePath);
// adding a sleep as it may take a while to register.
System.Threading.Thread.Sleep(1000);
}
else
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SharePath not found: {0}. Set CreateSharePath to true to create a SharePath that does not exist.", this.SharePath));
return;
}
}
}
using (ManagementClass managementClass = new ManagementClass(this.Scope, path, null))
{
// Set the input parameters
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
inParams["Description"] = this.Description;
inParams["Name"] = this.ShareName;
inParams["Path"] = this.SharePath;
// build the access permissions
if (this.AllowUsers != null | this.DenyUsers != null)
{
inParams["Access"] = this.SetAccessPermissions();
}
// Disk Drive
inParams["Type"] = 0x0;
if (this.MaximumAllowed > 0)
{
inParams["MaximumAllowed"] = this.MaximumAllowed;
}
ManagementBaseObject outParams = managementClass.InvokeMethod("Create", inParams, null);
ReturnCode returnCode = (ReturnCode)Convert.ToUInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture);
switch (returnCode)
{
case ReturnCode.Success:
break;
case ReturnCode.AccessDenied:
this.Log.LogError("Access Denied");
break;
case ReturnCode.UnknownFailure:
this.Log.LogError("Unknown Failure");
break;
case ReturnCode.InvalidName:
this.Log.LogError("Invalid Name");
break;
case ReturnCode.InvalidLevel:
this.Log.LogError("Invalid Level");
break;
case ReturnCode.InvalidParameter:
this.Log.LogError("Invalid Parameter");
break;
case ReturnCode.RedirectedPath:
this.Log.LogError("Redirected Path");
break;
case ReturnCode.UnknownDeviceOrDirectory:
this.Log.LogError("Unknown Device or Directory");
break;
case ReturnCode.NetNameNotFound:
this.Log.LogError("Net name not found");
break;
case ReturnCode.ShareAlreadyExists:
this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "The share already exists: {0}", this.ShareName));
break;
}
}
}
private ManagementObject SetAccessPermissions()
{
// build the security descriptor
ManagementPath securityDescriptorPath = new ManagementPath("Win32_SecurityDescriptor");
ManagementObject returnSecurityDescriptor;
using (ManagementObject securityDescriptor = new ManagementClass(this.Scope, securityDescriptorPath, null).CreateInstance())
{
// default owner | default group | DACL present | default SACL
securityDescriptor.Properties["ControlFlags"].Value = 0x1U | 0x2U | 0x4U | 0x20U;
securityDescriptor.Properties["DACL"].Value = this.BuildAccessControlList();
returnSecurityDescriptor = securityDescriptor;
}
return returnSecurityDescriptor;
}
private ManagementObject[] BuildAccessControlList()
{
List<ManagementObject> acl = new List<ManagementObject>();
if (this.AllowUsers != null)
{
foreach (ITaskItem user in this.AllowUsers)
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Allowing user: {0}", user.ItemSpec));
ManagementObject trustee = this.BuildTrustee(user.ItemSpec);
acl.Add(this.BuildAccessControlEntry(user, trustee, false));
}
}
if (this.DenyUsers != null)
{
foreach (ITaskItem user in this.DenyUsers)
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Denying user: {0}", user.ItemSpec));
ManagementObject trustee = this.BuildTrustee(user.ItemSpec);
acl.Add(this.BuildAccessControlEntry(user, trustee, true));
}
}
this.newPermissionCount = acl.Count;
return acl.ToArray();
}
private ManagementObject BuildTrustee(string userName)
{
if (!userName.Contains(@"\"))
{
// default to local user
userName = Environment.MachineName + @"\" + userName;
}
// build the trustee
string[] userNameParts = userName.Split('\\');
string domain = userNameParts[0];
string alias = userNameParts[1];
ManagementObject account = this.GetAccount(domain, alias);
ManagementObject sid = GetSecurityIdentifier(account);
ManagementPath trusteePath = new ManagementPath("Win32_Trustee");
ManagementObject returnedTrustee;
using (ManagementObject trustee = new ManagementClass(this.Scope, trusteePath, null).CreateInstance())
{
trustee.Properties["Domain"].Value = domain;
trustee.Properties["Name"].Value = alias;
trustee.Properties["SID"].Value = sid.Properties["BinaryRepresentation"].Value;
trustee.Properties["SidLength"].Value = sid.Properties["SidLength"].Value;
trustee.Properties["SIDString"].Value = sid.Properties["SID"].Value;
returnedTrustee = trustee;
}
return returnedTrustee;
}
private ManagementObject GetAccount(string domain, string alias)
{
// get the account - try to get it by searching those on the machine first which gets local accounts
string queryString = string.Format(CultureInfo.InvariantCulture, "select * from Win32_Account where Name = '{0}' and Domain='{1}'", alias, domain);
ObjectQuery query = new ObjectQuery(queryString);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query))
{
foreach (ManagementObject returnedAccount in searcher.Get())
{
return returnedAccount;
}
}
// didn't find it on the machine so we'll try to bind to it using a path - this works for domain accounts
string accountPathString = string.Format(CultureInfo.InvariantCulture, "Win32_Account.Name='{0}',Domain='{1}'", alias, domain);
ManagementPath accountPath = new ManagementPath(accountPathString);
ManagementObject returnAccount;
using (ManagementObject account = new ManagementObject(accountPath))
{
try
{
account.Get();
returnAccount = account;
}
catch (ManagementException ex)
{
throw new Exception(string.Format(CultureInfo.InvariantCulture, @"Could not find account '{0}\{1}'.", domain, alias), ex);
}
}
return returnAccount;
}
private ManagementObject BuildAccessControlEntry(ITaskItem user, ManagementObject trustee, bool deny)
{
ManagementPath acePath = new ManagementPath("Win32_ACE");
ManagementObject returnedAce;
using (ManagementObject ace = new ManagementClass(this.Scope, acePath, null).CreateInstance())
{
string permissions = user.GetMetadata("Permission");
if (string.IsNullOrEmpty(permissions) | permissions.IndexOf("Full", StringComparison.OrdinalIgnoreCase) >= 0)
{
// apply all permissions
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Setting Full permission for: {0}", user.ItemSpec));
ace.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x10000U | 0x20000U | 0x40000U | 0x80000U | 0x100000U;
}
else
{
if (permissions.IndexOf("Read", StringComparison.OrdinalIgnoreCase) >= 0)
{
// readonly permission
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Setting Read permission for: {0}", user.ItemSpec));
ace.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x20000U | 0x40000U | 0x80000U | 0x100000U;
}
if (permissions.IndexOf("Change", StringComparison.OrdinalIgnoreCase) >= 0)
{
// change permission
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Setting Change permission for: {0}", user.ItemSpec));
ace.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x10000U | 0x20000U | 0x40000U | 0x100000U;
}
}
// no flags
ace.Properties["AceFlags"].Value = 0x0U;
// 0 = allow, 1 = deny
ace.Properties["AceType"].Value = deny ? 1U : 0U;
ace.Properties["Trustee"].Value = trustee;
returnedAce = ace;
}
return returnedAce;
}
}
}
| |
using System;
using System.Collections.Generic;
using AutoMapper.Mappers;
using Shouldly;
using Xunit;
namespace AutoMapper.UnitTests.ConfigurationValidation
{
public class When_using_custom_validation
{
bool _calledForRoot = false;
bool _calledForValues = false;
bool _calledForInt = false;
public class Source
{
public int[] Values { get; set; }
}
public class Dest
{
public int[] Values { get; set; }
}
[Fact]
public void Should_call_the_validator()
{
var config = new MapperConfiguration(cfg =>
{
cfg.Advanced.Validator(Validator);
cfg.CreateMap<Source, Dest>();
});
config.AssertConfigurationIsValid();
_calledForRoot.ShouldBeTrue();
_calledForValues.ShouldBeTrue();
_calledForInt.ShouldBeTrue();
}
private void Validator(ValidationContext context)
{
if(context.TypeMap != null)
{
_calledForRoot = true;
context.TypeMap.Types.ShouldBe(context.Types);
context.Types.SourceType.ShouldBe(typeof(Source));
context.Types.DestinationType.ShouldBe(typeof(Dest));
context.ObjectMapper.ShouldBeNull();
context.PropertyMap.ShouldBeNull();
}
else
{
context.PropertyMap.SourceMember.Name.ShouldBe("Values");
context.PropertyMap.DestinationProperty.Name.ShouldBe("Values");
if(context.Types.Equals(new TypePair(typeof(int), typeof(int))))
{
_calledForInt = true;
context.ObjectMapper.ShouldBeOfType<AssignableMapper>();
}
else
{
_calledForValues = true;
context.ObjectMapper.ShouldBeOfType<ArrayMapper>();
context.Types.SourceType.ShouldBe(typeof(int[]));
context.Types.DestinationType.ShouldBe(typeof(int[]));
}
}
}
}
public class When_using_a_type_converter : AutoMapperSpecBase
{
public class A
{
public string Foo { get; set; }
}
public class B
{
public C Foo { get; set; }
}
public class C { }
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => cfg.CreateMap<A, B>().ConvertUsing(x => new B { Foo = new C() }));
}
public class When_using_a_type_converter_class : AutoMapperSpecBase
{
public class A
{
public string Foo { get; set; }
}
public class B
{
public C Foo { get; set; }
}
public class C { }
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => cfg.CreateMap<A, B>().ConvertUsing<Converter>());
class Converter : ITypeConverter<A, B>
{
public B Convert(A source, B dest, ResolutionContext context) => new B { Foo = new C() };
}
}
public class When_skipping_validation : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public int Blarg { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMap<Source, Dest>(MemberList.None));
[Fact]
public void Should_skip_validation()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.ConfigurationProvider.AssertConfigurationIsValid());
}
}
public class When_constructor_does_not_match : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public Dest(int blarg)
{
Value = blarg;
}
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMap<Source, Dest>());
[Fact]
public void Should_throw()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(() => Configuration.AssertConfigurationIsValid());
}
}
public class When_constructor_partially_matches : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public Dest(int value, int blarg)
{
Value = blarg;
}
public int Value { get; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMap<Source, Dest>());
[Fact]
public void Should_throw()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(() => Configuration.AssertConfigurationIsValid());
}
}
public class When_constructor_partially_matches_and_ctor_param_configured : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public Dest(int value, int blarg)
{
Value = blarg;
}
public int Value { get; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Dest>()
.ForCtorParam("blarg", opt => opt.MapFrom(src => src.Value));
});
[Fact]
public void Should_throw()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Configuration.AssertConfigurationIsValid());
}
}
public class When_constructor_partially_matches_and_constructor_validation_skipped : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public Dest(int value, int blarg)
{
Value = blarg;
}
public int Value { get; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Dest>().DisableCtorValidation();
});
[Fact]
public void Should_throw()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Configuration.AssertConfigurationIsValid());
}
}
public class When_testing_a_dto_with_mismatched_members : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
public class ModelObject2
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto2
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
}
public class ModelObject3
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
}
public class ModelDto3
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>();
cfg.CreateMap<ModelObject2, ModelDto2>();
cfg.CreateMap<ModelObject3, ModelDto3>(MemberList.Source);
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_fully_mapped_and_custom_matchers : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.Bar, opt => opt.MapFrom(m => m.Barr));
});
[Fact]
public void Should_pass_an_inspection_of_missing_mappings()
{
Configuration.AssertConfigurationIsValid();
}
}
public class When_testing_a_dto_with_matching_member_names_but_mismatched_types : NonValidatingSpecBase
{
public class Source
{
public decimal Value { get; set; }
}
public class Destination
{
public Type Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMissingTypeMaps = false;
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_member_type_mapped_mappings : AutoMapperSpecBase
{
private AutoMapperConfigurationException _exception;
public class Source
{
public int Value { get; set; }
public OtherSource Other { get; set; }
}
public class OtherSource
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public OtherDest Other { get; set; }
}
public class OtherDest
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<OtherSource, OtherDest>();
});
protected override void Because_of()
{
try
{
Configuration.AssertConfigurationIsValid();
}
catch (AutoMapperConfigurationException ex)
{
_exception = ex;
}
}
[Fact]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_matched_members_but_mismatched_types_that_are_ignored : AutoMapperSpecBase
{
private AutoMapperConfigurationException _exception;
public class ModelObject
{
public string Foo { get; set; }
public string Bar { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public int Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.Ignore());
});
protected override void Because_of()
{
try
{
Configuration.AssertConfigurationIsValid();
}
catch (AutoMapperConfigurationException ex)
{
_exception = ex;
}
}
[Fact]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_array_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public SourceItem[] Items;
}
public class Destination
{
public DestinationItem[] Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMissingTypeMaps = false;
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_list_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public List<SourceItem> Items;
}
public class Destination
{
public List<DestinationItem> Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMissingTypeMaps = false;
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_readonly_members : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public string ValuePlusOne { get { return (Value + 1).ToString(); } }
public int ValuePlusTwo { get { return Value + 2; } }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
Mapper.Map<Source, Destination>(new Source { Value = 5 });
}
[Fact]
public void Should_be_valid()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_in_a_specfic_profile : NonValidatingSpecBase
{
public class GoodSource
{
public int Value { get; set; }
}
public class GoodDest
{
public int Value { get; set; }
}
public class BadDest
{
public int Valufffff { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateProfile("Good", profile =>
{
profile.CreateMap<GoodSource, GoodDest>();
});
cfg.CreateProfile("Bad", profile =>
{
profile.CreateMap<GoodSource, BadDest>();
});
});
[Fact]
public void Should_ignore_bad_dtos_in_other_profiles()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Configuration.AssertConfigurationIsValid("Good"));
}
}
public class When_testing_a_dto_with_mismatched_custom_member_mapping : NonValidatingSpecBase
{
public class SubBarr { }
public class SubBar { }
public class ModelObject
{
public string Foo { get; set; }
public SubBarr Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public SubBar Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Barr));
cfg.CreateMissingTypeMaps = false;
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_value_specified_members : NonValidatingSpecBase
{
public class Source { }
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
object i = 7;
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.UseValue(i));
});
[Fact]
public void Should_validate_successfully()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_setter_only_peroperty_member : NonValidatingSpecBase
{
public class Source
{
public string Value { set { } }
}
public class Destination
{
public string Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_matching_void_method_member : NonValidatingSpecBase
{
public class Source
{
public void Method()
{
}
}
public class Destination
{
public string Method { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_redirecting_types : NonValidatingSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ConcreteSource, ConcreteDest>()
.ForMember(d => d.DifferentName, opt => opt.MapFrom(s => s.Name));
cfg.CreateMap<ConcreteSource, IAbstractDest>().As<ConcreteDest>();
});
[Fact]
public void Should_pass_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
class ConcreteSource
{
public string Name { get; set; }
}
class ConcreteDest : IAbstractDest
{
public string DifferentName { get; set; }
}
interface IAbstractDest
{
string DifferentName { get; set; }
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS
{
using System.Collections.Generic;
/// <summary>
/// The folderContent element contains the content of a folder:
/// its properties, messages, and subFolders.
/// folderContent = propList [PidTagEcWarning]
/// ( PidTagNewFXFolder / folderMessages )
/// [ PidTagFXDelProp *SubFolder ]
/// Actual stream deserialization:
/// folderContent = propList [PidTagEcWarning]
/// ( (*(*PidTagFXDelProp PidTagNewFXFolder)) / folderMessages )
/// [ *PidTagFXDelProp *SubFolder ]
/// </summary>
public class FolderContent : SyntacticalBase
{
#region Members
/// <summary>
/// Contains the properties of the Folder object, which are possibly affected by property filters.
/// </summary>
private PropList propList;
/// <summary>
/// The folderMessages element contains the messages contained in a folder.
/// </summary>
private FolderMessages folderMessages;
/// <summary>
/// The folderContent element contains the content of a folder: its properties, messages, and subFolders.
/// </summary>
private List<SubFolder> subFolders;
/// <summary>
/// The warning code.
/// </summary>
private uint? warningCode;
/// <summary>
/// The new fxFolder list.
/// </summary>
private List<Tuple<List<uint>, FolderReplicaInfo>> newFXFolderList;
/// <summary>
/// The fxdel prop list.
/// </summary>
private List<uint> fxdelPropList;
#region Constructors
/// <summary>
/// Initializes a new instance of the FolderContent class.
/// </summary>
/// <param name="stream">A FastTransferStream.</param>
public FolderContent(FastTransferStream stream)
: base(stream)
{
}
#endregion
/// <summary>
/// Gets or sets the NewFXFolderList.
/// </summary>
public List<Tuple<List<uint>, FolderReplicaInfo>> NewFXFolderList
{
get { return this.newFXFolderList; }
set { this.newFXFolderList = value; }
}
/// <summary>
/// Gets or sets warningCode.
/// </summary>
public uint? WarningCode
{
get { return this.warningCode; }
set { this.warningCode = value; }
}
/// <summary>
/// Gets or sets FXDelPropList before subFolder list.
/// </summary>
public List<uint> FXDelPropList
{
get { return this.fxdelPropList; }
set { this.fxdelPropList = value; }
}
/// <summary>
/// Gets or sets folderMessages.
/// </summary>
public FolderMessages FolderMessages
{
get { return this.folderMessages; }
set { this.folderMessages = value; }
}
/// <summary>
/// Gets or sets subFolders.
/// </summary>
public List<SubFolder> SubFolders
{
get { return this.subFolders; }
set { this.subFolders = value; }
}
/// <summary>
/// Gets or sets propList.
/// </summary>
public PropList PropList
{
get { return this.propList; }
set { this.propList = value; }
}
/// <summary>
/// Gets a value indicating whether contains pidtagNewfxfolder.
/// </summary>
public bool HasNewFXFolder
{
get
{
return (this.NewFXFolderList != null)
&& this.NewFXFolderList.Count > 0;
}
}
#endregion
#region Static methods
/// <summary>
/// Verify that a stream's current position contains a serialized folderContent.
/// </summary>
/// <param name="stream">A FastTransferStream.</param>
/// <returns>If the stream's current position contains
/// a serialized folderContent, return true, else false.</returns>
public static bool Verify(FastTransferStream stream)
{
return PropList.Verify(stream);
}
#endregion
#region Methods
/// <summary>
/// Get the corresponding AbstractFastTransferStream.
/// </summary>
/// <returns>The corresponding AbstractFastTransferStream.</returns>
public AbstractFastTransferStream GetAbstractFastTransferStream()
{
AbstractFastTransferStream afts = default(AbstractFastTransferStream);
afts.StreamType = FastTransferStreamType.folderContent;
afts.AbstractFolderContent.IsNoPermissionObjNotOut = !(this.SubFolders != null && this.SubFolders.Count > 0);
afts.AbstractFolderContent.IsPidTagEcWarningOut = this.WarningCode != null;
// The stack uses the structure defined in Open Specification 2.2.4.2 and the order to deserialize the payload. If the deserialization succeeds, the condition that IsFolderMessagesPrecededByPidTagFXDelProp is met.
if (this.FolderMessages != null && this.folderMessages.FXDelPropList != null)
{
for (int i = 0; i < this.folderMessages.FXDelPropList.Count; i++)
{
if ((this.folderMessages.FXDelPropList[i] == 0x3610000d) || (this.folderMessages.FXDelPropList[i] == 0x360F000d))
{
afts.AbstractFolderContent.AbsFolderMessage.IsFolderMessagesPrecededByPidTagFXDelProp = true;
break;
}
}
}
if (this.SubFolders != null && this.SubFolders.Count > 0)
{
// afts.AbstractTopFolder.subFolderInScope = true;
// The stack uses the structure defined in Open Specification 2.2.4.2 and the order to deserialize the payload. If the deserialization succeeds, the condition that IsFolderMessagesPrecededByPidTagFXDelProp is met.
for (int i = 0; i < this.FXDelPropList.Count; i++)
{
if (this.FXDelPropList[i] == 0x360E000d)
{
afts.AbstractFolderContent.IsSubFolderPrecededByPidTagFXDelProp = true;
break;
}
}
}
// afts.AbstractFolderContent.AbsFolderMessage.MessageList.AbsMessage.AbsMessageContent.IsNoPermissionMessageNotOut = ((this.SubFolders == null) || (this.SubFolders != null && this.SubFolders.Count == 0));
return afts;
}
/// <summary>
/// Deserialize fields from a FastTransferStream.
/// </summary>
/// <param name="stream">A FastTransferStream.</param>
public override void Deserialize(FastTransferStream stream)
{
// Actual stream deserialization:
// folderContent = propList [PidTagEcWarning]
// ( (*(*PidTagFXDelProp PidTagNewFXFolder)) / folderMessages )
// [ *PidTagFXDelProp *SubFolder ]
this.warningCode = null;
this.fxdelPropList = new List<uint>();
this.newFXFolderList = new List<Tuple<List<uint>, MS_OXCFXICS.FolderReplicaInfo>>();
this.propList = new PropList(stream);
if (!stream.IsEndOfStream)
{
uint marker = stream.VerifyUInt32();
if (marker == (uint)MetaProperties.PidTagEcWarning)
{
marker = stream.ReadUInt32();
this.warningCode = stream.ReadUInt32();
marker = stream.VerifyUInt32();
}
long lastPosi = stream.Position;
while (stream.VerifyMetaProperty(MetaProperties.PidTagFXDelProp)
|| stream.VerifyMetaProperty(MetaProperties.PidTagNewFXFolder))
{
lastPosi = stream.Position;
List<uint> tempFXdel = new List<uint>();
while (stream.VerifyMetaProperty(MetaProperties.PidTagFXDelProp))
{
stream.ReadMetaProperty(MetaProperties.PidTagFXDelProp);
uint prop = stream.ReadUInt32();
tempFXdel.Add(prop);
}
if (!stream.IsEndOfStream)
{
marker = stream.VerifyUInt32();
}
if (marker == (uint)MetaProperties.PidTagNewFXFolder)
{
marker = stream.ReadUInt32();
stream.ReadUInt32();
FolderReplicaInfo fri = new FolderReplicaInfo(stream);
this.newFXFolderList.Add(
new Tuple<List<uint>, FolderReplicaInfo>(
tempFXdel, fri));
}
else
{
stream.Position = lastPosi;
marker = stream.VerifyUInt32();
break;
}
}
if (FolderMessages.Verify(stream))
{
this.folderMessages = new FolderMessages(stream);
}
this.subFolders = new List<SubFolder>();
while (stream.VerifyMetaProperty(MetaProperties.PidTagFXDelProp))
{
stream.ReadMetaProperty(MetaProperties.PidTagFXDelProp);
uint prop = stream.ReadUInt32();
this.fxdelPropList.Add(prop);
}
while (SubFolder.Verify(stream))
{
this.subFolders.Add(new SubFolder(stream));
}
}
}
#endregion
}
}
| |
//
// MimePart.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
using MimeKit.IO;
using MimeKit.IO.Filters;
using MimeKit.Encodings;
namespace MimeKit {
/// <summary>
/// A basic leaf-node MIME part that contains content such as the message body or an attachment.
/// </summary>
public class MimePart : MimeEntity
{
static readonly string[] ContentTransferEncodings = new string[] {
null, "7bit", "8bit", "binary", "base64", "quoted-printable", "x-uuencode"
};
ContentEncoding encoding;
string md5sum;
int? duration;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MimePart"/> class
/// based on the <see cref="MimeEntityConstructorInfo"/>.
/// </summary>
/// <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks>
/// <param name="entity">Information used by the constructor.</param>
public MimePart (MimeEntityConstructorInfo entity) : base (entity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MimePart"/> class
/// with the specified media type and subtype.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="mediaSubtype">The media subtype.</param>
/// <param name="args">An array of initialization parameters: headers and part content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="mediaType"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="mediaSubtype"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="args"/> contains more than one <see cref="MimeKit.IContentObject"/> or
/// <see cref="System.IO.Stream"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> contains one or more arguments of an unknown type.</para>
/// </exception>
public MimePart (string mediaType, string mediaSubtype, params object[] args) : this (mediaType, mediaSubtype)
{
if (args == null)
throw new ArgumentNullException ("args");
IContentObject content = null;
foreach (object obj in args) {
if (obj == null || TryInit (obj))
continue;
IContentObject co = obj as IContentObject;
if (co != null) {
if (content != null)
throw new ArgumentException ("ContentObject should not be specified more than once.");
content = co;
continue;
}
Stream s = obj as Stream;
if (s != null) {
if (content != null)
throw new ArgumentException ("Stream (used as content) should not be specified more than once.");
// Use default as specified by ContentObject ctor when building a new MimePart.
content = new ContentObject (s, ContentEncoding.Default);
continue;
}
throw new ArgumentException ("Unknown initialization parameter: " + obj.GetType ());
}
if (content != null)
ContentObject = content;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MimePart"/> class
/// with the specified media type and subtype.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="mediaSubtype">The media subtype.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="mediaType"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="mediaSubtype"/> is <c>null</c>.</para>
/// </exception>
public MimePart (string mediaType, string mediaSubtype) : base (mediaType, mediaSubtype)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MimePart"/> class
/// with the default Content-Type of application/octet-stream.
/// </summary>
public MimePart () : base ("application", "octet-stream")
{
}
/// <summary>
/// Gets or sets the duration of the content if available.
/// </summary>
/// <value>The duration of the content.</value>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="value"/> is negative.
/// </exception>
public int? ContentDuration {
get { return duration; }
set {
if (duration == value)
return;
if (value.HasValue && value.Value < 0)
throw new ArgumentOutOfRangeException ("value");
if (value.HasValue)
SetHeader ("Content-Duration", value.Value.ToString ());
else
RemoveHeader ("Content-Duration");
}
}
/// <summary>
/// Gets or sets the md5sum of the content.
/// </summary>
/// <value>The md5sum of the content.</value>
public string ContentMd5 {
get { return md5sum; }
set {
if (md5sum == value)
return;
if (value != null)
md5sum = value.Trim ();
else
md5sum = null;
if (value != null)
SetHeader ("Content-Md5", md5sum);
else
RemoveHeader ("Content-Md5");
}
}
/// <summary>
/// Gets or sets the content transfer encoding.
/// </summary>
/// <value>The content transfer encoding.</value>
public ContentEncoding ContentTransferEncoding {
get { return encoding; }
set {
if (encoding == value)
return;
var text = ContentTransferEncodings[(int) value];
encoding = value;
if (text != null)
SetHeader ("Content-Transfer-Encoding", text);
else
RemoveHeader ("Content-Transfer-Encoding");
}
}
/// <summary>
/// Gets or sets the name of the file.
/// </summary>
/// <remarks>
/// <para>First checks for the "filename" parameter on the Content-Disposition header. If
/// that does not exist, then the "name" parameter on the Content-Type header is used.</para>
/// <para>When setting the filename, both the "filename" parameter on the Content-Disposition
/// header and the "name" parameter on the Content-Type header are set.</para>
/// </remarks>
/// <value>The name of the file.</value>
public string FileName {
get {
string filename = null;
if (ContentDisposition != null)
filename = ContentDisposition.FileName;
if (filename == null)
filename = ContentType.Name;
if (filename == null)
return null;
return filename.Trim ();
}
set {
if (value != null) {
if (ContentDisposition == null)
ContentDisposition = new ContentDisposition ();
ContentDisposition.FileName = value;
} else if (ContentDisposition != null) {
ContentDisposition.FileName = value;
}
ContentType.Name = value;
}
}
/// <summary>
/// Gets or sets the content of the mime part.
/// </summary>
/// <value>The content of the mime part.</value>
public IContentObject ContentObject {
get; set;
}
/// <summary>
/// Gets a value indicating whether this <see cref="MimePart"/> is an attachment.
/// </summary>
/// <value><c>true</c> if this <see cref="MimePart"/> is an attachment; otherwise, <c>false</c>.</value>
public bool IsAttachment {
get { return ContentDisposition != null && ContentDisposition.IsAttachment; }
set {
if (value) {
if (ContentDisposition == null)
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment);
else if (!ContentDisposition.IsAttachment)
ContentDisposition.Disposition = ContentDisposition.Attachment;
} else if (ContentDisposition != null && ContentDisposition.IsAttachment) {
ContentDisposition.Disposition = ContentDisposition.Inline;
}
}
}
/// <summary>
/// Calculates the most efficient content encoding given the specified constraint.
/// </summary>
/// <remarks>
/// If no <see cref="ContentObject"/> is set, <see cref="ContentEncoding.SevenBit"/> will be returned.
/// </remarks>
/// <returns>The most efficient content encoding.</returns>
/// <param name="constraint">The encoding constraint.</param>
/// <param name="token">A cancellation token.</param>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public ContentEncoding GetBestEncoding (EncodingConstraint constraint, CancellationToken token)
{
if (ContentObject == null)
return ContentEncoding.SevenBit;
using (var measure = new MeasuringStream ()) {
using (var filtered = new FilteredStream (measure)) {
var filter = new BestEncodingFilter ();
filtered.Add (filter);
ContentObject.DecodeTo (filtered, token);
filtered.Flush ();
return filter.GetBestEncoding (constraint);
}
}
}
/// <summary>
/// Calculates the most efficient content encoding given the specified constraint.
/// </summary>
/// <remarks>
/// If no <see cref="ContentObject"/> is set, <see cref="ContentEncoding.SevenBit"/> will be returned.
/// </remarks>
/// <returns>The most efficient content encoding.</returns>
/// <param name="constraint">The encoding constraint.</param>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public ContentEncoding GetBestEncoding (EncodingConstraint constraint)
{
return GetBestEncoding (constraint, CancellationToken.None);
}
/// <summary>
/// Computes the md5sum of the content.
/// </summary>
/// <returns>The md5sum of the content.</returns>
/// <exception cref="System.InvalidOperationException">
/// The <see cref="ContentObject"/> is <c>null</c>.
/// </exception>
public string ComputeContentMd5 ()
{
if (ContentObject == null)
throw new InvalidOperationException ("Cannot compute Md5 checksum without a ContentObject.");
var stream = ContentObject.Stream;
stream.Seek (0, SeekOrigin.Begin);
byte[] checksum;
using (var filtered = new FilteredStream (stream)) {
filtered.Add (DecoderFilter.Create (ContentObject.Encoding));
if (ContentType.Matches ("text", "*"))
filtered.Add (new Unix2DosFilter ());
using (var md5 = HashAlgorithm.Create ("MD5"))
checksum = md5.ComputeHash (filtered);
}
var base64 = new Base64Encoder (true);
var digest = new byte[base64.EstimateOutputLength (checksum.Length)];
int n = base64.Flush (checksum, 0, checksum.Length, digest);
return Encoding.ASCII.GetString (digest, 0, n);
}
/// <summary>
/// Verifies the Content-Md5 value against an independently computed md5sum.
/// </summary>
/// <returns><c>true</c>, if content md5sum was verified, <c>false</c> otherwise.</returns>
public bool VerifyContentMd5 ()
{
if (string.IsNullOrWhiteSpace (md5sum) || ContentObject == null)
return false;
return md5sum == ComputeContentMd5 ();
}
static bool NeedsEncoding (ContentEncoding encoding)
{
switch (encoding) {
case ContentEncoding.EightBit:
case ContentEncoding.Binary:
case ContentEncoding.Default:
return true;
default:
return false;
}
}
/// <summary>
/// Writes the <see cref="MimeKit.MimePart"/> to the specified output stream.
/// </summary>
/// <param name="options">The formatting options.</param>
/// <param name="stream">The output stream.</param>
/// <param name="token">A cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="stream"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override void WriteTo (FormatOptions options, Stream stream, CancellationToken token)
{
var saved = encoding;
if (NeedsEncoding (encoding)) {
var best = GetBestEncoding (options.EncodingConstraint);
if (best != ContentEncoding.SevenBit)
ContentTransferEncoding = best;
}
try {
base.WriteTo (options, stream, token);
if (ContentObject == null)
return;
if (ContentObject.Encoding != encoding) {
if (encoding == ContentEncoding.UUEncode) {
var begin = string.Format ("begin 0644 {0}", FileName ?? "unknown");
var buffer = Encoding.UTF8.GetBytes (begin);
stream.Write (buffer, 0, buffer.Length);
stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);
}
// transcode the content into the desired Content-Transfer-Encoding
using (var filtered = new FilteredStream (stream)) {
filtered.Add (EncoderFilter.Create (encoding));
if (encoding != ContentEncoding.Binary)
filtered.Add (options.CreateNewLineFilter ());
ContentObject.DecodeTo (filtered, token);
filtered.Flush ();
}
if (encoding == ContentEncoding.UUEncode) {
var buffer = Encoding.ASCII.GetBytes ("end");
stream.Write (buffer, 0, buffer.Length);
stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);
}
} else if (encoding != ContentEncoding.Binary) {
using (var filtered = new FilteredStream (stream)) {
filtered.Add (options.CreateNewLineFilter ());
ContentObject.WriteTo (filtered, token);
filtered.Flush ();
}
} else {
ContentObject.WriteTo (stream, token);
}
} finally {
if (saved != ContentEncoding.Default)
ContentTransferEncoding = saved;
}
}
/// <summary>
/// Called when the headers change in some way.
/// </summary>
/// <param name="action">The type of change.</param>
/// <param name="header">The header being added, changed or removed.</param>
protected override void OnHeadersChanged (HeaderListChangedAction action, Header header)
{
string text;
int value;
base.OnHeadersChanged (action, header);
switch (action) {
case HeaderListChangedAction.Added:
case HeaderListChangedAction.Changed:
switch (header.Id) {
case HeaderId.ContentTransferEncoding:
text = header.Value.Trim ().ToLowerInvariant ();
encoding = ContentEncoding.Default;
for (int i = 1; i < ContentTransferEncodings.Length; i++) {
if (ContentTransferEncodings[i] == text) {
encoding = (ContentEncoding) i;
break;
}
}
break;
case HeaderId.ContentDuration:
if (int.TryParse (header.Value, out value))
duration = value;
else
duration = null;
break;
case HeaderId.ContentMd5:
md5sum = header.Value.Trim ();
break;
}
break;
case HeaderListChangedAction.Removed:
switch (header.Id) {
case HeaderId.ContentTransferEncoding:
encoding = ContentEncoding.Default;
break;
case HeaderId.ContentDuration:
duration = null;
break;
case HeaderId.ContentMd5:
md5sum = null;
break;
}
break;
case HeaderListChangedAction.Cleared:
encoding = ContentEncoding.Default;
duration = null;
md5sum = null;
break;
default:
throw new ArgumentOutOfRangeException ();
}
}
}
}
| |
/*
* nMQTT, a .Net MQTT v3 client implementation.
* http://wiki.github.com/markallanson/nmqtt
*
* Copyright (c) 2009 Mark Allanson (mark@markallanson.net) & Contributors
*
* Licensed under the MIT License. You may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/mit-license.php
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
namespace Nmqtt
{
/// <summary>
/// Represents the Fixed Header of an MQTT message.
/// </summary>
internal partial class MqttHeader
{
/// <summary>
/// Backing storage for the payload size.
/// </summary>
private int messageSize;
/// <summary>
/// Gets or sets the type of the MQTT message.
/// </summary>
/// <value>The type of the MQTT message.</value>
public MqttMessageType MessageType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this MQTT Message is duplicate of a previous message.
/// </summary>
/// <value>
/// <c>true</c> if duplicate; otherwise, <c>false</c>.
/// </value>
public bool Duplicate { get; set; }
/// <summary>
/// Gets or sets the Quality of Service indicator for the message.
/// </summary>
/// <value>The qos.</value>
public MqttQos Qos { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this MQTT message should be retained by the message broker for transmission to new subscribers.
/// </summary>
/// <value>
/// <c>true</c> if message should be retained by the message broker; otherwise, <c>false</c>.
/// </value>
public bool Retain { get; set; }
/// <summary>
/// Gets or sets the size of the variable header + payload section of the message.
/// </summary>
/// <value>The size of the variable header + payload.</value>
/// <exception cref="Nmqtt.InvalidPayloadSizeException">The size of the variable header + payload exceeds the maximum allowed size.</exception>
public int MessageSize {
get { return this.messageSize; }
set {
if (value < 0 || value > Constants.MaxMessageSize) {
throw new InvalidPayloadSizeException(value, Constants.MaxMessageSize);
}
messageSize = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MqttHeader" /> class.
/// </summary>
public MqttHeader() {}
/// <summary>
/// Initializes a new instance of the <see cref="MqttHeader" /> class based on data contained within the supplied stream.
/// </summary>
/// <param name="headerStream">The stream containing the header message.</param>
public MqttHeader(Stream headerStream) {
ReadFrom(headerStream);
}
/// <summary>
/// Writes the header to a supplied stream.
/// </summary>
/// <param name="messageSize">The size of the message to write.</param>
/// <param name="messageStream">The stream to write the header bytes to.</param>
public void WriteTo(int messageSize, Stream messageStream) {
this.MessageSize = messageSize;
List<byte> headerBytes = HeaderBytes;
messageStream.Write(headerBytes.ToArray(), 0, headerBytes.Count);
}
/// <summary>
/// Creates a new MqttHeader based on a list of bytes.
/// </summary>
/// <param name="headerStream">The stream that contains the message, positioned at the beginning of the header.</param>
/// <returns></returns>
internal void ReadFrom(Stream headerStream) {
if (headerStream.Length < 2) {
throw new InvalidHeaderException("The supplied header is invalid. Header must be at least 2 bytes long.");
}
int firstHeaderByte = headerStream.ReadByte();
// pull out the first byte
Retain = ((firstHeaderByte & 1) == 1 ? true : false);
Qos = (MqttQos) ((firstHeaderByte & 6) >> 1);
Duplicate = (((firstHeaderByte & 8) >> 3) == 1 ? true : false);
MessageType = (MqttMessageType) ((firstHeaderByte & 240) >> 4);
// decode the remaining bytes as the remaining/payload size, input param is the 2nd to last byte of the header byte list
try {
MessageSize = ReadRemainingLength(headerStream);
} catch (InvalidPayloadSizeException ex) {
throw new InvalidHeaderException("The header being processed contained an invalid size byte pattern." +
"Message size must take a most 4 bytes, and the last byte must have bit 8 set to 0.",
ex);
}
}
/// <summary>
/// Gets the value of the Mqtt header as a byte array
/// </summary>
private List<byte> HeaderBytes {
get {
var headerBytes = new List<byte>();
// build the bytes that make up the header. The first byte is a combination of message type, dup,
// qos and retain, and the follow bytes (up to 4 of them) are the size of the payload + variable header.
headerBytes.Add(
(byte)
((((int) MessageType) << 4) + ((Duplicate ? 1 : 0) << 3) + (((int) Qos) << 1) + (Retain ? 1 : 0)));
headerBytes.AddRange(GetRemainingLengthBytes());
return headerBytes;
}
}
private static int ReadRemainingLength(Stream headerStream) {
Collection<byte> lengthBytes = ReadLengthBytes(headerStream);
return CalculateLength(lengthBytes);
}
/// <summary>
/// Calculates the remaining length of an mqttmessage from the bytes that make up the length
/// </summary>
/// <param name="lengthBytes">The length bytes.</param>
/// <returns></returns>
internal static int CalculateLength(IEnumerable<byte> lengthBytes) {
var remainingLength = 0;
var multiplier = 1;
foreach (var currentByte in lengthBytes) {
remainingLength += (currentByte & 0x7f)*multiplier;
multiplier *= 0x80;
}
return remainingLength;
}
/// <summary>
/// Reads the length bytes of an MqttHeader from the supplied stream.
/// </summary>
/// <param name="headerStream">The header stream.</param>
/// <returns></returns>
internal static Collection<byte> ReadLengthBytes(Stream headerStream) {
var lengthBytes = new Collection<byte>();
// read until we've got the entire size, or the 4 byte limit is reached
byte sizeByte;
int byteCount = 0;
do {
sizeByte = (byte) headerStream.ReadByte();
lengthBytes.Add(sizeByte);
} while (++byteCount <= 4 && (sizeByte & 0x80) == 0x80);
return lengthBytes;
}
/// <summary>
/// Calculates and return the bytes that represent the remaining length of the message.
/// </summary>
/// <returns></returns>
private List<byte> GetRemainingLengthBytes() {
var lengthBytes = new List<byte>();
int payloadCalc = messageSize;
// generate a byte array based on the message size, splitting it up into
// 7 bit chunks, with the 8th bit being used to indicate "one more to come"
do {
int nextByteValue = payloadCalc%128;
payloadCalc = payloadCalc/128;
if (payloadCalc > 0) {
nextByteValue = nextByteValue | 0x80;
}
lengthBytes.Add((byte) nextByteValue);
} while (payloadCalc > 0);
return lengthBytes;
}
/// <summary>
/// Returns a <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// A <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
/// </returns>
public override string ToString() {
var sb = new StringBuilder();
sb.AppendLine(String.Format("Header: MessageType={0}, Duplicate={1}, Retain={2}, Qos={3}, Size={4}",
MessageType, Duplicate, Retain, Qos, MessageSize));
return sb.ToString();
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Media.Effect.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Media.Effect
{
/// <java-name>
/// android/media/effect/EffectUpdateListener
/// </java-name>
[Dot42.DexImport("android/media/effect/EffectUpdateListener", AccessFlags = 1537)]
public partial interface IEffectUpdateListener
/* scope: __dot42__ */
{
/// <java-name>
/// onEffectUpdated
/// </java-name>
[Dot42.DexImport("onEffectUpdated", "(Landroid/media/effect/Effect;Ljava/lang/Object;)V", AccessFlags = 1025)]
void OnEffectUpdated(global::Android.Media.Effect.Effect effect, object @object) /* MethodBuilder.Create */ ;
}
/// <java-name>
/// android/media/effect/EffectContext
/// </java-name>
[Dot42.DexImport("android/media/effect/EffectContext", AccessFlags = 33)]
public partial class EffectContext
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal EffectContext() /* MethodBuilder.Create */
{
}
/// <java-name>
/// createWithCurrentGlContext
/// </java-name>
[Dot42.DexImport("createWithCurrentGlContext", "()Landroid/media/effect/EffectContext;", AccessFlags = 9)]
public static global::Android.Media.Effect.EffectContext CreateWithCurrentGlContext() /* MethodBuilder.Create */
{
return default(global::Android.Media.Effect.EffectContext);
}
/// <java-name>
/// getFactory
/// </java-name>
[Dot42.DexImport("getFactory", "()Landroid/media/effect/EffectFactory;", AccessFlags = 1)]
public virtual global::Android.Media.Effect.EffectFactory GetFactory() /* MethodBuilder.Create */
{
return default(global::Android.Media.Effect.EffectFactory);
}
/// <java-name>
/// release
/// </java-name>
[Dot42.DexImport("release", "()V", AccessFlags = 1)]
public virtual void Release() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getFactory
/// </java-name>
public global::Android.Media.Effect.EffectFactory Factory
{
[Dot42.DexImport("getFactory", "()Landroid/media/effect/EffectFactory;", AccessFlags = 1)]
get{ return GetFactory(); }
}
}
/// <java-name>
/// android/media/effect/Effect
/// </java-name>
[Dot42.DexImport("android/media/effect/Effect", AccessFlags = 1057)]
public abstract partial class Effect
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Effect() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetName() /* MethodBuilder.Create */ ;
/// <java-name>
/// apply
/// </java-name>
[Dot42.DexImport("apply", "(IIII)V", AccessFlags = 1025)]
public abstract void Apply(int int32, int int321, int int322, int int323) /* MethodBuilder.Create */ ;
/// <java-name>
/// setParameter
/// </java-name>
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 1025)]
public abstract void SetParameter(string @string, object @object) /* MethodBuilder.Create */ ;
/// <java-name>
/// setUpdateListener
/// </java-name>
[Dot42.DexImport("setUpdateListener", "(Landroid/media/effect/EffectUpdateListener;)V", AccessFlags = 1)]
public virtual void SetUpdateListener(global::Android.Media.Effect.IEffectUpdateListener effectUpdateListener) /* MethodBuilder.Create */
{
}
/// <java-name>
/// release
/// </java-name>
[Dot42.DexImport("release", "()V", AccessFlags = 1025)]
public abstract void Release() /* MethodBuilder.Create */ ;
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetName(); }
}
}
/// <java-name>
/// android/media/effect/EffectFactory
/// </java-name>
[Dot42.DexImport("android/media/effect/EffectFactory", AccessFlags = 33)]
public partial class EffectFactory
/* scope: __dot42__ */
{
/// <java-name>
/// EFFECT_BRIGHTNESS
/// </java-name>
[Dot42.DexImport("EFFECT_BRIGHTNESS", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_BRIGHTNESS = "android.media.effect.effects.BrightnessEffect";
/// <java-name>
/// EFFECT_CONTRAST
/// </java-name>
[Dot42.DexImport("EFFECT_CONTRAST", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_CONTRAST = "android.media.effect.effects.ContrastEffect";
/// <java-name>
/// EFFECT_FISHEYE
/// </java-name>
[Dot42.DexImport("EFFECT_FISHEYE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_FISHEYE = "android.media.effect.effects.FisheyeEffect";
/// <java-name>
/// EFFECT_BACKDROPPER
/// </java-name>
[Dot42.DexImport("EFFECT_BACKDROPPER", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_BACKDROPPER = "android.media.effect.effects.BackDropperEffect";
/// <java-name>
/// EFFECT_AUTOFIX
/// </java-name>
[Dot42.DexImport("EFFECT_AUTOFIX", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_AUTOFIX = "android.media.effect.effects.AutoFixEffect";
/// <java-name>
/// EFFECT_BLACKWHITE
/// </java-name>
[Dot42.DexImport("EFFECT_BLACKWHITE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_BLACKWHITE = "android.media.effect.effects.BlackWhiteEffect";
/// <java-name>
/// EFFECT_CROP
/// </java-name>
[Dot42.DexImport("EFFECT_CROP", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_CROP = "android.media.effect.effects.CropEffect";
/// <java-name>
/// EFFECT_CROSSPROCESS
/// </java-name>
[Dot42.DexImport("EFFECT_CROSSPROCESS", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_CROSSPROCESS = "android.media.effect.effects.CrossProcessEffect";
/// <java-name>
/// EFFECT_DOCUMENTARY
/// </java-name>
[Dot42.DexImport("EFFECT_DOCUMENTARY", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_DOCUMENTARY = "android.media.effect.effects.DocumentaryEffect";
/// <java-name>
/// EFFECT_BITMAPOVERLAY
/// </java-name>
[Dot42.DexImport("EFFECT_BITMAPOVERLAY", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_BITMAPOVERLAY = "android.media.effect.effects.BitmapOverlayEffect";
/// <java-name>
/// EFFECT_DUOTONE
/// </java-name>
[Dot42.DexImport("EFFECT_DUOTONE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_DUOTONE = "android.media.effect.effects.DuotoneEffect";
/// <java-name>
/// EFFECT_FILLLIGHT
/// </java-name>
[Dot42.DexImport("EFFECT_FILLLIGHT", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_FILLLIGHT = "android.media.effect.effects.FillLightEffect";
/// <java-name>
/// EFFECT_FLIP
/// </java-name>
[Dot42.DexImport("EFFECT_FLIP", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_FLIP = "android.media.effect.effects.FlipEffect";
/// <java-name>
/// EFFECT_GRAIN
/// </java-name>
[Dot42.DexImport("EFFECT_GRAIN", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_GRAIN = "android.media.effect.effects.GrainEffect";
/// <java-name>
/// EFFECT_GRAYSCALE
/// </java-name>
[Dot42.DexImport("EFFECT_GRAYSCALE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_GRAYSCALE = "android.media.effect.effects.GrayscaleEffect";
/// <java-name>
/// EFFECT_LOMOISH
/// </java-name>
[Dot42.DexImport("EFFECT_LOMOISH", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_LOMOISH = "android.media.effect.effects.LomoishEffect";
/// <java-name>
/// EFFECT_NEGATIVE
/// </java-name>
[Dot42.DexImport("EFFECT_NEGATIVE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_NEGATIVE = "android.media.effect.effects.NegativeEffect";
/// <java-name>
/// EFFECT_POSTERIZE
/// </java-name>
[Dot42.DexImport("EFFECT_POSTERIZE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_POSTERIZE = "android.media.effect.effects.PosterizeEffect";
/// <java-name>
/// EFFECT_REDEYE
/// </java-name>
[Dot42.DexImport("EFFECT_REDEYE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_REDEYE = "android.media.effect.effects.RedEyeEffect";
/// <java-name>
/// EFFECT_ROTATE
/// </java-name>
[Dot42.DexImport("EFFECT_ROTATE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_ROTATE = "android.media.effect.effects.RotateEffect";
/// <java-name>
/// EFFECT_SATURATE
/// </java-name>
[Dot42.DexImport("EFFECT_SATURATE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_SATURATE = "android.media.effect.effects.SaturateEffect";
/// <java-name>
/// EFFECT_SEPIA
/// </java-name>
[Dot42.DexImport("EFFECT_SEPIA", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_SEPIA = "android.media.effect.effects.SepiaEffect";
/// <java-name>
/// EFFECT_SHARPEN
/// </java-name>
[Dot42.DexImport("EFFECT_SHARPEN", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_SHARPEN = "android.media.effect.effects.SharpenEffect";
/// <java-name>
/// EFFECT_STRAIGHTEN
/// </java-name>
[Dot42.DexImport("EFFECT_STRAIGHTEN", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_STRAIGHTEN = "android.media.effect.effects.StraightenEffect";
/// <java-name>
/// EFFECT_TEMPERATURE
/// </java-name>
[Dot42.DexImport("EFFECT_TEMPERATURE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_TEMPERATURE = "android.media.effect.effects.ColorTemperatureEffect";
/// <java-name>
/// EFFECT_TINT
/// </java-name>
[Dot42.DexImport("EFFECT_TINT", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_TINT = "android.media.effect.effects.TintEffect";
/// <java-name>
/// EFFECT_VIGNETTE
/// </java-name>
[Dot42.DexImport("EFFECT_VIGNETTE", "Ljava/lang/String;", AccessFlags = 25)]
public const string EFFECT_VIGNETTE = "android.media.effect.effects.VignetteEffect";
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal EffectFactory() /* MethodBuilder.Create */
{
}
/// <java-name>
/// createEffect
/// </java-name>
[Dot42.DexImport("createEffect", "(Ljava/lang/String;)Landroid/media/effect/Effect;", AccessFlags = 1)]
public virtual global::Android.Media.Effect.Effect CreateEffect(string @string) /* MethodBuilder.Create */
{
return default(global::Android.Media.Effect.Effect);
}
/// <java-name>
/// isEffectSupported
/// </java-name>
[Dot42.DexImport("isEffectSupported", "(Ljava/lang/String;)Z", AccessFlags = 9)]
public static bool IsEffectSupported(string @string) /* MethodBuilder.Create */
{
return default(bool);
}
}
}
| |
using System;
using System.Collections.Generic;
using xsc = DotNetXmlSwfChart;
namespace testWeb.tests
{
public class StackedColumn3dOne : ChartTestBase
{
#region ChartInclude
public override DotNetXmlSwfChart.ChartHTML ChartInclude
{
get
{
DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML();
chartHtml.height = 300;
chartHtml.bgColor = "aa88ff";
chartHtml.flashFile = "charts/charts.swf";
chartHtml.libraryPath = "charts/charts_library";
chartHtml.xmlSource = "xmlData.aspx";
return chartHtml;
}
}
#endregion
#region Chart
public override DotNetXmlSwfChart.Chart Chart
{
get
{
xsc.Chart c = new xsc.Chart();
c.AddChartType(xsc.XmlSwfChartType.ColumnStacked3d);
c.AxisCategory = SetAxisCategory(c.ChartType[0]);
c.AxisTicks = SetAxisTicks();
c.AxisValue = SetAxisValue();
c.ChartBorder = SetChartBorder();
c.Data = SetChartData();
c.ChartGridH = SetChartGridH();
c.ChartRectangle = SetChartRectangle();
c.ChartTransition = SetChartTransition();
c.ChartValue = SetChartValue();
c.AddDrawImage(CreateDrawImage());
c.LegendLabel = SetLegendLabel();
c.LegendRectangle = SetLegendRectangle();
c.LinkAreas = SetLinkAreas();
c.AddSeriesColor("666666");
c.AddSeriesColor("768bb3");
c.SeriesGap = SetSeriesGap();
return c;
}
}
#endregion
#region Helpers
#region SetAxisCategory(xsc.XmlSwfChartType type)
private xsc.AxisCategory SetAxisCategory(xsc.XmlSwfChartType type)
{
xsc.AxisCategory ac = new xsc.AxisCategory(type);
ac.Size = 12;
ac.Color = "ffffff";
ac.Alpha = 75;
ac.Font = "Arial";
ac.Bold = true;
ac.Skip = 0;
ac.Orientation = "horizontal";
return ac;
}
#endregion
#region SetAxisTicks()
private xsc.AxisTicks SetAxisTicks()
{
xsc.AxisTicks at = new xsc.AxisTicks();
at.ValueTicks = false;
at.CategoryTicks = false;
return at;
}
#endregion
#region SetAxisValue()
private xsc.AxisValue SetAxisValue()
{
xsc.AxisValue av = new xsc.AxisValue();
av.Alpha = 0;
return av;
}
#endregion
#region SetChartBorder()
private xsc.ChartBorder SetChartBorder()
{
xsc.ChartBorder cb = new xsc.ChartBorder();
cb.TopThickness = 0;
cb.BottomThickness = 0;
cb.LeftThickness = 0;
cb.RightThickness = 0;
return cb;
}
#endregion
#region SetChartData()
private xsc.ChartData SetChartData()
{
xsc.ChartData cd = new xsc.ChartData();
cd.AddDataPoint("Region 1", "2005", 50);
cd.AddDataPoint("Region 1", "2006", 70);
cd.AddDataPoint("Region 1", "2007", 110);
cd.AddDataPoint("Region 2", "2005", 35);
cd.AddDataPoint("Region 2", "2006", 50);
cd.AddDataPoint("Region 2", "2007", 90);
return cd;
}
#endregion
#region SetChartGridH()
private xsc.ChartGrid SetChartGridH()
{
xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Horizontal);
cg.Thickness = 0;
return cg;
}
#endregion
#region SetChartRectangle()
private xsc.ChartRectangle SetChartRectangle()
{
xsc.ChartRectangle cr = new xsc.ChartRectangle();
cr.X = -25;
cr.Y = -10;
cr.Width = 425;
cr.Height = 245;
cr.PositiveAlpha = 0;
cr.NegativeAlpha = 25;
return cr;
}
#endregion
#region SetChartTransition()
private xsc.ChartTransition SetChartTransition()
{
xsc.ChartTransition ct = new xsc.ChartTransition();
ct.TransitionType = xsc.TransitionType.slide_down;
ct.Delay = 0;
ct.Duration = 1;
ct.Order = xsc.TransitionOrder.series;
return ct;
}
#endregion
#region SetChartValue()
private xsc.ChartValue SetChartValue()
{
xsc.ChartValue cv = new xsc.ChartValue();
cv.HideZero = true;
cv.Color = "000000";
cv.Alpha = 70;
cv.Size = 9;
cv.Position = "middle";
cv.Prefix = "";
cv.Suffix = "";
cv.Decimals = 0;
cv.Separator = "";
cv.AsPercentage = true;
return cv;
}
#endregion
#region CreateDrawImage()
private xsc.DrawImage CreateDrawImage()
{
xsc.DrawImage di = new xsc.DrawImage();
di.Transition = xsc.TransitionType.dissolve;
di.Delay = 1;
di.Duration = 0.6;
di.Url = "images/button.swf";
di.X = 300;
di.Y = 250;
di.Width = 70;
di.Height = 25;
return di;
}
#endregion
#region SetLegendLabel()
private xsc.LegendLabel SetLegendLabel()
{
xsc.LegendLabel ll = new xsc.LegendLabel();
ll.Size = 0;
ll.Alpha = 0;
return ll;
}
#endregion
#region SetLegendRectangle()
private xsc.LegendRectangle SetLegendRectangle()
{
xsc.LegendRectangle lr = new xsc.LegendRectangle();
lr.X = 0;
lr.Y = 300;
lr.Width = 0;
lr.Height = 0;
lr.Margin = 0;
lr.FillAlpha = 0;
lr.LineAlpha = 0;
lr.LineThickness = 0;
return lr;
}
#endregion
#region SetLinkAreas()
private List<xsc.LinkArea> SetLinkAreas()
{
List<xsc.LinkArea> list = new List<xsc.LinkArea>();
xsc.LinkArea la = new xsc.LinkArea();
la.X = 300;
la.Y = 250;
la.Width = 70;
la.Height = 25;
la.Target = "print";
list.Add(la);
return list;
}
#endregion
#region SetSeriesGap()
private xsc.SeriesGap SetSeriesGap()
{
xsc.SeriesGap sg = new xsc.SeriesGap();
sg.BarGap = 10;
sg.SetGap = 20;
return sg;
}
#endregion
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.