context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class MemberAccessTests { private class UnreadableIndexableClass { public int this[int index] { set { } } } [Fact] public static void CheckMemberAccessStructInstanceFieldTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(new FS() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessStructStaticFieldTest() { FS.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } finally { FS.SI = 0; } } [Fact] public static void CheckMemberAccessStructConstFieldTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "CI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessStructStaticReadOnlyFieldTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "RI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessStructInstancePropertyTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(new PS() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessStructStaticPropertyTest() { PS.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( null, typeof(PS), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } finally { PS.SI = 0; } } [Fact] public static void CheckMemberAccessClassInstanceFieldTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(new FC() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessClassStaticFieldTest() { FC.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } finally { FC.SI = 0; } } [Fact] public static void CheckMemberAccessClassConstFieldTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "CI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessClassStaticReadOnlyFieldTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "RI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessClassInstancePropertyTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(new PC() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } [Fact] public static void CheckMemberAccessClassStaticPropertyTest() { PC.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( null, typeof(PC), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Equal(42, f()); } finally { PC.SI = 0; } } [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")] public static void CheckMemberAccessClassInstanceFieldNullReferenceTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(null, typeof(FC)), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Throws<NullReferenceException>(() => f()); } [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")] public static void CheckMemberAccessClassInstanceFieldAssignNullReferenceTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Assign( Expression.Field( Expression.Constant(null, typeof(FC)), "II"), Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Throws<NullReferenceException>(() => f()); } [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")] public static void CheckMemberAccessClassInstancePropertyNullReferenceTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(null, typeof(PC)), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Throws<NullReferenceException>(() => f()); } [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")] public static void CheckMemberAccessClassInstanceIndexerNullReferenceTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(null, typeof(PC)), "Item", Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Throws<NullReferenceException>(() => f()); } [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")] public static void CheckMemberAccessClassInstanceIndexerAssignNullReferenceTest() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Assign( Expression.Property( Expression.Constant(null, typeof(PC)), "Item", Expression.Constant(1)), Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(); Assert.Throws<NullReferenceException>(() => f()); } [Fact] public static void AccessIndexedPropertyWithoutIndex() { Assert.Throws<ArgumentException>(() => Expression.Property(Expression.Default(typeof(List<int>)), typeof(List<int>).GetProperty("Item"))); } [Fact] public static void AccessIndexedPropertyWithoutIndexWriteOnly() { Assert.Throws<ArgumentException>(() => Expression.Property(Expression.Default(typeof(UnreadableIndexableClass)), typeof(UnreadableIndexableClass).GetProperty("Item"))); } } }
#region LICENSE /* Copyright 2014 - 2015 LeagueSharp AutoLevel.cs is part of EloBuddy.Common. EloBuddy.Common is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. EloBuddy.Common is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with EloBuddy.Common. If not, see <http://www.gnu.org/licenses/>. */ #endregion #region using System; using System.Collections.Generic; using System.Linq; using EloBuddy; #endregion namespace EloBuddy.Common { /// <summary> /// Automatically levels skills. /// </summary> public class AutoLevel { /// <summary> /// The order /// </summary> private static List<SpellSlot> order = new List<SpellSlot>(); /// <summary> /// The last leveled /// </summary> private static float LastLeveled; /// <summary> /// The next delay /// </summary> private static float NextDelay; /// <summary> /// The player /// </summary> private static readonly AIHeroClient Player = ObjectManager.Player; /// <summary> /// The random number /// </summary> private static Random RandomNumber; /// <summary> /// The enabled /// </summary> private static bool enabled; /// <summary> /// The initialize /// </summary> private static bool init; /// <summary> /// Initializes a new instance of the <see cref="AutoLevel"/> class. /// </summary> /// <param name="levels">The levels.</param> public AutoLevel(IEnumerable<int> levels) { UpdateSequence(levels); Init(); } /// <summary> /// Initializes a new instance of the <see cref="AutoLevel"/> class. /// </summary> /// <param name="levels">The levels.</param> public AutoLevel(List<SpellSlot> levels) { UpdateSequence(levels); Init(); } /// <summary> /// Initializes this instance. /// </summary> private static void Init() { if (init) { return; } init = true; RandomNumber = new Random(Utils.TickCount); Game.OnUpdate += Game_OnGameUpdate; } /// <summary> /// Fired when the game updates. /// </summary> /// <param name="args">The <see cref="EventArgs"/> instance containing the event data.</param> private static void Game_OnGameUpdate(EventArgs args) { if (!enabled || Player.SpellTrainingPoints < 1 || Utils.TickCount - LastLeveled < NextDelay) { return; } NextDelay = RandomNumber.Next(750); LastLeveled = Utils.TickCount; var spell = order[GetTotalPoints()]; Player.Spellbook.LevelSpell(spell); } /// <summary> /// Gets the total points. /// </summary> /// <returns></returns> private static int GetTotalPoints() { var spell = Player.Spellbook; var q = spell.GetSpell(SpellSlot.Q).Level; var w = spell.GetSpell(SpellSlot.W).Level; var e = spell.GetSpell(SpellSlot.E).Level; var r = spell.GetSpell(SpellSlot.R).Level; return q + w + e + r; } /// <summary> /// Enables this instance. /// </summary> public static void Enable() { enabled = true; } /// <summary> /// Disables this instance. /// </summary> public static void Disable() { enabled = false; } /// <summary> /// Sets if this instance is enabled or not according to the <paramref name="b"/>. /// </summary> /// <param name="b">if set to <c>true</c> [b].</param> public static void Enabled(bool b) { enabled = b; } /// <summary> /// Updates the sequence. /// </summary> /// <param name="levels">The levels.</param> public static void UpdateSequence(IEnumerable<int> levels) { Init(); order.Clear(); foreach (var level in levels) { order.Add((SpellSlot) level); } } /// <summary> /// Updates the sequence. /// </summary> /// <param name="levels">The levels.</param> public static void UpdateSequence(List<SpellSlot> levels) { Init(); order.Clear(); order = levels; } /// <summary> /// Gets the sequence. /// </summary> /// <returns></returns> public static int[] GetSequence() { return order.Select(spell => (int) spell).ToArray(); } /// <summary> /// Gets the sequence list. /// </summary> /// <returns></returns> public static List<SpellSlot> GetSequenceList() { return order; } } }
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using GSF.ASN1; using GSF.ASN1.Attributes; using GSF.ASN1.Coders; using GSF.ASN1.Types; namespace GSF.MMS.Model { [ASN1PreparedElement] [ASN1Sequence(Name = "GetEventConditionAttributes_Response", IsSet = false)] public class GetEventConditionAttributes_Response : IASN1PreparedElement { private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(GetEventConditionAttributes_Response)); private Identifier accessControlList_; private bool accessControlList_present; private bool alarmSummaryReports_; private EC_Class class__; private Unsigned32 evaluationInterval_; private bool evaluationInterval_present; private bool mmsDeletable_; private MonitoredVariableChoiceType monitoredVariable_; private bool monitoredVariable_present; private Priority priority_; private Unsigned8 severity_; [ASN1Boolean(Name = "")] [ASN1Element(Name = "mmsDeletable", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = true)] public bool MmsDeletable { get { return mmsDeletable_; } set { mmsDeletable_ = value; } } [ASN1Element(Name = "class", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public EC_Class Class_ { get { return class__; } set { class__ = value; } } [ASN1Element(Name = "priority", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = true)] public Priority Priority { get { return priority_; } set { priority_ = value; } } [ASN1Element(Name = "severity", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = true)] public Unsigned8 Severity { get { return severity_; } set { severity_ = value; } } [ASN1Boolean(Name = "")] [ASN1Element(Name = "alarmSummaryReports", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = true)] public bool AlarmSummaryReports { get { return alarmSummaryReports_; } set { alarmSummaryReports_ = value; } } [ASN1Element(Name = "monitoredVariable", IsOptional = true, HasTag = true, Tag = 6, HasDefaultValue = false)] public MonitoredVariableChoiceType MonitoredVariable { get { return monitoredVariable_; } set { monitoredVariable_ = value; monitoredVariable_present = true; } } [ASN1Element(Name = "evaluationInterval", IsOptional = true, HasTag = true, Tag = 7, HasDefaultValue = false)] public Unsigned32 EvaluationInterval { get { return evaluationInterval_; } set { evaluationInterval_ = value; evaluationInterval_present = true; } } [ASN1Element(Name = "accessControlList", IsOptional = true, HasTag = true, Tag = 8, HasDefaultValue = false)] public Identifier AccessControlList { get { return accessControlList_; } set { accessControlList_ = value; accessControlList_present = true; } } public void initWithDefaults() { bool param_MmsDeletable = false; MmsDeletable = param_MmsDeletable; Priority param_Priority = new Priority(64); Priority = param_Priority; Unsigned8 param_Severity = new Unsigned8(64); Severity = param_Severity; bool param_AlarmSummaryReports = false; AlarmSummaryReports = param_AlarmSummaryReports; } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isMonitoredVariablePresent() { return monitoredVariable_present; } public bool isEvaluationIntervalPresent() { return evaluationInterval_present; } public bool isAccessControlListPresent() { return accessControlList_present; } [ASN1PreparedElement] [ASN1Choice(Name = "monitoredVariable")] public class MonitoredVariableChoiceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(MonitoredVariableChoiceType)); private NullObject undefined_; private bool undefined_selected; private VariableSpecification variableReference_; private bool variableReference_selected; [ASN1Element(Name = "variableReference", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)] public VariableSpecification VariableReference { get { return variableReference_; } set { selectVariableReference(value); } } [ASN1Null(Name = "undefined")] [ASN1Element(Name = "undefined", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public NullObject Undefined { get { return undefined_; } set { selectUndefined(value); } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isVariableReferenceSelected() { return variableReference_selected; } public void selectVariableReference(VariableSpecification val) { variableReference_ = val; variableReference_selected = true; undefined_selected = false; } public bool isUndefinedSelected() { return undefined_selected; } public void selectUndefined() { selectUndefined(new NullObject()); } public void selectUndefined(NullObject val) { undefined_ = val; undefined_selected = true; variableReference_selected = false; } } } }
using Aurora.Devices; using Aurora.Devices.Razer; using Aurora.EffectsEngine; using Aurora.Profiles; using Aurora.Settings.Overrides; using Aurora.Utils; using Newtonsoft.Json; using RazerSdkWrapper; using RazerSdkWrapper.Data; using RazerSdkWrapper.Utils; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace Aurora.Settings.Layers { public class RazerLayerHandlerProperties : LayerHandlerProperties<RazerLayerHandlerProperties> { // Color Enhancing public bool? _ColorPostProcessEnabled { get; set; } [JsonIgnore] public bool ColorPostProcessEnabled => Logic._ColorPostProcessEnabled ?? _ColorPostProcessEnabled ?? false; public double? _BrightnessChange { get; set; } [JsonIgnore] public double BrightnessChange => Logic._BrightnessChange ?? _BrightnessChange ?? 0; public double? _SaturationChange { get; set; } [JsonIgnore] public double SaturationChange => Logic._SaturationChange ?? _SaturationChange ?? 0; public double? _HueShift { get; set; } [JsonIgnore] public double HueShift => Logic._HueShift ?? _HueShift ?? 0; public Dictionary<DeviceKeys, DeviceKeys> _KeyCloneMap { get; set; } [JsonIgnore] public Dictionary<DeviceKeys, DeviceKeys> KeyCloneMap => Logic._KeyCloneMap ?? _KeyCloneMap ?? new Dictionary<DeviceKeys, DeviceKeys>(); public RazerLayerHandlerProperties() : base() { } public RazerLayerHandlerProperties(bool arg = false) : base(arg) { } public override void Default() { base.Default(); _ColorPostProcessEnabled = false; _BrightnessChange = 0; _SaturationChange = 0; _HueShift = 0; _KeyCloneMap = new Dictionary<DeviceKeys, DeviceKeys>(); } } [LogicOverrideIgnoreProperty("_PrimaryColor")] [LogicOverrideIgnoreProperty("_Sequence")] [LayerHandlerMeta(Name = "Razer Chroma", IsDefault = true)] public class RazerLayerHandler : LayerHandler<RazerLayerHandlerProperties> { private Color[] _keyboardColors; private Color[] _mousepadColors; private Color _mouseColor; private string _currentAppExecutable; private int _currentAppPid; private bool _isDumping; public RazerLayerHandler() { _keyboardColors = new Color[22 * 6]; _mousepadColors = new Color[16]; if (Global.razerSdkManager != null) { Global.razerSdkManager.DataUpdated += OnDataUpdated; var appList = Global.razerSdkManager.GetDataProvider<RzAppListDataProvider>(); appList.Update(); _currentAppExecutable = appList.CurrentAppExecutable; _currentAppPid = appList.CurrentAppPid; } } protected override UserControl CreateControl() { return new Control_RazerLayer(this); } private void OnDataUpdated(object s, EventArgs e) { if (!(s is AbstractDataProvider provider)) return; provider.Update(); if (_isDumping) DumpData(provider); if (provider is RzKeyboardDataProvider keyboard) { for (var i = 0; i < keyboard.Grids[0].Height * keyboard.Grids[0].Width; i++) _keyboardColors[i] = keyboard.GetZoneColor(i); } else if (provider is RzMouseDataProvider mouse) { _mouseColor = mouse.GetZoneColor(55); } else if (provider is RzMousepadDataProvider mousePad) { for (var i = 0; i < mousePad.Grids[0].Height * mousePad.Grids[0].Width; i++) _mousepadColors[i] = mousePad.GetZoneColor(i); } else if (provider is RzAppListDataProvider appList) { _currentAppExecutable = appList.CurrentAppExecutable; _currentAppPid = appList.CurrentAppPid; } } public bool StartDumpingData() { var root = Global.LogsDirectory; if (!Directory.Exists(root)) return false; var path = $@"{root}\RazerLayer"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); foreach (var file in Directory.EnumerateFiles(path, "*.bin", SearchOption.TopDirectoryOnly)) File.Delete(file); Global.logger.Info("RazerLayerHandler started dumping data"); _isDumping = true; return true; } public void StopDumpingData() { Global.logger.Info("RazerLayerHandler stopped dumping data"); _isDumping = false; } public void DumpData(AbstractDataProvider provider) { var path = Path.Combine(Global.LogsDirectory, "RazerLayer"); var filename = $"{provider.GetType().Name}_{Environment.TickCount}.bin"; using (var file = File.Open($@"{path}\{filename}", FileMode.Create)) { var data = provider.Read(); file.Write(data, 0, data.Length); } } public override EffectLayer Render(IGameState gamestate) { var layer = new EffectLayer(); if (!IsCurrentAppValid()) return layer; foreach (var key in (DeviceKeys[])Enum.GetValues(typeof(DeviceKeys))) { if (!TryGetColor(key, out Color color)) continue; layer.Set(key, color); } if (Properties.KeyCloneMap != null) foreach (var target in Properties.KeyCloneMap) if(TryGetColor(target.Value, out var clr)) layer.Set(target.Key, clr); return layer; } private bool TryGetColor(DeviceKeys key, out Color color) { color = Color.Transparent; if (RazerLayoutMap.GenericKeyboard.TryGetValue(key, out var position)) color = _keyboardColors[position[1] + position[0] * 22]; else if (key >= DeviceKeys.MOUSEPADLIGHT1 && key <= DeviceKeys.MOUSEPADLIGHT15) color = _mousepadColors[DeviceKeys.MOUSEPADLIGHT15 - key]; else if (key == DeviceKeys.Peripheral) color = _mouseColor; else return false; if (Properties.ColorPostProcessEnabled) color = PostProcessColor(color); return true; } private bool IsCurrentAppValid() => !string.IsNullOrEmpty(_currentAppExecutable) && string.Compare(_currentAppExecutable, "Aurora.exe", true) != 0; private Color PostProcessColor(Color color) { if (color.R == 0 && color.G == 0 && color.B == 0) return color; if (Properties.BrightnessChange != 0) color = ColorUtils.ChangeBrightness(color, Properties.BrightnessChange); if (Properties.SaturationChange != 0) color = ColorUtils.ChangeSaturation(color, Properties.SaturationChange); if (Properties.HueShift != 0) color = ColorUtils.ChangeHue(color, Properties.HueShift); return color; } public override void Dispose() { if(Global.razerSdkManager != null) Global.razerSdkManager.DataUpdated -= OnDataUpdated; base.Dispose(); } } }
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using erl.Oracle.TnsNames.Antlr4.Runtime; using erl.Oracle.TnsNames.Antlr4.Runtime.Atn; using erl.Oracle.TnsNames.Antlr4.Runtime.Dfa; using erl.Oracle.TnsNames.Antlr4.Runtime.Misc; using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen; namespace erl.Oracle.TnsNames.Antlr4.Runtime.Atn { public class ATN { public const int INVALID_ALT_NUMBER = 0; [NotNull] public readonly IList<ATNState> states = new List<ATNState>(); /// <summary> /// Each subrule/rule is a decision point and we must track them so we /// can go back later and build DFA predictors for them. /// </summary> /// <remarks> /// Each subrule/rule is a decision point and we must track them so we /// can go back later and build DFA predictors for them. This includes /// all the rules, subrules, optional blocks, ()+, ()* etc... /// </remarks> [NotNull] public readonly IList<DecisionState> decisionToState = new List<DecisionState>(); /// <summary>Maps from rule index to starting state number.</summary> /// <remarks>Maps from rule index to starting state number.</remarks> public RuleStartState[] ruleToStartState; /// <summary>Maps from rule index to stop state number.</summary> /// <remarks>Maps from rule index to stop state number.</remarks> public RuleStopState[] ruleToStopState; [NotNull] public readonly IDictionary<string, TokensStartState> modeNameToStartState = new Dictionary<string, TokensStartState>(); /// <summary>The type of the ATN.</summary> /// <remarks>The type of the ATN.</remarks> public readonly ATNType grammarType; /// <summary>The maximum value for any symbol recognized by a transition in the ATN.</summary> /// <remarks>The maximum value for any symbol recognized by a transition in the ATN.</remarks> public readonly int maxTokenType; /// <summary>For lexer ATNs, this maps the rule index to the resulting token type.</summary> /// <remarks> /// For lexer ATNs, this maps the rule index to the resulting token type. /// For parser ATNs, this maps the rule index to the generated bypass token /// type if the /// <see cref="ATNDeserializationOptions.GenerateRuleBypassTransitions()"/> /// deserialization option was specified; otherwise, this is /// <see langword="null"/> /// . /// </remarks> public int[] ruleToTokenType; /// <summary> /// For lexer ATNs, this is an array of /// <see cref="ILexerAction"/> /// objects which may /// be referenced by action transitions in the ATN. /// </summary> public ILexerAction[] lexerActions; [NotNull] public readonly IList<TokensStartState> modeToStartState = new List<TokensStartState>(); private readonly PredictionContextCache contextCache = new PredictionContextCache(); [NotNull] public DFA[] decisionToDFA = new DFA[0]; [NotNull] public DFA[] modeToDFA = new DFA[0]; protected internal readonly ConcurrentDictionary<int, int> LL1Table = new ConcurrentDictionary<int, int>(); /// <summary>Used for runtime deserialization of ATNs from strings</summary> public ATN(ATNType grammarType, int maxTokenType) { this.grammarType = grammarType; this.maxTokenType = maxTokenType; } public virtual PredictionContext GetCachedContext(PredictionContext context) { return PredictionContext.GetCachedContext(context, contextCache, new PredictionContext.IdentityHashMap()); } /// <summary> /// Compute the set of valid tokens that can occur starting in state /// <paramref name="s"/> /// . /// If /// <paramref name="ctx"/> /// is /// <see cref="PredictionContext.EMPTY"/> /// , the set of tokens will not include what can follow /// the rule surrounding /// <paramref name="s"/> /// . In other words, the set will be /// restricted to tokens reachable staying within /// <paramref name="s"/> /// 's rule. /// </summary> [return: NotNull] public virtual IntervalSet NextTokens(ATNState s, RuleContext ctx) { LL1Analyzer anal = new LL1Analyzer(this); IntervalSet next = anal.Look(s, ctx); return next; } /// <summary> /// Compute the set of valid tokens that can occur starting in /// <paramref name="s"/> /// and /// staying in same rule. /// <see cref="TokenConstants.EPSILON"/> /// is in set if we reach end of /// rule. /// </summary> [return: NotNull] public virtual IntervalSet NextTokens(ATNState s) { if (s.nextTokenWithinRule != null) { return s.nextTokenWithinRule; } s.nextTokenWithinRule = NextTokens(s, null); s.nextTokenWithinRule.SetReadonly(true); return s.nextTokenWithinRule; } public virtual void AddState(ATNState state) { if (state != null) { state.atn = this; state.stateNumber = states.Count; } states.Add(state); } public virtual void RemoveState(ATNState state) { states[state.stateNumber] = null; } // just free mem, don't shift states in list public virtual void DefineMode(string name, TokensStartState s) { modeNameToStartState[name] = s; modeToStartState.Add(s); modeToDFA = Arrays.CopyOf(modeToDFA, modeToStartState.Count); modeToDFA[modeToDFA.Length - 1] = new DFA(s); DefineDecisionState(s); } public virtual int DefineDecisionState(DecisionState s) { decisionToState.Add(s); s.decision = decisionToState.Count - 1; decisionToDFA = Arrays.CopyOf(decisionToDFA, decisionToState.Count); decisionToDFA[decisionToDFA.Length - 1] = new DFA(s, s.decision); return s.decision; } public virtual DecisionState GetDecisionState(int decision) { if (decisionToState.Count != 0) { return decisionToState[decision]; } return null; } public virtual int NumberOfDecisions { get { return decisionToState.Count; } } /// <summary> /// Computes the set of input symbols which could follow ATN state number /// <paramref name="stateNumber"/> /// in the specified full /// <paramref name="context"/> /// . This method /// considers the complete parser context, but does not evaluate semantic /// predicates (i.e. all predicates encountered during the calculation are /// assumed true). If a path in the ATN exists from the starting state to the /// <see cref="RuleStopState"/> /// of the outermost context without matching any /// symbols, /// <see cref="TokenConstants.EOF"/> /// is added to the returned set. /// <p>If /// <paramref name="context"/> /// is /// <see langword="null"/> /// , it is treated as /// <see cref="ParserRuleContext.EmptyContext"/> /// .</p> /// </summary> /// <param name="stateNumber">the ATN state number</param> /// <param name="context">the full parse context</param> /// <returns> /// The set of potentially valid input symbols which could follow the /// specified state in the specified context. /// </returns> /// <exception cref="System.ArgumentException"> /// if the ATN does not contain a state with /// number /// <paramref name="stateNumber"/> /// </exception> [return: NotNull] public virtual IntervalSet GetExpectedTokens(int stateNumber, RuleContext context) { if (stateNumber < 0 || stateNumber >= states.Count) { throw new ArgumentException("Invalid state number."); } RuleContext ctx = context; ATNState s = states[stateNumber]; IntervalSet following = NextTokens(s); if (!following.Contains(TokenConstants.EPSILON)) { return following; } IntervalSet expected = new IntervalSet(); expected.AddAll(following); expected.Remove(TokenConstants.EPSILON); while (ctx != null && ctx.invokingState >= 0 && following.Contains(TokenConstants.EPSILON)) { ATNState invokingState = states[ctx.invokingState]; RuleTransition rt = (RuleTransition)invokingState.Transition(0); following = NextTokens(rt.followState); expected.AddAll(following); expected.Remove(TokenConstants.EPSILON); ctx = ctx.Parent; } if (following.Contains(TokenConstants.EPSILON)) { expected.Add(TokenConstants.EOF); } return expected; } } }
/* * 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 Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Documents; using IndexOutput = Lucene.Net.Store.IndexOutput; using UnicodeUtil = Lucene.Net.Util.UnicodeUtil; namespace Lucene.Net.Index { sealed class TermVectorsTermsWriterPerField:TermsHashConsumerPerField { internal TermVectorsTermsWriterPerThread perThread; internal TermsHashPerField termsHashPerField; internal TermVectorsTermsWriter termsWriter; internal FieldInfo fieldInfo; internal DocumentsWriter.DocState docState; internal FieldInvertState fieldState; internal bool doVectors; internal bool doVectorPositions; internal bool doVectorOffsets; internal int maxNumPostings; internal IOffsetAttribute offsetAttribute = null; public TermVectorsTermsWriterPerField(TermsHashPerField termsHashPerField, TermVectorsTermsWriterPerThread perThread, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.perThread = perThread; this.termsWriter = perThread.termsWriter; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; } internal override int GetStreamCount() { return 2; } internal override bool Start(IFieldable[] fields, int count) { doVectors = false; doVectorPositions = false; doVectorOffsets = false; for (int i = 0; i < count; i++) { IFieldable field = fields[i]; if (field.IsIndexed && field.IsTermVectorStored) { doVectors = true; doVectorPositions |= field.IsStorePositionWithTermVector; doVectorOffsets |= field.IsStoreOffsetWithTermVector; } } if (doVectors) { if (perThread.doc == null) { perThread.doc = termsWriter.GetPerDoc(); perThread.doc.docID = docState.docID; System.Diagnostics.Debug.Assert(perThread.doc.numVectorFields == 0); System.Diagnostics.Debug.Assert(0 == perThread.doc.perDocTvf.Length); System.Diagnostics.Debug.Assert(0 == perThread.doc.perDocTvf.FilePointer); } System.Diagnostics.Debug.Assert(perThread.doc.docID == docState.docID); if (termsHashPerField.numPostings != 0) { // Only necessary if previous doc hit a // non-aborting exception while writing vectors in // this field: termsHashPerField.Reset(); perThread.termsHashPerThread.Reset(false); } } // TODO: only if needed for performance //perThread.postingsCount = 0; return doVectors; } public void Abort() { } /// <summary>Called once per field per document if term vectors /// are enabled, to write the vectors to /// RAMOutputStream, which is then quickly flushed to /// the real term vectors files in the Directory. /// </summary> internal override void Finish() { System.Diagnostics.Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.finish start")); int numPostings = termsHashPerField.numPostings; System.Diagnostics.Debug.Assert(numPostings >= 0); if (!doVectors || numPostings == 0) return ; if (numPostings > maxNumPostings) maxNumPostings = numPostings; IndexOutput tvf = perThread.doc.perDocTvf; // This is called once, after inverting all occurences // of a given field in the doc. At this point we flush // our hash into the DocWriter. System.Diagnostics.Debug.Assert(fieldInfo.storeTermVector); System.Diagnostics.Debug.Assert(perThread.VectorFieldsInOrder(fieldInfo)); perThread.doc.AddField(termsHashPerField.fieldInfo.number); RawPostingList[] postings = termsHashPerField.SortPostings(); tvf.WriteVInt(numPostings); byte bits = (byte) (0x0); if (doVectorPositions) bits |= TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR; if (doVectorOffsets) bits |= TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR; tvf.WriteByte(bits); int encoderUpto = 0; int lastTermBytesCount = 0; ByteSliceReader reader = perThread.vectorSliceReader; char[][] charBuffers = perThread.termsHashPerThread.charPool.buffers; for (int j = 0; j < numPostings; j++) { TermVectorsTermsWriter.PostingList posting = (TermVectorsTermsWriter.PostingList) postings[j]; int freq = posting.freq; char[] text2 = charBuffers[posting.textStart >> DocumentsWriter.CHAR_BLOCK_SHIFT]; int start2 = posting.textStart & DocumentsWriter.CHAR_BLOCK_MASK; // We swap between two encoders to save copying // last Term's byte array UnicodeUtil.UTF8Result utf8Result = perThread.utf8Results[encoderUpto]; // TODO: we could do this incrementally UnicodeUtil.UTF16toUTF8(text2, start2, utf8Result); int termBytesCount = utf8Result.length; // TODO: UTF16toUTF8 could tell us this prefix // Compute common prefix between last term and // this term int prefix = 0; if (j > 0) { byte[] lastTermBytes = perThread.utf8Results[1 - encoderUpto].result; byte[] termBytes = perThread.utf8Results[encoderUpto].result; while (prefix < lastTermBytesCount && prefix < termBytesCount) { if (lastTermBytes[prefix] != termBytes[prefix]) break; prefix++; } } encoderUpto = 1 - encoderUpto; lastTermBytesCount = termBytesCount; int suffix = termBytesCount - prefix; tvf.WriteVInt(prefix); tvf.WriteVInt(suffix); tvf.WriteBytes(utf8Result.result, prefix, suffix); tvf.WriteVInt(freq); if (doVectorPositions) { termsHashPerField.InitReader(reader, posting, 0); reader.WriteTo(tvf); } if (doVectorOffsets) { termsHashPerField.InitReader(reader, posting, 1); reader.WriteTo(tvf); } } termsHashPerField.Reset(); // NOTE: we clear, per-field, at the thread level, // because term vectors fully write themselves on each // field; this saves RAM (eg if large doc has two large // fields w/ term vectors on) because we recycle/reuse // all RAM after each field: perThread.termsHashPerThread.Reset(false); } internal void ShrinkHash() { termsHashPerField.ShrinkHash(maxNumPostings); maxNumPostings = 0; } internal override void Start(IFieldable f) { if (doVectorOffsets) { offsetAttribute = fieldState.attributeSource.AddAttribute<IOffsetAttribute>(); } else { offsetAttribute = null; } } internal override void NewTerm(RawPostingList p0) { System.Diagnostics.Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.newTerm start")); TermVectorsTermsWriter.PostingList p = (TermVectorsTermsWriter.PostingList) p0; p.freq = 1; if (doVectorOffsets) { int startOffset = fieldState.offset + offsetAttribute.StartOffset; ; int endOffset = fieldState.offset + offsetAttribute.EndOffset; termsHashPerField.WriteVInt(1, startOffset); termsHashPerField.WriteVInt(1, endOffset - startOffset); p.lastOffset = endOffset; } if (doVectorPositions) { termsHashPerField.WriteVInt(0, fieldState.position); p.lastPosition = fieldState.position; } } internal override void AddTerm(RawPostingList p0) { System.Diagnostics.Debug.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.addTerm start")); TermVectorsTermsWriter.PostingList p = (TermVectorsTermsWriter.PostingList) p0; p.freq++; if (doVectorOffsets) { int startOffset = fieldState.offset + offsetAttribute.StartOffset; ; int endOffset = fieldState.offset + offsetAttribute.EndOffset; termsHashPerField.WriteVInt(1, startOffset - p.lastOffset); termsHashPerField.WriteVInt(1, endOffset - startOffset); p.lastOffset = endOffset; } if (doVectorPositions) { termsHashPerField.WriteVInt(0, fieldState.position - p.lastPosition); p.lastPosition = fieldState.position; } } internal override void SkippingLongTerm() { } } }
using Moq; using NUnit.Framework; using PopForums.Configuration; using PopForums.Services; namespace PopForums.Test.Services { [TestFixture] public class TextParsingServiceCleanForumCodeTests { private TextParsingService GetService() { _mockSettingsManager = new Mock<ISettingsManager>(); _settings = new Settings(); _mockSettingsManager.Setup(s => s.Current).Returns(_settings); return new TextParsingService(_mockSettingsManager.Object); } private Mock<ISettingsManager> _mockSettingsManager; private Settings _settings; [Test] public void FilterDupeLineBreaks() { var service = GetService(); var result = service.CleanForumCode("ahoihfohfo\r\noishfoihg\r\n\r\n\r\nehufhffh \r\n\r\n\r\n\r\nbbb"); Assert.AreEqual("ahoihfohfo\r\noishfoihg\r\n\r\nehufhffh \r\n\r\nbbb", result); } [Test] public void LeaveNormalLineBreaks() { var service = GetService(); var result = service.CleanForumCode("first\r\n\r\nsecond"); Assert.AreEqual("first\r\n\r\nsecond", result); } [Test] public void ConvertLonelyCarriageReturn() { var service = GetService(); var result = service.CleanForumCode("first\nsecond\r\nthird"); Assert.AreEqual("first\r\nsecond\r\nthird", result); } [Test] public void RemoveImageTagIfImagesDisallowed() { var service = GetService(); _settings.AllowImages = false; var result = service.CleanForumCode("fff[i]blah[/i] f f8whef 98wy 8wyef [image=blah.jpg]asfd affs[i]blah[/i]"); Assert.AreEqual("fff[i]blah[/i] f f8whef 98wy 8wyef asfd affs[i]blah[/i]", result); } [Test] public void AllowWellFormedImageTag() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("fff[i]blah[/i] f f8whef [image=\"blah.jpg\"] 98wy 8wyef [image=blah.jpg]asfd affs[i]blah[/i]"); Assert.AreEqual("fff[i]blah[/i] f f8whef [image=\"blah.jpg\"] 98wy 8wyef [image=blah.jpg]asfd affs[i]blah[/i]", result); } [Test] public void RemoveMalFormedImageTag() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("fff[i]blah[/i] f f8whef [image \"blah.jpg\"] 98wy 8wyef [image=blah.jpg]asfd [image=\"blah.jpg\"]affs[i]blah[/i]"); Assert.AreEqual("fff[i]blah[/i] f f8whef 98wy 8wyef [image=blah.jpg]asfd [image=\"blah.jpg\"]affs[i]blah[/i]", result); } [Test] public void CloseUnclosedTag() { var service = GetService(); var result = service.CleanForumCode("eorifj e oeihf eorhf [b]eoeirf eriojf"); Assert.AreEqual("eorifj e oeihf eorhf [b]eoeirf eriojf[/b]", result); } [Test] public void CloseMultipleUnclosedTags() { var service = GetService(); var result = service.CleanForumCode("eo[ul]rifj [i]e[/i] oeihf eorhf [b]eoeirf [i]eriojf"); Assert.AreEqual("eo[ul]rifj [i]e[/i] oeihf eorhf [b]eoeirf [i]eriojf[/i][/b][/ul]", result); } [Test] public void CleanUpOverlappingTags() { var service = GetService(); var result = service.CleanForumCode("eo[ul]rifj [i]e[/ul]asdfg[/i] oeihf eorhf [b]eoeirf [i]eriojf[/i][/b]"); Assert.AreEqual("eo[ul]rifj [i]e[/i][/ul][i]asdfg[/i] oeihf eorhf [b]eoeirf [i]eriojf[/i][/b]", result); } [Test] public void CleanUpOverlappingTags2() { var service = GetService(); var result = service.CleanForumCode("now is [i]the time to [b]write good[/i] tests [li]and make[/b] sure that [b][i]everything[/li] is awesome[/i][/b] and stuff"); Assert.AreEqual("now is [i]the time to [b]write good[/b][/i][b] tests [li]and make[/li][/b][li] sure that [b][i]everything[/i][/b][/li][b][i] is awesome[/i][/b] and stuff", result); } [Test] public void ClosingTagWithoutOpener() { var service = GetService(); var result = service.CleanForumCode("ohf whfwofhw h whfweohf[b]oihfowihfwf[/b] ihfwhf [/i]"); Assert.AreEqual("[i]ohf whfwofhw h whfweohf[b]oihfowihfwf[/b] ihfwhf [/i]", result); } [Test] public void ClosingTagWithoutOpener2() { var service = GetService(); var result = service.CleanForumCode("ohf whfwofhw h whfweohf[b]oihfowihfwf[/b] ihfwhf [/i][/li]"); Assert.AreEqual("[li][i]ohf whfwofhw h whfweohf[b]oihfowihfwf[/b] ihfwhf [/i][/li]", result); } [Test] public void UrlTagOk() { var service = GetService(); var result = service.CleanForumCode("ohf whfwofhw h whfweohf[url=\"http://popw.com/\"]oihfo[b]wihfwf[/url] ihfwhf[/b]"); Assert.AreEqual("ohf whfwofhw h whfweohf[url=\"http://popw.com/\"]oihfo[b]wihfwf[/b][/url][b] ihfwhf[/b]", result); } [Test] public void IgnoreInvalidTag() { var service = GetService(); var result = service.CleanForumCode("ohf i oih hgoehi[bad]gaeiorw iowh owahfaowhfwohf"); Assert.AreEqual("ohf i oih hgoehi[bad]gaeiorw iowh owahfaowhfwohf", result); } [Test] public void TagUrlWithProtocol() { var service = GetService(); var result = service.CleanForumCode("ohf i oih hgoehi http://popw.com/ owahfaowhfwohf"); Assert.AreEqual("ohf i oih hgoehi [url=http://popw.com/]http://popw.com/[/url] owahfaowhfwohf", result); } [Test] public void TagLongUrlWithProtocol() { var service = GetService(); var result = service.CleanForumCode("ohf i oih hgoehi http://popw.com/1234567890123456789012345678901234567890123456789012345678901234567890 owahfaowhfwohf"); Assert.AreEqual("ohf i oih hgoehi [url=http://popw.com/1234567890123456789012345678901234567890123456789012345678901234567890]http://popw.com/123456789012345678901234567890123456789012345678901...1234567890[/url] owahfaowhfwohf", result); } [Test] public void TagWwwUrl() { var service = GetService(); var result = service.CleanForumCode("ohf i oih hgoehi www.popw.com owahfaowhfwohf"); Assert.AreEqual("ohf i oih hgoehi [url=http://www.popw.com]www.popw.com[/url] owahfaowhfwohf", result); } [Test] public void TagLongWwwUrl() { var service = GetService(); var result = service.CleanForumCode("ohf i oih hgoehi www.popw.com/1234567890123456789012345678901234567890123456789012345678901234567890 owahfaowhfwohf"); Assert.AreEqual("ohf i oih hgoehi [url=http://www.popw.com/1234567890123456789012345678901234567890123456789012345678901234567890]www.popw.com/123456789012345678901234567890123456789012345678901234...1234567890[/url] owahfaowhfwohf", result); } [Test] public void TagEmailUrl() { var service = GetService(); var result = service.CleanForumCode("ohf i oih hgoehi jeff@popw.com owahfaowhfwohf"); Assert.AreEqual("ohf i oih hgoehi [url=mailto:jeff@popw.com]jeff@popw.com[/url] owahfaowhfwohf", result); } [Test] public void EscapeHtml() { var service = GetService(); var result = service.CleanForumCode("ohf i oih hgoehi <a href=\"javascript:alert('blah')\">indeed</a> owahfaowhfwohf"); Assert.AreEqual("ohf i oih hgoehi &lt;a href=\"javascript:alert('blah')\"&gt;indeed&lt;/a&gt; owahfaowhfwohf", result); } [Test] public void DontCreateUrlOpenForOrphanCloser() { var service = GetService(); var result = service.CleanForumCode("test [b]test[/url] test[/b]"); Assert.AreEqual("test [b]test test[/b]", result); } [Test] public void DoubleHttpArchiveUrl() { var service = GetService(); var result = service.CleanForumCode("blah http://web.archive.org/web/20001002225219/http://coasterbuzz.com/forums/ blah"); Assert.AreEqual("blah [url=http://web.archive.org/web/20001002225219/http://coasterbuzz.com/forums/]http://web.archive.org/web/20001002225219/http://coasterbuzz.com/forums/[/url] blah", result); } [Test] public void YouTubeHttpOnYouTubeDomain() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("blah http://youtube.com/watch?v=12345 blah"); Assert.AreEqual(result, "blah [youtube=http://youtube.com/watch?v=12345] blah"); } [Test] public void YouTubeHttpOnWwwYouTubeDomain() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("blah http://www.youtube.com/watch?v=12345 blah"); Assert.AreEqual(result, "blah [youtube=http://www.youtube.com/watch?v=12345] blah"); } [Test] public void YouTubeHttpsOnYouTubeDomain() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("blah https://youtube.com/watch?v=12345 blah"); Assert.AreEqual(result, "blah [youtube=https://youtube.com/watch?v=12345] blah"); } [Test] public void YouTubeHttpsOnWwwYouTubeDomain() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("blah https://www.youtube.com/watch?v=12345 blah"); Assert.AreEqual(result, "blah [youtube=https://www.youtube.com/watch?v=12345] blah"); } [Test] public void YouTubeHttpOnShortYouTubeDomain() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("blah http://youtu.be/12345 blah"); Assert.AreEqual(result, "blah [youtube=http://youtu.be/12345] blah"); } [Test] public void YouTubeHttpsOnShortYouTubeDomain() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("blah https://youtu.be/12345 blah"); Assert.AreEqual(result, "blah [youtube=https://youtu.be/12345] blah"); } [Test] public void YouTubeLinkParsedToLinkWithImagesOff() { var service = GetService(); _settings.AllowImages = false; var result = service.CleanForumCode("blah https://youtu.be/12345 blah"); Assert.AreEqual(result, "blah [url=https://youtu.be/12345]https://youtu.be/12345[/url] blah"); } [Test] public void YouTubeLinkInUrlTagNotParsed() { var service = GetService(); _settings.AllowImages = true; var result = service.CleanForumCode("blah [url=https://youtu.be/12345]test[/url] blah"); Assert.AreEqual(result, "blah [url=https://youtu.be/12345]test[/url] blah"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MusicPickerService.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Collections.Immutable; using System.Composition; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA1033: Interface methods should be callable by child types /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] public sealed class InterfaceMethodsShouldBeCallableByChildTypesFixer : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(InterfaceMethodsShouldBeCallableByChildTypesAnalyzer.RuleId); public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); SyntaxNode nodeToFix = root.FindNode(context.Span); if (nodeToFix == null) { return; } if (!(semanticModel.GetDeclaredSymbol(nodeToFix, context.CancellationToken) is IMethodSymbol methodSymbol)) { return; } SyntaxGenerator generator = SyntaxGenerator.GetGenerator(context.Document); SyntaxNode declaration = generator.GetDeclaration(nodeToFix); if (declaration == null) { return; } IMethodSymbol? candidateToIncreaseVisibility = GetExistingNonVisibleAlternate(methodSymbol); if (candidateToIncreaseVisibility != null) { ISymbol symbolToChange; bool checkSetter = false; if (candidateToIncreaseVisibility.IsAccessorMethod()) { symbolToChange = candidateToIncreaseVisibility.AssociatedSymbol; if (methodSymbol.AssociatedSymbol.Kind == SymbolKind.Property) { var originalProperty = (IPropertySymbol)methodSymbol.AssociatedSymbol; checkSetter = originalProperty.SetMethod != null; } } else { symbolToChange = candidateToIncreaseVisibility; } if (symbolToChange != null) { string title = string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix1, symbolToChange.Name); context.RegisterCodeFix(new MyCodeAction(title, async ct => await MakeProtected(context.Document, symbolToChange, checkSetter, ct).ConfigureAwait(false), equivalenceKey: MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix1), context.Diagnostics); } } else { ISymbol symbolToChange = methodSymbol.IsAccessorMethod() ? methodSymbol.AssociatedSymbol : methodSymbol; if (symbolToChange != null) { string title = string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix2, symbolToChange.Name); context.RegisterCodeFix(new MyCodeAction(title, async ct => await ChangeToPublicInterfaceImplementation(context.Document, symbolToChange, ct).ConfigureAwait(false), equivalenceKey: MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix2), context.Diagnostics); } } context.RegisterCodeFix(new MyCodeAction(string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix3, methodSymbol.ContainingType.Name), async ct => await MakeContainingTypeSealed(context.Document, methodSymbol, ct).ConfigureAwait(false), equivalenceKey: MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix3), context.Diagnostics); } private static IMethodSymbol? GetExistingNonVisibleAlternate(IMethodSymbol methodSymbol) { foreach (IMethodSymbol interfaceMethod in methodSymbol.ExplicitInterfaceImplementations) { foreach (INamedTypeSymbol type in methodSymbol.ContainingType.GetBaseTypesAndThis()) { IMethodSymbol candidate = type.GetMembers(interfaceMethod.Name).OfType<IMethodSymbol>().FirstOrDefault(m => !m.Equals(methodSymbol)); if (candidate != null) { return candidate; } } } return null; } private static async Task<Document> MakeProtected(Document document, ISymbol symbolToChange, bool checkSetter, CancellationToken cancellationToken) { SymbolEditor editor = SymbolEditor.Create(document); ISymbol? getter = null; ISymbol? setter = null; if (symbolToChange.Kind == SymbolKind.Property) { var propertySymbol = (IPropertySymbol)symbolToChange; getter = propertySymbol.GetMethod; setter = propertySymbol.SetMethod; } await editor.EditAllDeclarationsAsync(symbolToChange, (docEditor, declaration) => { docEditor.SetAccessibility(declaration, Accessibility.Protected); }, cancellationToken).ConfigureAwait(false); if (getter != null && getter.DeclaredAccessibility == Accessibility.Private) { await editor.EditAllDeclarationsAsync(getter, (docEditor, declaration) => { docEditor.SetAccessibility(declaration, Accessibility.NotApplicable); }, cancellationToken).ConfigureAwait(false); } if (checkSetter && setter != null && setter.DeclaredAccessibility == Accessibility.Private) { await editor.EditAllDeclarationsAsync(setter, (docEditor, declaration) => { docEditor.SetAccessibility(declaration, Accessibility.NotApplicable); }, cancellationToken).ConfigureAwait(false); } return editor.GetChangedDocuments().First(); } private static async Task<Document> ChangeToPublicInterfaceImplementation(Document document, ISymbol symbolToChange, CancellationToken cancellationToken) { SymbolEditor editor = SymbolEditor.Create(document); IEnumerable<ISymbol>? explicitImplementations = GetExplicitImplementations(symbolToChange); if (explicitImplementations == null) { return document; } await editor.EditAllDeclarationsAsync(symbolToChange, (docEditor, declaration) => { SyntaxNode newDeclaration = declaration; foreach (ISymbol implementedMember in explicitImplementations) { SyntaxNode interfaceTypeNode = docEditor.Generator.TypeExpression(implementedMember.ContainingType); newDeclaration = docEditor.Generator.AsPublicInterfaceImplementation(newDeclaration, interfaceTypeNode); } docEditor.ReplaceNode(declaration, newDeclaration); }, cancellationToken).ConfigureAwait(false); return editor.GetChangedDocuments().First(); } private static IEnumerable<ISymbol>? GetExplicitImplementations(ISymbol? symbol) { if (symbol == null) { return null; } return symbol.Kind switch { SymbolKind.Method => ((IMethodSymbol)symbol).ExplicitInterfaceImplementations, SymbolKind.Event => ((IEventSymbol)symbol).ExplicitInterfaceImplementations, SymbolKind.Property => ((IPropertySymbol)symbol).ExplicitInterfaceImplementations, _ => null, }; } private static async Task<Document> MakeContainingTypeSealed(Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken) { SymbolEditor editor = SymbolEditor.Create(document); await editor.EditAllDeclarationsAsync(methodSymbol.ContainingType, (docEditor, declaration) => { DeclarationModifiers modifiers = docEditor.Generator.GetModifiers(declaration); docEditor.SetModifiers(declaration, modifiers + DeclarationModifiers.Sealed); }, cancellationToken).ConfigureAwait(false); return editor.GetChangedDocuments().First(); } private class MyCodeAction : DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
#region Licence... /* The MIT License (MIT) Copyright (c) 2015 Oleg Shilo 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 Licence... using Microsoft.Deployment.WindowsInstaller; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml.Linq; using WixSharp.Bootstrapper; using IO = System.IO; namespace WixSharp { //This code requires heavy optimization and refactoring. Toady it serves the purpose of refining the API. public partial class Compiler { /// <summary> /// Builds WiX Bootstrapper application from the specified <see cref="Bundle"/> project instance. /// </summary> /// <param name="project">The project.</param> /// <param name="path">The path.</param> /// <exception cref="System.ApplicationException">Wix compiler/linker cannot be found</exception> public static string Build(Bundle project, string path) { if (Compiler.ClientAssembly.IsEmpty()) Compiler.ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().Location; string oldCurrDir = Environment.CurrentDirectory; try { //System.Diagnostics.Debug.Assert(false); Compiler.TempFiles.Clear(); string compiler = Utils.PathCombine(WixLocation, "candle.exe"); string linker = Utils.PathCombine(WixLocation, "light.exe"); if (!IO.File.Exists(compiler) || !IO.File.Exists(linker)) { Console.WriteLine("Wix binaries cannot be found. Expected location is " + IO.Path.GetDirectoryName(compiler)); throw new ApplicationException("Wix compiler/linker cannot be found"); } else { string wxsFile = BuildWxs(project); if (!project.SourceBaseDir.IsEmpty()) Environment.CurrentDirectory = project.SourceBaseDir; string objFile = IO.Path.ChangeExtension(wxsFile, ".wixobj"); string pdbFile = IO.Path.ChangeExtension(wxsFile, ".wixpdb"); string extensionDlls = ""; foreach (string dll in project.WixExtensions.Distinct()) extensionDlls += " -ext \"" + dll + "\""; string wxsFiles = ""; foreach (string file in project.WxsFiles.Distinct()) wxsFiles += " \"" + file + "\""; Run(compiler, CandleOptions + " " + extensionDlls + " \"" + wxsFile + "\" "+ wxsFiles + " -out \"" + objFile + "\""); if (IO.File.Exists(objFile)) { string msiFile = wxsFile.PathChangeExtension(".exe"); if (IO.File.Exists(msiFile)) IO.File.Delete(msiFile); //if (project.IsLocalized && IO.File.Exists(project.LocalizationFile)) // Run(linker, LightOptions + " \"" + objFile + "\" -out \"" + msiFile + "\"" + extensionDlls + " -cultures:" + project.Language + " -loc \"" + project.LocalizationFile + "\""); //else Run(linker, LightOptions + " \"" + objFile + "\" -out \"" + msiFile + "\"" + extensionDlls + " -cultures:" + project.Language); if (IO.File.Exists(msiFile)) { Compiler.TempFiles.Add(wxsFile); Console.WriteLine("\n----------------------------------------------------------\n"); Console.WriteLine("Bootstrapper file has been built: " + path + "\n"); Console.WriteLine(" Name : " + project.Name); Console.WriteLine(" Version : " + project.Version); Console.WriteLine(" UpgradeCode: {" + project.UpgradeCode + "}\n"); IO.File.Delete(objFile); IO.File.Delete(pdbFile); if (path != msiFile) { if (IO.File.Exists(path)) IO.File.Delete(path); IO.File.Move(msiFile, path); } } } else { Console.WriteLine("Cannot build " + wxsFile); Trace.WriteLine("Cannot build " + wxsFile); } } if (!PreserveTempFiles && !project.PreserveTempFiles) foreach (var file in Compiler.TempFiles) try { if (IO.File.Exists(file)) IO.File.Delete(file); } catch { } } finally { Environment.CurrentDirectory = oldCurrDir; } return path; } /// <summary> /// Builds the WiX source file and generates batch file capable of building /// WiX/MSI bootstrapper with WiX toolset. /// </summary> /// <param name="project">The project.</param> /// <param name="path">The path to the batch file to be created.</param> /// <exception cref="System.ApplicationException">Wix compiler/linker cannot be found</exception> public static string BuildCmd(Bundle project, string path = null) { if (Compiler.ClientAssembly.IsEmpty()) Compiler.ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().Location; if (path == null) path = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, "Build_" + project.OutFileName) + ".cmd"); //System.Diagnostics.Debug.Assert(false); string compiler = Utils.PathCombine(WixLocation, "candle.exe"); string linker = Utils.PathCombine(WixLocation, "light.exe"); string batchFile = path; if (!IO.File.Exists(compiler) || !IO.File.Exists(linker)) { Console.WriteLine("Wix binaries cannot be found. Expected location is " + IO.Path.GetDirectoryName(compiler)); throw new ApplicationException("Wix compiler/linker cannot be found"); } else { string wxsFile = BuildWxs(project); if (!project.SourceBaseDir.IsEmpty()) Environment.CurrentDirectory = project.SourceBaseDir; string objFile = IO.Path.ChangeExtension(wxsFile, ".wixobj"); string pdbFile = IO.Path.ChangeExtension(wxsFile, ".wixpdb"); string extensionDlls = ""; foreach (string dll in project.WixExtensions.Distinct()) extensionDlls += " -ext \"" + dll + "\""; string wxsFiles = ""; foreach (string file in project.WxsFiles.Distinct()) wxsFiles += " \"" + file + "\""; string batchFileContent = "\"" + compiler + "\" " + CandleOptions + " " + extensionDlls + " \"" + IO.Path.GetFileName(wxsFile) + "\" "+ wxsFiles + "\r\n"; //Run(compiler, CandleOptions + " " + extensionDlls + " \"" + wxsFile + "\" -out \"" + objFile + "\""); //if (project.IsLocalized && IO.File.Exists(project.LocalizationFile)) // Run(linker, LightOptions + " \"" + objFile + "\" -out \"" + msiFile + "\"" + extensionDlls + " -cultures:" + project.Language + " -loc \"" + project.LocalizationFile + "\""); //else //Run(linker, LightOptions + " \"" + objFile + "\" -out \"" + msiFile + "\"" + extensionDlls + " -cultures:" + project.Language); batchFileContent += "\"" + linker + "\" " + LightOptions + " \"" + objFile + "\" " + extensionDlls + " -cultures:" + project.Language + "\r\npause"; using (var sw = new IO.StreamWriter(batchFile)) sw.Write(batchFileContent); } return path; } /// <summary> /// Builds the WiX source file (*.wxs) from the specified <see cref="Bundle"/> instance. /// </summary> /// <param name="project">The project.</param> /// <returns></returns> public static string BuildWxs(Bundle project) { lock (typeof(Compiler)) { //very important to keep "ClientAssembly = " in all "public Build*" methods to ensure GetCallingAssembly //returns the build script assembly but not just another method of Compiler. if (ClientAssembly.IsEmpty()) ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().Location; WixEntity.ResetIdGenerator(); string file = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, project.OutFileName) + ".wxs"); if (IO.File.Exists(file)) IO.File.Delete(file); string extraNamespaces = project.WixNamespaces.Distinct() .Select(x => x.StartsWith("xmlns:") ? x : "xmlns:" + x) .ConcatItems(" "); var doc = XDocument.Parse( @"<?xml version=""1.0"" encoding=""utf-8""?> <Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi"" " + extraNamespaces + @"> </Wix>"); doc.Root.Add(project.ToXml()); AutoElements.NormalizeFilePaths(doc, project.SourceBaseDir, EmitRelativePaths); project.InvokeWixSourceGenerated(doc); if (WixSourceGenerated != null) WixSourceGenerated(doc); string xml = ""; using (IO.StringWriter sw = new StringWriterWithEncoding(Encoding.Default)) { doc.Save(sw, SaveOptions.None); xml = sw.ToString(); } //of course you can use XmlTextWriter.WriteRaw but this is just a temporary quick'n'dirty solution //http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2657663&SiteID=1 xml = xml.Replace("xmlns=\"\"", ""); DefaultWixSourceFormatedHandler(ref xml); project.InvokeWixSourceFormated(ref xml); if (WixSourceFormated != null) WixSourceFormated(ref xml); using (var sw = new IO.StreamWriter(file, false, Encoding.Default)) sw.WriteLine(xml); Console.WriteLine("\n----------------------------------------------------------\n"); Console.WriteLine("Wix project file has been built: " + file + "\n"); project.InvokeWixSourceSaved(file); if (WixSourceSaved != null) WixSourceSaved(file); return file; } } /// <summary> /// Builds WiX Bootstrapper application from the specified <see cref="Bundle"/> project instance. /// </summary> /// <param name="project">The project.</param> /// <returns></returns> public static string Build(Bundle project) { if (Compiler.ClientAssembly.IsEmpty()) Compiler.ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().Location; string outFile = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, project.OutFileName) + ".exe"); Utils.EnsureFileDir(outFile); if (IO.File.Exists(outFile)) IO.File.Delete(outFile); Build(project, outFile); return IO.File.Exists(outFile) ? outFile : null; } } }
/* * TestTimer.cs - Tests for the "Boolean" class. * * Copyright (C) 2002 Free Software Foundation. * * Author: Russell Stuart <russell-savannah@stuart.id.au> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using CSUnit; using System; using System.Collections; using System.Threading; public class TestTimer : TestCase { AutoResetEvent autoResetEvent; int checkTimeoutCount; Timer timer; DateTime timeTimerExpired; TimerCallback timerCallbackDelegate = new TimerCallback(timerCallback); System.DateTime startTest; public TestTimer(String name) : base(name) { } protected override void Setup() { if (!TestThread.IsThreadingSupported) return; this.timer = new Timer(this.timerCallbackDelegate, this, Timeout.Infinite, Timeout.Infinite); this.timeTimerExpired = DateTime.MaxValue; this.checkTimeoutCount = 0; this.startTest = System.DateTime.Now; this.autoResetEvent = new AutoResetEvent(false); } protected override void Cleanup() { if (!TestThread.IsThreadingSupported) return; this.timer.Dispose(); } public void TestTimerAAAAA() { System.Console.Write("if timers fail up MIN_TIMEOUT in TimerTest.cs .. "); } // // MIN_TIMEOUT is the minimum amount of time (in milliseconds) the tests // try to measure. The bigger this is the longer the tests will take // to run. But if it takes your machine longer than this to execute // the steps in the test, the test will appear to fail. // const int MIN_TIMEOUT = 20; const int SHORT_TIMEOUT = MIN_TIMEOUT * 2; private static void timerCallback(Object state) { TestTimer testTimer = (TestTimer)state; lock (testTimer) { testTimer.timeTimerExpired = DateTime.Now; testTimer.autoResetEvent.Set(); } } private static void timerCallbackDummy(Object state) { } // // Test the constructor builds a reasonable looking object. // public void TestTimerConstructor() { if (!TestThread.IsThreadingSupported) return; TimerCallback timerCallbackDummyDelegate = new TimerCallback(timerCallbackDummy); // // Verify it checks the arguments correctly. // try { new Timer(null, this, 0, 0); Assert("Expected ArgumentNullException", false); } catch (ArgumentNullException) { } Timer timer = new Timer( timerCallbackDummyDelegate, null, 0, Timeout.Infinite); timer.Dispose(); timer = new Timer(timerCallbackDummyDelegate, null, 0, 0); timer.Dispose(); try { new Timer(this.timerCallbackDelegate, this, -2, 0); Assert("Expected ArgumentOutOfRangeException", false); } catch (ArgumentOutOfRangeException) { } try { new Timer(this.timerCallbackDelegate, this, 0, -2); Assert("Expected ArgumentOutOfRangeException", false); } catch (ArgumentOutOfRangeException) { } } // // Test the various constructors set the timeout required. // public void TestTimerConstructorTimeout() { if (!TestThread.IsThreadingSupported) return; // // Test various conbinations of due and period. All we are really // checking here is the right parameters are passed to Change() by // the constructor. // Timer t = new Timer(this.timerCallbackDelegate, this, 0, Timeout.Infinite); this.checkTimeout(0); this.checkTimeout(Timeout.Infinite); t.Dispose(); t = new Timer(this.timerCallbackDelegate, this, 0, SHORT_TIMEOUT); this.checkTimeout(0); this.checkTimeout(SHORT_TIMEOUT); t.Dispose(); // // Ditto, unit time units. // t = new Timer(this.timerCallbackDelegate, this, (uint)0, (uint)0); this.checkTimeout(0); this.checkTimeout(Timeout.Infinite); t.Dispose(); t = new Timer(this.timerCallbackDelegate, this, (uint)SHORT_TIMEOUT, (uint)0); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(Timeout.Infinite); t.Dispose(); // // Ditto, long time units. // t = new Timer(this.timerCallbackDelegate, this, (long)0, (long)0); this.checkTimeout(0); this.checkTimeout(Timeout.Infinite); t.Dispose(); t = new Timer(this.timerCallbackDelegate, this, (long)SHORT_TIMEOUT, (long)0); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(Timeout.Infinite); t.Dispose(); // // Ditto, TimeSpan time units. // t = new Timer(this.timerCallbackDelegate, this, TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(0)); this.checkTimeout(0); this.checkTimeout(Timeout.Infinite); t.Dispose(); t = new Timer(this.timerCallbackDelegate, this, TimeSpan.FromMilliseconds(SHORT_TIMEOUT), TimeSpan.FromMilliseconds(0)); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(Timeout.Infinite); t.Dispose(); } // // Check that all forms of Dispose() work as advertised. // public void TestTimerDispose() { if (!TestThread.IsThreadingSupported) return; Timer t = new Timer(this.timerCallbackDelegate, this, SHORT_TIMEOUT, SHORT_TIMEOUT); t.Dispose(); t.Dispose(); Assert(!t.Change(0, Timeout.Infinite)); this.checkTimeout(Timeout.Infinite); AutoResetEvent autoResetEvent = new AutoResetEvent(false); t = new Timer(this.timerCallbackDelegate, this, SHORT_TIMEOUT, SHORT_TIMEOUT); Assert(t.Dispose(autoResetEvent)); Assert(!t.Dispose(autoResetEvent)); Assert(autoResetEvent.WaitOne(SHORT_TIMEOUT/2, false)); Assert(this.timeTimerExpired == DateTime.MaxValue); try { this.timer.Dispose(null); Assert("Expected ArgumentNullException", false); } catch (ArgumentNullException) { } } // // Test all combinations of due and period. // public void TestTimerTimeout() { if (!TestThread.IsThreadingSupported) return; // // Test various conbinations of due and period. // Assert(this.timer.Change(0, Timeout.Infinite)); this.checkTimeout(0); this.checkTimeout(Timeout.Infinite); Assert(this.timer.Change(SHORT_TIMEOUT, Timeout.Infinite)); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(Timeout.Infinite); Assert(this.timer.Change(SHORT_TIMEOUT, 0)); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(Timeout.Infinite); Assert(this.timer.Change(0, SHORT_TIMEOUT)); this.checkTimeout(0); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); Assert(this.timer.Change(SHORT_TIMEOUT, SHORT_TIMEOUT)); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); // // Test setting the timeouts in various units. // Assert(this.timer.Change((uint)SHORT_TIMEOUT, (uint)SHORT_TIMEOUT)); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); Assert(this.timer.Change((long)SHORT_TIMEOUT, (long)SHORT_TIMEOUT)); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); Assert(this.timer.Change( TimeSpan.FromMilliseconds(SHORT_TIMEOUT), TimeSpan.FromMilliseconds(SHORT_TIMEOUT))); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); // // Test cancelling a timeout. // Assert(this.timer.Change(Timeout.Infinite, Timeout.Infinite)); this.checkTimeout(Timeout.Infinite); } private void checkTimeout(int delay) { checkTimeoutCount += 1; DateTime dateTime; // // A zero delay. // if (delay == 0) { Assert(this.autoResetEvent.WaitOne(MIN_TIMEOUT, false)); lock (this) this.timeTimerExpired = DateTime.MaxValue; return; } // // A non-Infinite delay. // if (delay != Timeout.Infinite) { long timeStarted = DateTime.UtcNow.Ticks; Assert(this.autoResetEvent.WaitOne(delay + MIN_TIMEOUT, false)); lock (this) this.timeTimerExpired = DateTime.MaxValue; Assert(DateTime.UtcNow.Ticks - timeStarted > SHORT_TIMEOUT - MIN_TIMEOUT); return; } // // The timer should NOT expire. // Thread.Sleep(SHORT_TIMEOUT + MIN_TIMEOUT); lock (this) { dateTime = this.timeTimerExpired; this.timeTimerExpired = DateTime.MaxValue; } Assert(dateTime == DateTime.MaxValue); } private int recurseCount; private static void timerCallbackRecursive(Object state) { TestTimer testTimer = (TestTimer)state; lock (testTimer) { testTimer.timeTimerExpired = DateTime.Now; testTimer.autoResetEvent.Set(); if (--testTimer.recurseCount > 0) Assert(testTimer.timer.Change(SHORT_TIMEOUT, Timeout.Infinite)); } } // // Test the callback changing the timeout. // public void TestTimerChangeRecursive() { if (!TestThread.IsThreadingSupported) return; this.recurseCount = 3; this.timer.Dispose(); this.timer = new Timer(new TimerCallback(timerCallbackRecursive), this, 0, SHORT_TIMEOUT); this.checkTimeout(0); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(SHORT_TIMEOUT); this.checkTimeout(Timeout.Infinite); } // // Test timeouts fire in the correct order. // // Brute force is used here. Every possible ordering of 1, 2, 3, // 4 and 5 timers is checked. // private class TimerTester : IDisposable { private Timer timer; private int id; private bool armed; private TestTimer testTimer; public TimerTester(TestTimer testTimer, int id) { this.testTimer = testTimer; this.id = id; this.timer = new Timer(new TimerCallback(expired), this, Timeout.Infinite, Timeout.Infinite); this.armed = false; } public void Arm() { this.timer.Change( SHORT_TIMEOUT + this.id * MIN_TIMEOUT, Timeout.Infinite); this.armed = true; } public void Disarm() { lock (this.testTimer) { this.timer.Change(Timeout.Infinite, Timeout.Infinite); this.armed = false; } } public void Dispose() { this.timer.Dispose(); } public int Id { get { return this.id; } } public bool IsArmed { get { return this.armed; } } private static void expired(Object state) { TimerTester timerTester = (TimerTester)state; lock (timerTester.testTimer) { // // Did somebody else fail? // if (timerTester.testTimer.vectorIndex < 0) return; // // Were we supposed to go off? // if (!timerTester.armed || timerTester.testTimer.vectorIndex > timerTester.id) { timerTester.testTimer.vectorIndex = -timerTester.id; return; } // // We were supposed to be next. // timerTester.testTimer.vectorIndex = timerTester.id + 1; timerTester.testTimer.firedCount -= 1; if (timerTester.testTimer.firedCount == 0) Monitor.Pulse(timerTester.testTimer); } } } private TimerTester[] timerVector; private int vectorIndex; private int firedCount; public void TestTimerTimeoutOrdering() { if (!TestThread.IsThreadingSupported) return; System.Console.Write("this will take a while ... "); for (int i = 1; i <= 5; i += 1) { this.timerVector = new TimerTester[i]; try { for (int j = 0; j < this.timerVector.Length; j += 1) this.timerVector[j] = new TimerTester(this, j + 1); permuteTimeoutOrdering(0); } finally { for (int j = 0; j < this.timerVector.Length; j += 1) this.timerVector[j].Dispose(); this.timerVector = null; } } } private void permuteTimeoutOrdering(int index) { // // Have we finished permuting this.timerVector? // if (index == this.timerVector.Length) { // // Arm all the timers and do the test. // lock (this) { this.vectorIndex = 1; this.firedCount = this.timerVector.Length; for (int i = 0; i < this.timerVector.Length; i += 1) this.timerVector[i].Arm(); Assert(Monitor.Wait(this, SHORT_TIMEOUT*2 + this.firedCount*MIN_TIMEOUT)); Assert(this.firedCount == 0); } return; } // // Permute the vector at the passed index. // TimerTester first = this.timerVector[index]; for (int i = index; i < this.timerVector.Length; i += 1) { this.timerVector[index] = this.timerVector[i]; this.timerVector[i] = first; this.permuteTimeoutOrdering(index + 1); this.timerVector[i] = this.timerVector[index]; this.timerVector[index] = first; } } // // Test timer cancelling. // // Again a brute force test. Create a number of times, then delete every // 2nd one, every 3rd one, and so on. // public void TestTimerCancel() { if (!TestThread.IsThreadingSupported) return; this.timerVector = new TimerTester[10]; for (int i = 0; i < this.timerVector.Length; i += 1) { int id = (i + this.timerVector.Length/2) % this.timerVector.Length + 1; this.timerVector[i] = new TimerTester(this, id); } try { for (int i = 2; i <= this.timerVector.Length; i += 1) { lock (this) { this.firedCount = this.timerVector.Length; this.vectorIndex = 1; for (int j = 0; j < this.timerVector.Length; j += 1) this.timerVector[j].Arm(); for (int j = i - 1; j < this.timerVector.Length; j += i) { this.timerVector[j].Disarm(); this.firedCount -= 1; } Assert(Monitor.Wait(this, SHORT_TIMEOUT*2 + this.timerVector.Length*MIN_TIMEOUT)); } } } finally { for (int i = 0; i < this.timerVector.Length; i += 1) this.timerVector[i].Dispose(); this.timerVector = null; } } }
// 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.IO; using System.Drawing.Internal; using Gdip = System.Drawing.SafeNativeMethods.Gdip; using System.Runtime.Serialization; namespace System.Drawing.Imaging { /// <summary> /// Defines a graphic metafile. A metafile contains records that describe a sequence of graphics operations that /// can be recorded and played back. /// </summary> public sealed partial class Metafile : Image { /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and /// <see cref='WmfPlaceableFileHeader'/>. /// </summary> public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) : this(hmetafile, wmfHeader, false) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified stream. /// </summary> public Metafile(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } Gdip.CheckStatus(Gdip.GdipCreateMetafileFromStream(new GPStream(stream), out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context. /// </summary> public Metafile(IntPtr referenceHdc, EmfType emfType, string description) { Gdip.CheckStatus(Gdip.GdipRecordMetafile( referenceHdc, emfType, IntPtr.Zero, MetafileFrameUnit.GdiCompatible, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string desc) { IntPtr metafile = IntPtr.Zero; if (frameRect.IsEmpty) { Gdip.CheckStatus(Gdip.GdipRecordMetafile( referenceHdc, type, IntPtr.Zero, MetafileFrameUnit.GdiCompatible, desc, out metafile)); } else { Gdip.CheckStatus(Gdip.GdipRecordMetafileI( referenceHdc, type, ref frameRect, frameUnit, desc, out metafile)); } SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, EmfType type, string description) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); Gdip.CheckStatus(Gdip.GdipRecordMetafileFileName( fileName, referenceHdc, type, IntPtr.Zero, MetafileFrameUnit.GdiCompatible, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); IntPtr metafile = IntPtr.Zero; if (frameRect.IsEmpty) { Gdip.CheckStatus(Gdip.GdipRecordMetafileFileName( fileName, referenceHdc, type, IntPtr.Zero, frameUnit, description, out metafile)); } else { Gdip.CheckStatus(Gdip.GdipRecordMetafileFileNameI( fileName, referenceHdc, type, ref frameRect, frameUnit, description, out metafile)); } SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description) { Gdip.CheckStatus(Gdip.GdipRecordMetafileStream( new GPStream(stream), referenceHdc, type, IntPtr.Zero, MetafileFrameUnit.GdiCompatible, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { Gdip.CheckStatus(Gdip.GdipRecordMetafileStream( new GPStream(stream), referenceHdc, type, ref frameRect, frameUnit, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { IntPtr metafile = IntPtr.Zero; if (frameRect.IsEmpty) { Gdip.CheckStatus(Gdip.GdipRecordMetafileStream( new GPStream(stream), referenceHdc, type, IntPtr.Zero, frameUnit, description, out metafile)); } else { Gdip.CheckStatus(Gdip.GdipRecordMetafileStreamI( new GPStream(stream), referenceHdc, type, ref frameRect, frameUnit, description, out metafile)); } SetNativeImage(metafile); } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) { MetafileHeader header = new MetafileHeader { wmf = new MetafileHeaderWmf() }; Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromWmf(hmetafile, wmfHeader, header.wmf)); return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(IntPtr henhmetafile) { MetafileHeader header = new MetafileHeader { emf = new MetafileHeaderEmf() }; Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromEmf(henhmetafile, header.emf)); return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(string fileName) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); MetafileHeader header = new MetafileHeader(); IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromFile(fileName, memory)); int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(Stream stream) { MetafileHeader header; IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromStream(new GPStream(stream), memory)); int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; header = new MetafileHeader(); if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with this <see cref='Metafile'/>. /// </summary> public MetafileHeader GetMetafileHeader() { MetafileHeader header; IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromMetafile(new HandleRef(this, nativeImage), memory)); int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; header = new MetafileHeader(); if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns a Windows handle to an enhanced <see cref='Metafile'/>. /// </summary> public IntPtr GetHenhmetafile() { Gdip.CheckStatus(Gdip.GdipGetHemfFromMetafile(new HandleRef(this, nativeImage), out IntPtr hEmf)); return hEmf; } } }
namespace Nancy.Tests.Unit.ErrorHandling { using System; using System.IO; using FakeItEasy; using Nancy.Configuration; using Nancy.ErrorHandling; using Nancy.Responses.Negotiation; using Nancy.ViewEngines; using Xunit; using Xunit.Extensions; public class DefaultStatusCodeHandlerFixture { private readonly IResponseNegotiator responseNegotiator; private readonly IStatusCodeHandler statusCodeHandler; public DefaultStatusCodeHandlerFixture() { var environment = new DefaultNancyEnvironment(); environment.Tracing( enabled: true, displayErrorTraces: true); this.responseNegotiator = A.Fake<IResponseNegotiator>(); this.statusCodeHandler = new DefaultStatusCodeHandler(this.responseNegotiator, environment); } [Theory] [InlineData(HttpStatusCode.Continue)] [InlineData(HttpStatusCode.SwitchingProtocols)] [InlineData(HttpStatusCode.Processing)] [InlineData(HttpStatusCode.Checkpoint)] [InlineData(HttpStatusCode.OK)] [InlineData(HttpStatusCode.Created)] [InlineData(HttpStatusCode.Accepted)] [InlineData(HttpStatusCode.NonAuthoritativeInformation)] [InlineData(HttpStatusCode.NoContent)] [InlineData(HttpStatusCode.ResetContent)] [InlineData(HttpStatusCode.PartialContent)] [InlineData(HttpStatusCode.MultipleStatus)] [InlineData(HttpStatusCode.IMUsed)] [InlineData(HttpStatusCode.MultipleChoices)] [InlineData(HttpStatusCode.MovedPermanently)] [InlineData(HttpStatusCode.Found)] [InlineData(HttpStatusCode.SeeOther)] [InlineData(HttpStatusCode.NotModified)] [InlineData(HttpStatusCode.UseProxy)] [InlineData(HttpStatusCode.SwitchProxy)] [InlineData(HttpStatusCode.TemporaryRedirect)] [InlineData(HttpStatusCode.ResumeIncomplete)] [InlineData(HttpStatusCode.Unauthorized)] public void Should_not_handle_non_error_codes(HttpStatusCode statusCode) { var result = this.statusCodeHandler.HandlesStatusCode(statusCode, null); result.ShouldBeFalse(); } [Theory] [InlineData(HttpStatusCode.Continue)] [InlineData(HttpStatusCode.SwitchingProtocols)] [InlineData(HttpStatusCode.Processing)] [InlineData(HttpStatusCode.Checkpoint)] [InlineData(HttpStatusCode.OK)] [InlineData(HttpStatusCode.Created)] [InlineData(HttpStatusCode.Accepted)] [InlineData(HttpStatusCode.NonAuthoritativeInformation)] [InlineData(HttpStatusCode.NoContent)] [InlineData(HttpStatusCode.ResetContent)] [InlineData(HttpStatusCode.PartialContent)] [InlineData(HttpStatusCode.MultipleStatus)] [InlineData(HttpStatusCode.IMUsed)] [InlineData(HttpStatusCode.MultipleChoices)] [InlineData(HttpStatusCode.MovedPermanently)] [InlineData(HttpStatusCode.Found)] [InlineData(HttpStatusCode.SeeOther)] [InlineData(HttpStatusCode.NotModified)] [InlineData(HttpStatusCode.UseProxy)] [InlineData(HttpStatusCode.SwitchProxy)] [InlineData(HttpStatusCode.TemporaryRedirect)] [InlineData(HttpStatusCode.ResumeIncomplete)] [InlineData(HttpStatusCode.Unauthorized)] public void Should_not_respond_when_handling_non_error_codes(HttpStatusCode statusCode) { // Given var context = new NancyContext(); // When this.statusCodeHandler.Handle(statusCode, context); // Then context.Response.ShouldBeNull(); } [Fact] public void Should_set_response_contents_if_required() { // Given var context = new NancyContext(); context.Response = new Response(); // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then context.Response.Contents.ShouldNotBeNull(); } [Fact] public void Should_not_overwrite_response_contents() { // Given var context = new NancyContext(); Action<Stream> contents = stream => { }; context.Response = new Response() { StatusCode = HttpStatusCode.NotFound, Contents = contents }; // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then context.Response.Contents.ShouldEqual(contents); } [Fact] public void Should_overwrite_response_contents_if_the_body_is_null_object() { // Given var context = new NancyContext(); context.Response = new Response { StatusCode = HttpStatusCode.NotFound }; A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).Throws(new ViewNotFoundException(string.Empty)); // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then using (var stream = new MemoryStream()) { context.Response.Contents.Invoke(stream); stream.ToArray().Length.ShouldBeGreaterThan(0); } } [Fact] public void Should_create_response_if_it_doesnt_exist_in_context() { // Given var context = new NancyContext(); // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then context.Response.ShouldNotBeNull(); } [Fact] public void Should_leave_reponse_stream_open_if_response_is_InternalServerError() { // Given var context = new NancyContext(); var memoryStream = new MemoryStream(); // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); context.Response.Contents(memoryStream); // Then memoryStream.CanRead.ShouldBeTrue(); } [Fact] public void Should_negotiate_response_with_content_negotiator() { // Given var context = new NancyContext(); // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); // Then A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).MustHaveHappened(); } [Fact] public void Should_render_html_response_from_static_resources() { // Given var context = new NancyContext(); A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).Throws(new ViewNotFoundException(string.Empty)); // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); // Then Assert.Equal("text/html", context.Response.ContentType); } [Fact] public void Should_reset_negotiation_context() { // Given var context = new NancyContext(); var negotiationContext = new NegotiationContext { ViewName = "Index" }; context.NegotiationContext = negotiationContext; // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); // Then Assert.Null(context.NegotiationContext.ViewName); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Uheer.Areas.HelpPage.ModelDescriptions; using Uheer.Areas.HelpPage.Models; namespace Uheer.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.IO; using System.Linq; using NUnit.Framework; namespace Mercurial.Tests { [TestFixture] public class MergeJobTests : MergeResolveTests { [Test] [Category("Integration")] public void StartMerge_NoRepository_ThrowsMercurialExecutionException() { try { Repo.StartMerge(); } catch (MercurialExecutionException) { // success } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } } [Test] [Category("Integration")] public void StartMerge_NoChangesetsToMerge_ThrowsMercurialExecutionException() { Repo.Init(); WriteTextFileAndCommit(Repo, "dummy.txt", "dummy", "dummy", true); try { Repo.StartMerge(); } catch (MercurialExecutionException) { // success } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } } [Test] [Category("Integration")] public void StartMerge_RepoWithoutMergeConflict_ReturnsMergeJobThatIsReadyToCommit() { CreateRepositoryWithoutMergeConflicts(); try { MergeJob job = Repo.StartMerge(); Assert.That(job.State, Is.EqualTo(MergeJobState.ReadyToCommit)); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } } [Test] [Category("Integration")] public void StartMerge_RepoWithMergeConflict_ReturnsMergeJobThatHasConflicts() { CreateRepositoryWithMergeConflicts(); try { MergeJob job = Repo.StartMerge(); Assert.That(job.State, Is.EqualTo(MergeJobState.HasUnresolvedConflicts)); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } } [Test] [Category("Integration")] public void StartMerge_RepoWithMergeConflict_ReturnsMergeJobThatListsTheConflictingFile() { CreateRepositoryWithMergeConflicts(); try { MergeJob job = Repo.StartMerge(); CollectionAssert.AreEqual( new[] { new MergeJobConflict(job, "dummy.txt", MergeConflictState.Unresolved), }, job.UnresolvedConflicts); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } } [Test] [Category("Integration")] public void CancelMerge_MergeWithConflicts_RestoresStateOfFile() { CreateRepositoryWithMergeConflicts(); MergeJob job; try { job = Repo.StartMerge(); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); return; } job.CancelMerge(); string contents = File.ReadAllText(Path.Combine(Repo.Path, "dummy.txt")); const string expected = "1 yyy\n2\n3\n4\n5"; Assert.That(contents, Is.EqualTo(expected)); } [Test] [Category("Integration")] public void ResolveConflictThroughMerge_MarksFileAsResolved() { CreateRepositoryWithMergeConflicts(); MergeJob job = null; try { job = Repo.StartMerge(); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } job.UnresolvedConflicts.First().Resolve(new ResolveCommand().WithMergeTool(MergeTools.InternalLocal)); Assert.That(job.State, Is.EqualTo(MergeJobState.ReadyToCommit)); } [Test] [Category("Integration")] public void Cleanup_RemovesExtraFiles() { CreateRepositoryWithMergeConflicts(); MergeJob job; try { job = Repo.StartMerge(); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); return; } job.Cleanup(); FileStatus[] status = Repo.Status().ToArray(); CollectionAssert.AreEqual( new[] { new FileStatus(FileState.Modified, "dummy.txt"), }, status); } [Test] [Category("Integration")] public void Commit_WithUnresolvedConflicts_ThrowsInvalidOperationException() { CreateRepositoryWithMergeConflicts(); try { MergeJob job = Repo.StartMerge(); Assert.Throws<InvalidOperationException>(() => job.Commit("merged")); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } } [Test] [Category("Integration")] public void Commit_WithNoUnresolvedConflicts_Commits() { CreateRepositoryWithoutMergeConflicts(); int logEntriesBeforeCommit = Repo.Log().Count(); MergeJob job; try { job = Repo.StartMerge(); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); return; } job.Commit("merged"); int logEntriesAfterCommit = Repo.Log().Count(); Assert.That(logEntriesAfterCommit, Is.GreaterThan(logEntriesBeforeCommit)); } [Test] [Category("Integration")] public void Parents_InAMerge_HasCorrectValues() { CreateRepositoryWithoutMergeConflicts(); try { MergeJob job = Repo.StartMerge(); Assert.That(job.LocalParent.RevisionNumber, Is.EqualTo(2)); Assert.That(job.OtherParent.RevisionNumber, Is.EqualTo(1)); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } } [Test] [Category("Integration")] [TestCase(MergeJobConflictSubFile.Base, "dummy.txt.base")] [TestCase(MergeJobConflictSubFile.Local, "dummy.txt.local")] [TestCase(MergeJobConflictSubFile.Other, "dummy.txt.other")] [TestCase(MergeJobConflictSubFile.Current, "dummy.txt")] public void MergeJobFile_IndividualFilePathsForAConflict_WithTestCases(MergeJobConflictSubFile subFile, string expectedPath) { CreateRepositoryWithMergeConflicts(); MergeJob job; try { job = Repo.StartMerge(); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); return; } string path = job[0].GetMergeSubFilePath(subFile); Assert.That(path, Is.EqualTo(expectedPath)); path = job[0].GetFullMergeSubFilePath(subFile); expectedPath = Path.Combine(Repo.Path, expectedPath); Assert.That(path, Is.EqualTo(expectedPath)); } [Test] [Category("Integration")] [TestCase(MergeJobConflictSubFile.Base, BaseContents)] [TestCase(MergeJobConflictSubFile.Local, LocalChangedContentsWithConflict)] [TestCase(MergeJobConflictSubFile.Other, OtherChangedContents)] [TestCase(MergeJobConflictSubFile.Current, LocalChangedContentsWithConflict)] public void MergeJobFile_IndividualFileContentsForAConflict_WithTestCases(MergeJobConflictSubFile subFile, string expectedContents) { CreateRepositoryWithMergeConflicts(); MergeJob job; try { job = Repo.StartMerge(); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); return; } string contents = job[0].GetMergeSubFileContentsAsText(subFile); Assert.That(contents, Is.EqualTo(expectedContents)); } } }
// 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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; namespace System.Security.Principal { public class IdentityReferenceCollection : ICollection<IdentityReference> { #region Private members // // Container enumerated by this collection // private readonly List<IdentityReference> _Identities; #endregion #region Constructors // // Creates an empty collection of default size // public IdentityReferenceCollection() : this(0) { } // // Creates an empty collection of given initial size // public IdentityReferenceCollection(int capacity) { _Identities = new List<IdentityReference>(capacity); } #endregion #region ICollection<IdentityReference> implementation public void CopyTo(IdentityReference[] array, int offset) { _Identities.CopyTo(0, array, offset, Count); } public int Count { get { return _Identities.Count; } } bool ICollection<IdentityReference>.IsReadOnly { get { return false; } } public void Add(IdentityReference identity) { if (identity == null) { throw new ArgumentNullException(nameof(identity)); } Contract.EndContractBlock(); _Identities.Add(identity); } public bool Remove(IdentityReference identity) { if (identity == null) { throw new ArgumentNullException(nameof(identity)); } Contract.EndContractBlock(); if (Contains(identity)) { return _Identities.Remove(identity); } return false; } public void Clear() { _Identities.Clear(); } public bool Contains(IdentityReference identity) { if (identity == null) { throw new ArgumentNullException(nameof(identity)); } Contract.EndContractBlock(); return _Identities.Contains(identity); } #endregion #region IEnumerable<IdentityReference> implementation IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<IdentityReference> GetEnumerator() { return new IdentityReferenceEnumerator(this); } #endregion #region Public methods public IdentityReference this[int index] { get { return _Identities[index]; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); _Identities[index] = value; } } internal List<IdentityReference> Identities { get { return _Identities; } } public IdentityReferenceCollection Translate(Type targetType) { return Translate(targetType, false); } public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) { if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } // // Target type must be a subclass of IdentityReference // if (!targetType.GetTypeInfo().IsSubclassOf(typeof(IdentityReference))) { throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType)); } Contract.EndContractBlock(); // // if the source collection is empty, just return an empty collection // if (Identities.Count == 0) { return new IdentityReferenceCollection(); } int SourceSidsCount = 0; int SourceNTAccountsCount = 0; // // First, see how many of each of the source types we have. // The cases where source type == target type require no conversion. // for (int i = 0; i < Identities.Count; i++) { Type type = Identities[i].GetType(); if (type == targetType) { continue; } else if (type == typeof(SecurityIdentifier)) { SourceSidsCount += 1; } else if (type == typeof(NTAccount)) { SourceNTAccountsCount += 1; } else { // // Rare case that we have defined a type of identity reference and not included it in the code logic above. // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL. // Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic."); throw new NotSupportedException(); } } bool Homogeneous = false; IdentityReferenceCollection SourceSids = null; IdentityReferenceCollection SourceNTAccounts = null; if (SourceSidsCount == Count) { Homogeneous = true; SourceSids = this; } else if (SourceSidsCount > 0) { SourceSids = new IdentityReferenceCollection(SourceSidsCount); } if (SourceNTAccountsCount == Count) { Homogeneous = true; SourceNTAccounts = this; } else if (SourceNTAccountsCount > 0) { SourceNTAccounts = new IdentityReferenceCollection(SourceNTAccountsCount); } // // Repackage only if the source is not homogeneous (contains different source types) // IdentityReferenceCollection Result = null; if (!Homogeneous) { Result = new IdentityReferenceCollection(Identities.Count); for (int i = 0; i < Identities.Count; i++) { IdentityReference id = this[i]; Type type = id.GetType(); if (type == targetType) { continue; } else if (type == typeof(SecurityIdentifier)) { SourceSids.Add(id); } else if (type == typeof(NTAccount)) { SourceNTAccounts.Add(id); } else { // // Rare case that we have defined a type of identity reference and not included it in the code logic above. // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL. // Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic."); throw new NotSupportedException(); } } } bool someFailed = false; IdentityReferenceCollection TargetSids = null, TargetNTAccounts = null; if (SourceSidsCount > 0) { TargetSids = SecurityIdentifier.Translate(SourceSids, targetType, out someFailed); if (Homogeneous && !(forceSuccess && someFailed)) { Result = TargetSids; } } if (SourceNTAccountsCount > 0) { TargetNTAccounts = NTAccount.Translate(SourceNTAccounts, targetType, out someFailed); if (Homogeneous && !(forceSuccess && someFailed)) { Result = TargetNTAccounts; } } if (forceSuccess && someFailed) { // // Need to throw an exception here and provide information regarding // which identity references could not be translated to the target type // Result = new IdentityReferenceCollection(); if (TargetSids != null) { foreach (IdentityReference id in TargetSids) { if (id.GetType() != targetType) { Result.Add(id); } } } if (TargetNTAccounts != null) { foreach (IdentityReference id in TargetNTAccounts) { if (id.GetType() != targetType) { Result.Add(id); } } } throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, Result); } else if (!Homogeneous) { SourceSidsCount = 0; SourceNTAccountsCount = 0; Result = new IdentityReferenceCollection(Identities.Count); for (int i = 0; i < Identities.Count; i++) { IdentityReference id = this[i]; Type type = id.GetType(); if (type == targetType) { Result.Add(id); } else if (type == typeof(SecurityIdentifier)) { Result.Add(TargetSids[SourceSidsCount++]); } else if (type == typeof(NTAccount)) { Result.Add(TargetNTAccounts[SourceNTAccountsCount++]); } else { // // Rare case that we have defined a type of identity reference and not included it in the code logic above. // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL. // Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic."); throw new NotSupportedException(); } } } return Result; } #endregion } internal class IdentityReferenceEnumerator : IEnumerator<IdentityReference>, IDisposable { #region Private members // // Current enumeration index // private int _current; // // Parent collection // private readonly IdentityReferenceCollection _collection; #endregion #region Constructors internal IdentityReferenceEnumerator(IdentityReferenceCollection collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } Contract.EndContractBlock(); _collection = collection; _current = -1; } #endregion #region IEnumerator implementation /// <internalonly/> object IEnumerator.Current { get { return Current; } } public IdentityReference Current { get { return _collection.Identities[_current]; } } public bool MoveNext() { _current++; return (_current < _collection.Count); } public void Reset() { _current = -1; } public void Dispose() { } #endregion } }
// // CoverArtService.cs // // Authors: // James Willcox <snorp@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2005-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.Data; using Gtk; using Mono.Unix; using Hyena; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.ServiceStack; using Banshee.Configuration; using Banshee.Gui; using Banshee.Collection.Gui; using Banshee.Library; using Banshee.Metadata; using Banshee.Networking; using Banshee.Sources; namespace Banshee.CoverArt { public class CoverArtService : IExtensionService { private InterfaceActionService action_service; private ActionGroup actions; private bool disposed; private uint ui_manager_id; private CoverArtJob job; public CoverArtService () { } void IExtensionService.Initialize () { if (!ServiceManager.DbConnection.TableExists ("CoverArtDownloads")) { ServiceManager.DbConnection.Execute (@" CREATE TABLE CoverArtDownloads ( AlbumID INTEGER UNIQUE, Downloaded BOOLEAN, LastAttempt INTEGER NOT NULL )"); } action_service = ServiceManager.Get<InterfaceActionService> (); if (!ServiceStartup ()) { ServiceManager.SourceManager.SourceAdded += OnSourceAdded; } } private void OnSourceAdded (SourceAddedArgs args) { if (ServiceStartup ()) { ServiceManager.SourceManager.SourceAdded -= OnSourceAdded; } } private bool ServiceStartup () { if (action_service == null || ServiceManager.SourceManager.MusicLibrary == null) { return false; } Initialize (); return true; } private void Initialize () { ThreadAssist.AssertInMainThread (); actions = new ActionGroup ("CoverArt"); ActionEntry[] action_list = new ActionEntry [] { new ActionEntry ("CoverArtAction", null, Catalog.GetString ("_Cover Art"), null, Catalog.GetString ("Manage cover art"), null), new ActionEntry ("FetchCoverArtAction", null, Catalog.GetString ("_Download Cover Art"), null, Catalog.GetString ("Download cover art for all tracks"), OnFetchCoverArt) }; actions.Add (action_list); action_service.UIManager.InsertActionGroup (actions, 0); ui_manager_id = action_service.UIManager.AddUiFromResource ("CoverArtMenu.xml"); ServiceManager.SourceManager.MusicLibrary.TracksAdded += OnTracksAdded; ServiceManager.SourceManager.MusicLibrary.TracksChanged += OnTracksChanged; } public void Dispose () { if (disposed) { return; } ThreadAssist.ProxyToMain (delegate { Gtk.Action fetch_action = action_service.GlobalActions["FetchCoverArtAction"]; if (fetch_action != null) { action_service.GlobalActions.Remove (fetch_action); } action_service.RemoveActionGroup ("CoverArt"); action_service.UIManager.RemoveUi (ui_manager_id); actions.Dispose (); actions = null; action_service = null; ServiceManager.SourceManager.MusicLibrary.TracksAdded -= OnTracksAdded; ServiceManager.SourceManager.MusicLibrary.TracksChanged -= OnTracksChanged; disposed = true; }); } public void FetchCoverArt () { bool force = false; if (!String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("BANSHEE_FORCE_COVER_ART_FETCH"))) { Log.Debug ("Forcing cover art download session"); force = true; } FetchCoverArt (force); } public void FetchCoverArt (bool force) { if (job == null && ServiceManager.Get<Network> ().Connected) { DateTime last_scan = DateTime.MinValue; if (!force) { try { last_scan = DatabaseConfigurationClient.Client.Get<DateTime> ("last_cover_art_scan", DateTime.MinValue); } catch (FormatException) { Log.Warning ("last_cover_art_scan is malformed, resetting to default value"); DatabaseConfigurationClient.Client.Set<DateTime> ("last_cover_art_scan", DateTime.MinValue); } } job = new CoverArtJob (last_scan); job.Finished += delegate { if (!job.IsCancelRequested) { DatabaseConfigurationClient.Client.Set<DateTime> ("last_cover_art_scan", DateTime.Now); } job = null; }; job.Start (); } } private void OnFetchCoverArt (object o, EventArgs args) { FetchCoverArt (true); } private void OnTracksAdded (Source sender, TrackEventArgs args) { FetchCoverArt (); } private void OnTracksChanged (Source sender, TrackEventArgs args) { if (args.ChangedFields == null) { FetchCoverArt (); } else { foreach (Hyena.Query.QueryField field in args.ChangedFields) { if (field == Banshee.Query.BansheeQuery.AlbumField || field == Banshee.Query.BansheeQuery.ArtistField) { FetchCoverArt (); break; } } } } string IService.ServiceName { get { return "CoverArtService"; } } public static readonly SchemaEntry<bool> EnabledSchema = new SchemaEntry<bool> ( "plugins.cover_art", "enabled", true, "Plugin enabled", "Cover art plugin enabled" ); } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; using System.Xml.XPath; namespace Aphysoft.Share.Html { /// <summary> /// Represents an HTML navigator on an HTML document seen as a data store. /// </summary> public class HtmlNodeNavigator : XPathNavigator { #region Fields private int _attindex; private HtmlNode _currentnode; private HtmlDocument _doc = new HtmlDocument(); private HtmlNameTable _nametable = new HtmlNameTable(); internal bool Trace; #endregion #region Constructors internal HtmlNodeNavigator() { Reset(); } internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode) { if (currentNode == null) { throw new ArgumentNullException("currentNode"); } if (currentNode.OwnerDocument != doc) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } InternalTrace(null); _doc = doc; Reset(); _currentnode = currentNode; } private HtmlNodeNavigator(HtmlNodeNavigator nav) { if (nav == null) { throw new ArgumentNullException("nav"); } InternalTrace(null); _doc = nav._doc; _currentnode = nav._currentnode; _attindex = nav._attindex; _nametable = nav._nametable; // REVIEW: should we do this? } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public HtmlNodeNavigator(Stream stream) { _doc.Load(stream); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding) { _doc.Load(stream, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document.</param> public HtmlNodeNavigator(TextReader reader) { _doc.Load(reader); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> public HtmlNodeNavigator(string path) { _doc.Load(path); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(string path, Encoding encoding) { _doc.Load(path, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } #endregion #region Properties /// <summary> /// Gets the base URI for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string BaseURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the current HTML document. /// </summary> public HtmlDocument CurrentDocument { get { return _doc; } } /// <summary> /// Gets the current HTML node. /// </summary> public HtmlNode CurrentNode { get { return _currentnode; } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasAttributes { get { InternalTrace(">" + (_currentnode.Attributes.Count > 0)); return (_currentnode.Attributes.Count > 0); } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasChildren { get { InternalTrace(">" + (_currentnode.ChildNodes.Count > 0)); return (_currentnode.ChildNodes.Count > 0); } } /// <summary> /// Gets a value indicating whether the current node is an empty element. /// </summary> public override bool IsEmptyElement { get { InternalTrace(">" + !HasChildren); // REVIEW: is this ok? return !HasChildren; } } /// <summary> /// Gets the name of the current HTML node without the namespace prefix. /// </summary> public override string LocalName { get { if (_attindex != -1) { InternalTrace("att>" + _currentnode.Attributes[_attindex].Name); return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name); } InternalTrace("node>" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } /// <summary> /// Gets the qualified name of the current node. /// </summary> public override string Name { get { InternalTrace(">" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } /// <summary> /// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string NamespaceURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the <see cref="XmlNameTable"/> associated with this implementation. /// </summary> public override XmlNameTable NameTable { get { InternalTrace(null); return _nametable; } } /// <summary> /// Gets the type of the current node. /// </summary> public override XPathNodeType NodeType { get { switch (_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + XPathNodeType.Comment); return XPathNodeType.Comment; case HtmlNodeType.Document: InternalTrace(">" + XPathNodeType.Root); return XPathNodeType.Root; case HtmlNodeType.Text: InternalTrace(">" + XPathNodeType.Text); return XPathNodeType.Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + XPathNodeType.Attribute); return XPathNodeType.Attribute; } InternalTrace(">" + XPathNodeType.Element); return XPathNodeType.Element; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the prefix associated with the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string Prefix { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the text value of the current node. /// </summary> public override string Value { get { InternalTrace("nt=" + _currentnode.NodeType); switch (_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + ((HtmlCommentNode) _currentnode).Comment); return ((HtmlCommentNode) _currentnode).Comment; case HtmlNodeType.Document: InternalTrace(">"); return ""; case HtmlNodeType.Text: InternalTrace(">" + ((HtmlTextNode) _currentnode).Text); return ((HtmlTextNode) _currentnode).Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + _currentnode.Attributes[_attindex].Value); return _currentnode.Attributes[_attindex].Value; } return _currentnode.InnerText; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the xml:lang scope for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string XmlLang { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } #endregion #region Public Methods /// <summary> /// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator. /// </summary> /// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns> public override XPathNavigator Clone() { InternalTrace(null); return new HtmlNodeNavigator(this); } /// <summary> /// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns> public override string GetAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); HtmlAttribute att = _currentnode.Attributes[localName]; if (att == null) { InternalTrace(">null"); return null; } InternalTrace(">" + att.Value); return att.Value; } /// <summary> /// Returns the value of the namespace node corresponding to the specified local name. /// Always returns string.Empty for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns> public override string GetNamespace(string name) { InternalTrace("name=" + name); return string.Empty; } /// <summary> /// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator that you want to compare against.</param> /// <returns>true if the two navigators have the same position, otherwise, false.</returns> public override bool IsSamePosition(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false"); return false; } InternalTrace(">" + (nav._currentnode == _currentnode)); return (nav._currentnode == _currentnode); } /// <summary> /// Moves to the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param> /// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveTo(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false (nav is not an HtmlNodeNavigator)"); return false; } InternalTrace("moveto oid=" + nav.GetHashCode() + ", n:" + nav._currentnode.Name + ", a:" + nav._attindex); if (nav._doc == _doc) { _currentnode = nav._currentnode; _attindex = nav._attindex; InternalTrace(">true"); return true; } // we don't know how to handle that InternalTrace(">false (???)"); return false; } /// <summary> /// Moves to the HTML attribute with matching LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns> public override bool MoveToAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); int index = _currentnode.Attributes.GetAttributeIndex(localName); if (index == -1) { InternalTrace(">false"); return false; } _attindex = index; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToFirst() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } if (_currentnode.ParentNode.FirstChild == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode.FirstChild; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first HTML attribute. /// </summary> /// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns> public override bool MoveToFirstAttribute() { if (!HasAttributes) { InternalTrace(">false"); return false; } _attindex = 0; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first child of the current node. /// </summary> /// <returns>true if there is a first child node, otherwise false.</returns> public override bool MoveToFirstChild() { if (!_currentnode.HasChildNodes) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ChildNodes[0]; InternalTrace(">true"); return true; } /// <summary> /// Moves the XPathNavigator to the first namespace node of the current element. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Moves to the node that has an attribute of type ID whose value matches the specified string. /// </summary> /// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param> /// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveToId(string id) { InternalTrace("id=" + id); HtmlNode node = _doc.GetElementbyId(id); if (node == null) { InternalTrace(">false"); return false; } _currentnode = node; InternalTrace(">true"); return true; } /// <summary> /// Moves the XPathNavigator to the namespace node with the specified local name. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNamespace(string name) { InternalTrace("name=" + name); return false; } /// <summary> /// Moves to the next sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns> public override bool MoveToNext() { if (_currentnode.NextSibling == null) { InternalTrace(">false"); return false; } InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml); InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml); _currentnode = _currentnode.NextSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the next HTML attribute. /// </summary> /// <returns></returns> public override bool MoveToNextAttribute() { InternalTrace(null); if (_attindex >= (_currentnode.Attributes.Count - 1)) { InternalTrace(">false"); return false; } _attindex++; InternalTrace(">true"); return true; } /// <summary> /// Moves the XPathNavigator to the next namespace node. /// Always returns falsefor the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Moves to the parent of the current node. /// </summary> /// <returns>true if there is a parent node, otherwise false.</returns> public override bool MoveToParent() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode; InternalTrace(">true"); return true; } /// <summary> /// Moves to the previous sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToPrevious() { if (_currentnode.PreviousSibling == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.PreviousSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the root node to which the current node belongs. /// </summary> public override void MoveToRoot() { _currentnode = _doc.DocumentNode; InternalTrace(null); } #endregion #region Internal Methods [Conditional("TRACE")] internal void InternalTrace(object traceValue) { if (!Trace) { return; } StackFrame sf = new StackFrame(1, true); string name = sf.GetMethod().Name; string nodename = _currentnode == null ? "(null)" : _currentnode.Name; string nodevalue; if (_currentnode == null) { nodevalue = "(null)"; } else { switch (_currentnode.NodeType) { case HtmlNodeType.Comment: nodevalue = ((HtmlCommentNode) _currentnode).Comment; break; case HtmlNodeType.Document: nodevalue = ""; break; case HtmlNodeType.Text: nodevalue = ((HtmlTextNode) _currentnode).Text; break; default: nodevalue = _currentnode.CloneNode(false).OuterHtml; break; } } System.Diagnostics.Trace.WriteLine(string.Format("oid={0},n={1},a={2},v={3},{4}", GetHashCode(), nodename, _attindex, nodevalue, traceValue), "N!" + name); } #endregion #region Private Methods private void Reset() { InternalTrace(null); _currentnode = _doc.DocumentNode; _attindex = -1; } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.FileUploadWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.NetworkInformation { public enum DuplicateAddressDetectionState { Invalid = 0, Tentative = 1, Duplicate = 2, Deprecated = 3, Preferred = 4, } public abstract partial class GatewayIPAddressInformation { protected GatewayIPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } } public partial class GatewayIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.IEnumerable { protected internal GatewayIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.GatewayIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.GatewayIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.GatewayIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class IcmpV4Statistics { protected IcmpV4Statistics() { } public abstract long AddressMaskRepliesReceived { get; } public abstract long AddressMaskRepliesSent { get; } public abstract long AddressMaskRequestsReceived { get; } public abstract long AddressMaskRequestsSent { get; } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long SourceQuenchesReceived { get; } public abstract long SourceQuenchesSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } public abstract long TimestampRepliesReceived { get; } public abstract long TimestampRepliesSent { get; } public abstract long TimestampRequestsReceived { get; } public abstract long TimestampRequestsSent { get; } } public abstract partial class IcmpV6Statistics { protected IcmpV6Statistics() { } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MembershipQueriesReceived { get; } public abstract long MembershipQueriesSent { get; } public abstract long MembershipReductionsReceived { get; } public abstract long MembershipReductionsSent { get; } public abstract long MembershipReportsReceived { get; } public abstract long MembershipReportsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long NeighborAdvertisementsReceived { get; } public abstract long NeighborAdvertisementsSent { get; } public abstract long NeighborSolicitsReceived { get; } public abstract long NeighborSolicitsSent { get; } public abstract long PacketTooBigMessagesReceived { get; } public abstract long PacketTooBigMessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long RouterAdvertisementsReceived { get; } public abstract long RouterAdvertisementsSent { get; } public abstract long RouterSolicitsReceived { get; } public abstract long RouterSolicitsSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } } public abstract partial class IPAddressInformation { protected IPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } public abstract bool IsDnsEligible { get; } public abstract bool IsTransient { get; } } public partial class IPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.IEnumerable { internal IPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.IPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.IPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.IPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.IPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class IPGlobalProperties { protected IPGlobalProperties() { } public abstract string DhcpScopeName { get; } public abstract string DomainName { get; } public abstract string HostName { get; } public abstract bool IsWinsProxy { get; } public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; } public virtual System.IAsyncResult BeginGetUnicastAddresses(System.AsyncCallback callback, object state) { throw null; } public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection EndGetUnicastAddresses(System.IAsyncResult asyncResult) { throw null; } public abstract System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections(); public abstract System.Net.IPEndPoint[] GetActiveTcpListeners(); public abstract System.Net.IPEndPoint[] GetActiveUdpListeners(); public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics(); public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics(); public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { throw null; } public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics(); public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics(); public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection GetUnicastAddresses() { throw null; } public virtual System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection> GetUnicastAddressesAsync() { throw null; } } public abstract partial class IPGlobalStatistics { protected IPGlobalStatistics() { } public abstract int DefaultTtl { get; } public abstract bool ForwardingEnabled { get; } public abstract int NumberOfInterfaces { get; } public abstract int NumberOfIPAddresses { get; } public abstract int NumberOfRoutes { get; } public abstract long OutputPacketRequests { get; } public abstract long OutputPacketRoutingDiscards { get; } public abstract long OutputPacketsDiscarded { get; } public abstract long OutputPacketsWithNoRoute { get; } public abstract long PacketFragmentFailures { get; } public abstract long PacketReassembliesRequired { get; } public abstract long PacketReassemblyFailures { get; } public abstract long PacketReassemblyTimeout { get; } public abstract long PacketsFragmented { get; } public abstract long PacketsReassembled { get; } public abstract long ReceivedPackets { get; } public abstract long ReceivedPacketsDelivered { get; } public abstract long ReceivedPacketsDiscarded { get; } public abstract long ReceivedPacketsForwarded { get; } public abstract long ReceivedPacketsWithAddressErrors { get; } public abstract long ReceivedPacketsWithHeadersErrors { get; } public abstract long ReceivedPacketsWithUnknownProtocol { get; } } public abstract partial class IPInterfaceProperties { protected IPInterfaceProperties() { } public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; } public abstract string DnsSuffix { get; } public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; } public abstract bool IsDnsEnabled { get; } public abstract bool IsDynamicDnsEnabled { get; } public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; } public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; } public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties(); public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties(); } public abstract partial class IPInterfaceStatistics { protected IPInterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv4InterfaceProperties { protected IPv4InterfaceProperties() { } public abstract int Index { get; } public abstract bool IsAutomaticPrivateAddressingActive { get; } public abstract bool IsAutomaticPrivateAddressingEnabled { get; } public abstract bool IsDhcpEnabled { get; } public abstract bool IsForwardingEnabled { get; } public abstract int Mtu { get; } public abstract bool UsesWins { get; } } public abstract partial class IPv4InterfaceStatistics { protected IPv4InterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv6InterfaceProperties { protected IPv6InterfaceProperties() { } public abstract int Index { get; } public abstract int Mtu { get; } public virtual long GetScopeId(System.Net.NetworkInformation.ScopeLevel scopeLevel) { throw null; } } public abstract partial class MulticastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected MulticastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class MulticastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.IEnumerable { protected internal MulticastIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.MulticastIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.MulticastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.MulticastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public enum NetBiosNodeType { Unknown = 0, Broadcast = 1, Peer2Peer = 2, Mixed = 4, Hybrid = 8, } public delegate void NetworkAddressChangedEventHandler(object sender, System.EventArgs e); public delegate void NetworkAvailabilityChangedEventHandler(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e); public partial class NetworkAvailabilityEventArgs : System.EventArgs { internal NetworkAvailabilityEventArgs() { } public bool IsAvailable { get { throw null; } } } public partial class NetworkChange { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public NetworkChange() { } public static event System.Net.NetworkInformation.NetworkAddressChangedEventHandler NetworkAddressChanged { add { } remove { } } public static event System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { } remove { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static void RegisterNetworkChange(System.Net.NetworkInformation.NetworkChange nc) { } } public partial class NetworkInformationException : System.ComponentModel.Win32Exception { public NetworkInformationException() { } public NetworkInformationException(int errorCode) { } protected NetworkInformationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public override int ErrorCode { get { throw null; } } } public abstract partial class NetworkInterface { protected NetworkInterface() { } public virtual string Description { get { throw null; } } public virtual string Id { get { throw null; } } public static int IPv6LoopbackInterfaceIndex { get { throw null; } } public virtual bool IsReceiveOnly { get { throw null; } } public static int LoopbackInterfaceIndex { get { throw null; } } public virtual string Name { get { throw null; } } public virtual System.Net.NetworkInformation.NetworkInterfaceType NetworkInterfaceType { get { throw null; } } public virtual System.Net.NetworkInformation.OperationalStatus OperationalStatus { get { throw null; } } public virtual long Speed { get { throw null; } } public virtual bool SupportsMulticast { get { throw null; } } public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { throw null; } public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { throw null; } public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { throw null; } public virtual System.Net.NetworkInformation.IPv4InterfaceStatistics GetIPv4Statistics() { throw null; } public static bool GetIsNetworkAvailable() { throw null; } public virtual System.Net.NetworkInformation.PhysicalAddress GetPhysicalAddress() { throw null; } public virtual bool Supports(System.Net.NetworkInformation.NetworkInterfaceComponent networkInterfaceComponent) { throw null; } } public enum NetworkInterfaceComponent { IPv4 = 0, IPv6 = 1, } public enum NetworkInterfaceType { Unknown = 1, Ethernet = 6, TokenRing = 9, Fddi = 15, BasicIsdn = 20, PrimaryIsdn = 21, Ppp = 23, Loopback = 24, Ethernet3Megabit = 26, Slip = 28, Atm = 37, GenericModem = 48, FastEthernetT = 62, Isdn = 63, FastEthernetFx = 69, Wireless80211 = 71, AsymmetricDsl = 94, RateAdaptDsl = 95, SymmetricDsl = 96, VeryHighSpeedDsl = 97, IPOverAtm = 114, GigabitEthernet = 117, Tunnel = 131, MultiRateSymmetricDsl = 143, HighPerformanceSerialBus = 144, Wman = 237, Wwanpp = 243, Wwanpp2 = 244, } public enum OperationalStatus { Up = 1, Down = 2, Testing = 3, Unknown = 4, Dormant = 5, NotPresent = 6, LowerLayerDown = 7, } public partial class PhysicalAddress { public static readonly System.Net.NetworkInformation.PhysicalAddress None; public PhysicalAddress(byte[] address) { } public override bool Equals(object comparand) { throw null; } public byte[] GetAddressBytes() { throw null; } public override int GetHashCode() { throw null; } public static System.Net.NetworkInformation.PhysicalAddress Parse(string address) { throw null; } public override string ToString() { throw null; } } public enum PrefixOrigin { Other = 0, Manual = 1, WellKnown = 2, Dhcp = 3, RouterAdvertisement = 4, } public enum ScopeLevel { None = 0, Interface = 1, Link = 2, Subnet = 3, Admin = 4, Site = 5, Organization = 8, Global = 14, } public enum SuffixOrigin { Other = 0, Manual = 1, WellKnown = 2, OriginDhcp = 3, LinkLayerAddress = 4, Random = 5, } public abstract partial class TcpConnectionInformation { protected TcpConnectionInformation() { } public abstract System.Net.IPEndPoint LocalEndPoint { get; } public abstract System.Net.IPEndPoint RemoteEndPoint { get; } public abstract System.Net.NetworkInformation.TcpState State { get; } } public enum TcpState { Unknown = 0, Closed = 1, Listen = 2, SynSent = 3, SynReceived = 4, Established = 5, FinWait1 = 6, FinWait2 = 7, CloseWait = 8, Closing = 9, LastAck = 10, TimeWait = 11, DeleteTcb = 12, } public abstract partial class TcpStatistics { protected TcpStatistics() { } public abstract long ConnectionsAccepted { get; } public abstract long ConnectionsInitiated { get; } public abstract long CumulativeConnections { get; } public abstract long CurrentConnections { get; } public abstract long ErrorsReceived { get; } public abstract long FailedConnectionAttempts { get; } public abstract long MaximumConnections { get; } public abstract long MaximumTransmissionTimeout { get; } public abstract long MinimumTransmissionTimeout { get; } public abstract long ResetConnections { get; } public abstract long ResetsSent { get; } public abstract long SegmentsReceived { get; } public abstract long SegmentsResent { get; } public abstract long SegmentsSent { get; } } public abstract partial class UdpStatistics { protected UdpStatistics() { } public abstract long DatagramsReceived { get; } public abstract long DatagramsSent { get; } public abstract long IncomingDatagramsDiscarded { get; } public abstract long IncomingDatagramsWithErrors { get; } public abstract int UdpListeners { get; } } public abstract partial class UnicastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected UnicastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.IPAddress IPv4Mask { get; } public virtual int PrefixLength { get { throw null; } } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class UnicastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.IEnumerable { protected internal UnicastIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.UnicastIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.UnicastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.UnicastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.General { [TestCategory("Elasticity"), TestCategory("Placement")] public class ElasticPlacementTests : TestClusterPerTest { private readonly List<IActivationCountBasedPlacementTestGrain> grains = new List<IActivationCountBasedPlacementTestGrain>(); private const int leavy = 300; private const int perSilo = 1000; protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.ApplyToAllNodes(nodeConfig => nodeConfig.LoadSheddingEnabled = true); }); builder.AddSiloBuilderConfigurator<SiloConfigurator>(); } private class SiloConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore") .AddMemoryGrainStorageAsDefault(); } } /// <summary> /// Test placement behaviour for newly added silos. The grain placement strategy should favor them /// until they reach a similar load as the other silos. /// </summary> [Fact, TestCategory("Functional")] public async Task ElasticityTest_CatchingUp() { logger.Info("\n\n\n----- Phase 1 -----\n\n"); AddTestGrains(perSilo).Wait(); AddTestGrains(perSilo).Wait(); var activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, leavy); SiloHandle silo3 = this.HostedCluster.StartAdditionalSilo(); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); logger.Info("\n\n\n----- Phase 2 -----\n\n"); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); logger.Info("-----------------------------------------------------------------"); activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); double expected = (6.0 * perSilo) / 3.0; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy); AssertIsInRange(activationCounts[silo3], expected, leavy); logger.Info("\n\n\n----- Phase 3 -----\n\n"); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); logger.Info("-----------------------------------------------------------------"); activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); expected = (9.0 * perSilo) / 3.0; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy); AssertIsInRange(activationCounts[silo3], expected, leavy); logger.Info("-----------------------------------------------------------------"); logger.Info("Test finished OK. Expected per silo = {0}", expected); } /// <summary> /// This evaluates the how the placement strategy behaves once silos are stopped: The strategy should /// balance the activations from the stopped silo evenly among the remaining silos. /// </summary> [Fact, TestCategory("Functional")] public async Task ElasticityTest_StoppingSilos() { List<SiloHandle> runtimes = await this.HostedCluster.StartAdditionalSilos(2); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); int stopLeavy = leavy; await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); var activationCounts = await GetPerSiloActivationCounts(); logger.Info("-----------------------------------------------------------------"); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, stopLeavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, stopLeavy); AssertIsInRange(activationCounts[runtimes[0]], perSilo, stopLeavy); AssertIsInRange(activationCounts[runtimes[1]], perSilo, stopLeavy); this.HostedCluster.StopSilo(runtimes[0]); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); await InvokeAllGrains(); activationCounts = await GetPerSiloActivationCounts(); logger.Info("-----------------------------------------------------------------"); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); double expected = perSilo * 1.33; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, stopLeavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, stopLeavy); AssertIsInRange(activationCounts[runtimes[1]], expected, stopLeavy); logger.Info("-----------------------------------------------------------------"); logger.Info("Test finished OK. Expected per silo = {0}", expected); } /// <summary> /// Do not place activation in case all silos are above 110 CPU utilization. /// </summary> [Fact, TestCategory("Functional")] public async Task ElasticityTest_AllSilosCPUTooHigh() { var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress); var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress); await taintedGrainPrimary.EnableOverloadDetection(false); await taintedGrainSecondary.EnableOverloadDetection(false); await taintedGrainPrimary.LatchCpuUsage(110.0f); await taintedGrainSecondary.LatchCpuUsage(110.0f); await Assert.ThrowsAsync<OrleansException>(() => this.AddTestGrains(1)); } /// <summary> /// Do not place activation in case all silos are above 110 CPU utilization or have overloaded flag set. /// </summary> [SkippableFact(Skip= "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_AllSilosOverloaded() { var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress); var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress); await taintedGrainPrimary.LatchCpuUsage(110.0f); await taintedGrainSecondary.LatchOverloaded(); // OrleansException or GateWayTooBusyException var exception = await Assert.ThrowsAnyAsync<Exception>(() => this.AddTestGrains(1)); Assert.True(exception is OrleansException || exception is GatewayTooBusyException); } [Fact, TestCategory("Functional")] public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo() { await ElasticityGrainPlacementTest( g => g.LatchOverloaded(), g => g.UnlatchOverloaded(), "LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo", "A grain instantiated with the load-aware placement strategy should not attempt to create activations on an overloaded silo."); } [Fact, TestCategory("Functional")] public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos() { // a CPU usage of 110% will disqualify a silo from getting new grains. const float undesirability = (float)110.0; await ElasticityGrainPlacementTest( g => g.LatchCpuUsage(undesirability), g => g.UnlatchCpuUsage(), "LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos", "A grain instantiated with the load-aware placement strategy should not attempt to create activations on a busy silo."); } private async Task<IPlacementTestGrain> GetGrainAtSilo(SiloAddress silo) { while (true) { IPlacementTestGrain grain = this.GrainFactory.GetGrain<IRandomPlacementTestGrain>(Guid.NewGuid()); SiloAddress address = await grain.GetLocation(); if (address.Equals(silo)) return grain; } } private static void AssertIsInRange(int actual, double expected, int leavy) { Assert.True(expected - leavy <= actual && actual <= expected + leavy, String.Format("Expecting a value in the range between {0} and {1}, but instead got {2} outside the range.", expected - leavy, expected + leavy, actual)); } private async Task ElasticityGrainPlacementTest( Func<IPlacementTestGrain, Task> taint, Func<IPlacementTestGrain, Task> restore, string name, string assertMsg) { await this.HostedCluster.WaitForLivenessToStabilizeAsync(); logger.Info("********************** Starting the test {0} ******************************", name); var taintedSilo = this.HostedCluster.StartAdditionalSilo(); const long sampleSize = 10; var taintedGrain = await GetGrainAtSilo(taintedSilo.SiloAddress); var testGrains = Enumerable.Range(0, (int)sampleSize). Select( n => this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid())); // make the grain's silo undesirable for new grains. taint(taintedGrain).Wait(); List<IPEndPoint> actual; try { actual = testGrains.Select( g => g.GetEndpoint().Result).ToList(); } finally { // i don't know if this necessary but to be safe, i'll restore the silo's desirability. logger.Info("********************** Finalizing the test {0} ******************************", name); restore(taintedGrain).Wait(); } var unexpected = taintedSilo.SiloAddress.Endpoint; Assert.True( actual.All( i => !i.Equals(unexpected)), assertMsg); } private Task AddTestGrains(int amount) { var promises = new List<Task>(); for (var i = 0; i < amount; i++) { IActivationCountBasedPlacementTestGrain grain = this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid()); this.grains.Add(grain); // Make sure we activate grain: promises.Add(grain.Nop()); } return Task.WhenAll(promises); } private Task InvokeAllGrains() { var promises = new List<Task>(); foreach (var grain in grains) { promises.Add(grain.Nop()); } return Task.WhenAll(promises); } private async Task<Dictionary<SiloHandle, int>> GetPerSiloActivationCounts() { string fullTypeName = "UnitTests.Grains.ActivationCountBasedPlacementTestGrain"; IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0); SimpleGrainStatistic[] stats = await mgmtGrain.GetSimpleGrainStatistics(); return this.HostedCluster.GetActiveSilos() .ToDictionary( s => s, s => stats .Where(stat => stat.SiloAddress.Equals(s.SiloAddress) && stat.GrainType == fullTypeName) .Select(stat => stat.ActivationCount).SingleOrDefault()); } private void LogCounts(Dictionary<SiloHandle, int> activationCounts) { var sb = new StringBuilder(); foreach (var silo in this.HostedCluster.GetActiveSilos()) { int count; activationCounts.TryGetValue(silo, out count); sb.AppendLine($"{silo.Name}.ActivationCount = {count}"); } logger.Info(sb.ToString()); } } }
// NVNC - .NET VNC Server Library // Copyright (C) 2014 T!T@N // // This file is a heavy modified version of RfbProtocol.cs from the // VncSharp project. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.IO; using System.Net; using System.Drawing; using System.Collections.Generic; using System.Threading; using System.Net.Sockets; using System.Security.Cryptography; using Nixxis.RfbServer.Encodings; namespace Nixxis.RfbServer { /// <summary> /// Contains methods and properties to handle all aspects of the RFB Protocol versions 3.3 - 3.8. /// </summary> public class RfbProtocol { /// <summary> /// RFB Encoding constants. /// </summary> public enum Encoding : int { //encodings RAW_ENCODING = 0, //working COPYRECT_ENCODING = 1, //working RRE_ENCODING = 2, //working CORRE_ENCODING = 4, //error HEXTILE_ENCODING = 5, //working ZRLE_ENCODING = 16, //working //pseudo-encodings ZLIB_ENCODING = 6, //working } /// <summary> /// Server to Client Message-Type constants. /// </summary> public enum ServerMessages : int { FRAMEBUFFER_UPDATE = 0, SET_COLOR_MAP_ENTRIES = 1, BELL = 2, SERVER_CUT_TEXT = 3, } /// <summary> /// Client to Server Message-Type constants. /// </summary> public enum ClientMessages : byte { SET_PIXEL_FORMAT = 0, READ_COLOR_MAP_ENTRIES = 1, SET_ENCODINGS = 2, FRAMEBUFFER_UPDATE_REQUEST = 3, KEY_EVENT = 4, POINTER_EVENT = 5, CLIENT_CUT_TEXT = 6, } //Version numbers protected int verMajor = 3; // Major version of Protocol--probably 3 protected int verMinor = 8;//8; // Minor version of Protocol--probably 3, 7, or 8 //Shared flag private bool _shared; public bool Shared { get { return _shared; } set { _shared = value; } } public string CutText; protected Socket localClient; // Network object used to communicate with host protected TcpListener serverSocket; protected NetworkStream stream; // Stream object used to send/receive data protected BinaryReader reader; // Integral rather than Byte values are typically protected BinaryWriter writer; // sent and received, so these handle this. protected ZlibCompressedWriter zlibWriter; //The Zlib Stream Writer used for Zlib and ZRLE encodings public bool isRunning; public bool isConnected { get { return localClient.Connected; } } //Port property private int _port; public int Port { get { return _port; } set { _port = value; } } public string DisplayName; private List<Socket> clients = new List<Socket>(); public List<Socket> Clients { get { return clients; } } //Supported encodings private uint[] _encodings; public uint[] Encodings { get { return _encodings; } } /// <summary> /// Gets the best encoding from the ones the client sent. /// </summary> /// <returns>Returns a enum representation of the encoding.</returns> public Encoding GetPreferredEncoding() { Encoding prefEnc = Encoding.ZRLE_ENCODING; try { for (int i = 0; i < Encodings.Length; i++) if (((Encoding)Encodings[i]) == prefEnc) return prefEnc; } catch { prefEnc = Encoding.ZLIB_ENCODING; } return prefEnc; } public RfbProtocol(int port, string displayname) { Port = port; DisplayName = displayname; //Start(); } /// <summary> /// Gets the Protocol Version of the remote VNC Host--probably 3.3, 3.7, or 3.8. /// </summary> /// <returns>Returns a float representation of the protocol version that the server is using.</returns> public float ServerVersion { get { return (float)verMajor + (verMinor * 0.1f); } } public ZlibCompressedWriter ZlibWriter { get { return zlibWriter; } } /// <summary> /// The main server loop. Listening on the selected port occurs here, and accepting incoming connections /// </summary> public void Start() { isRunning = true; try { serverSocket = new TcpListener(IPAddress.Any, Port); serverSocket.Server.NoDelay = true; serverSocket.Start(); System.Diagnostics.Trace.WriteLine(string.Format("Listening started"), "VNCServer"); } //The port is being used, and serverSocket cannot start catch (Exception ex) { Console.WriteLine(ex.ToString()); return; } try { localClient = serverSocket.AcceptSocket(); localClient.NoDelay = true; //Disable the Naggle algorithm IPAddress localIP = IPAddress.Parse(((IPEndPoint)localClient.RemoteEndPoint).Address.ToString()); Console.WriteLine(localIP); stream = new NetworkStream(localClient, true); reader = new BigEndianBinaryReader(stream); writer = new BigEndianBinaryWriter(stream); zlibWriter = new ZlibCompressedWriter(stream); clients.Add(localClient); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } /// <summary> /// Reads VNC Protocol Version message (see RFB Doc v. 3.8 section 6.1.1) /// </summary> /// <exception cref="NotSupportedException">Thrown if the version of the protocol is not known or supported.</exception> public void ReadProtocolVersion() { try { byte[] b = reader.ReadBytes(12); // As of the time of writing, the only supported versions are 3.3, 3.7, and 3.8. if (b[0] == 0x52 && // R b[1] == 0x46 && // F b[2] == 0x42 && // B b[3] == 0x20 && // (space) b[4] == 0x30 && // 0 b[5] == 0x30 && // 0 b[6] == 0x33 && // 3 b[7] == 0x2e && // . (b[8] == 0x30 || // 0 b[8] == 0x38) && // BUG FIX: Apple reports 8 (b[9] == 0x30 || // 0 b[9] == 0x38) && // BUG FIX: Apple reports 8 (b[10] == 0x33 || // 3, 7, OR 8 are all valid and possible b[10] == 0x36 || // BUG FIX: UltraVNC reports protocol version 3.6! b[10] == 0x37 || b[10] == 0x38 || b[10] == 0x39) && // BUG FIX: Apple reports 9 b[11] == 0x0a) // \n { // Since we only currently support the 3.x protocols, this can be assumed here. // If and when 4.x comes out, this will need to be fixed--however, the entire // protocol will need to be updated then anyway :) verMajor = 3; // Figure out which version of the protocol this is: switch (b[10]) { case 0x33: case 0x36: // BUG FIX: pass 3.3 for 3.6 to allow UltraVNC to work, thanks to Steve Bostedor. verMinor = 3; break; case 0x37: verMinor = 7; break; case 0x38: verMinor = 8; break; case 0x39: // BUG FIX: Apple reports 3.889 // According to the RealVNC mailing list, Apple is really using 3.3 // (see http://www.mail-archive.com/vnc-list@realvnc.com/msg23615.html). I've tested with // both 3.3 and 3.8, and they both seem to work (I obviously haven't hit the issues others have). // Because 3.8 seems to work, I'm leaving that, but it might be necessary to use 3.3 in future. verMinor = 8; break; } } else { throw new NotSupportedException("Only versions 3.3, 3.7, and 3.8 of the RFB Protocol are supported."); } } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Sends the Protocol Version supported by the server. Will be highest supported by client (see RFB Doc v. 3.8 section 6.1.1). /// </summary> public void WriteProtocolVersion() { try { // We will use which ever version the server understands, be it 3.3, 3.7, or 3.8. System.Diagnostics.Debug.Assert(verMinor == 3 || verMinor == 7 || verMinor == 8, "Wrong Protocol Version!", string.Format("Protocol Version should be 3.3, 3.7, or 3.8 but is {0}.{1}", verMajor.ToString(), verMinor.ToString())); writer.Write(GetBytes(string.Format("RFB 003.00{0}\n", verMinor.ToString()))); writer.Flush(); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Closes the active connection and stops the VNC Server. /// </summary> public void Close() { isRunning = false; try { if (serverSocket != null) { serverSocket.Stop(); System.Diagnostics.Trace.WriteLine(string.Format("Listening stopped"), "VNCServer"); serverSocket = null; } localClient.Close(); // localClient.Disconnect(true); } catch { } } /// <summary> /// Converts the VNC password to a byte array. /// </summary> /// <param name="password">The VNC password as a String, to be converted to bytes.</param> /// <returns>Returns a byte array of the password.</returns> private byte[] PasswordToKey(string password) { byte[] key = new byte[8]; // Key limited to 8 bytes max. if (password.Length >= 8) { System.Text.Encoding.ASCII.GetBytes(password, 0, 8, key, 0); } else { System.Text.Encoding.ASCII.GetBytes(password, 0, password.Length, key, 0); } // VNC uses reverse byte order in key for (int i = 0; i < 8; i++) key[i] = (byte)(((key[i] & 0x01) << 7) | ((key[i] & 0x02) << 5) | ((key[i] & 0x04) << 3) | ((key[i] & 0x08) << 1) | ((key[i] & 0x10) >> 1) | ((key[i] & 0x20) >> 3) | ((key[i] & 0x40) >> 5) | ((key[i] & 0x80) >> 7)); return key; } /// <summary> /// If the password is not empty, perform VNC Authentication with it. /// </summary> /// <param name="password">The current VNC Password</param> /// <returns>Returns a boolean value representing successful authentication or not.</returns> public bool WriteAuthentication(string password) { // Indicate to the client which type of authentication will be used. //The type of Authentication to be used, 1 (None) or 2 (VNC Authentication). if (String.IsNullOrEmpty(password)) { // Protocol Version 3.7 onward supports multiple security types, while 3.3 only 1 if (verMinor == 3) { WriteUint32(1); } else { byte[] types = new byte[] { 1 }; writer.Write((byte)types.Length); for (int i = 0; i < types.Length; i++ ) writer.Write(types[i]); } if (verMinor >= 7) reader.ReadByte(); if(verMinor == 8) WriteSecurityResult(0); return true; } else { if (verMinor == 3) { WriteUint32(2); } else { byte[] types = new byte[] { 2 }; writer.Write((byte)types.Length); for (int i = 0; i < types.Length; i++) writer.Write(types[i]); } if (verMinor >= 7) reader.ReadByte(); //A random 16 byte challenge byte[] bChallenge = new byte[16]; Random rand = new Random(System.DateTime.Now.Millisecond); rand.NextBytes(bChallenge); // send the bytes to the client and wait for the response writer.Write(bChallenge); writer.Flush(); byte[] receivedBytes = reader.ReadBytes(16); byte[] key = PasswordToKey(password); DES des = new DESCryptoServiceProvider(); des.Padding = PaddingMode.None; des.Mode = CipherMode.ECB; ICryptoTransform enc = des.CreateEncryptor(key, null); byte[] ourBytes = new byte[16]; enc.TransformBlock(bChallenge, 0, bChallenge.Length, ourBytes, 0); /* Console.WriteLine("Us: " + System.Text.Encoding.ASCII.GetString(ourBytes)); Console.WriteLine("Client sent us: " + System.Text.Encoding.ASCII.GetString(receivedBytes)); */ bool authOK = true; for (int i = 0; i < ourBytes.Length; i++) if (receivedBytes[i] != ourBytes[i]) authOK = false; if (authOK) { WriteSecurityResult(0); return true; } else { WriteSecurityResult(1); if (verMinor == 8) { string ErrorMsg = "Wrong password, sorry"; WriteUint32((uint)ErrorMsg.Length); writer.Write(GetBytes(ErrorMsg)); } return false; } } } /// <summary> /// When the client uses VNC Authentication, after the Challege/Response, a status code is sent to indicate whether authentication worked. /// </summary> /// <param name="sr">An unsigned integer indicating the status of authentication: 0 = OK; 1 = Failed; 2 = Too Many (deprecated).</return public void WriteSecurityResult(uint sr) { writer.Write(sr); } /// <summary> /// Receives an Initialisation message from the client. /// </summary> /// <returns>True if the server allows other clients to connect, otherwise False.</returns> public bool ReadClientInit() { bool sh = false; try { this.Shared = (reader.ReadByte() == 1); sh = this.Shared; return Shared; } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); } return sh; } /// <summary> /// Writes the server's Initialization message, specifically the Framebuffer's properties. /// </summary> /// <param name="fb">The framebuffer that is sent.</param> public void WriteServerInit(Framebuffer fb) { try { writer.Write(Convert.ToUInt16(fb.Width)); writer.Write(Convert.ToUInt16(fb.Height)); writer.Write(fb.ToPixelFormat()); writer.Write(Convert.ToUInt32(fb.DesktopName.Length)); writer.Write(GetBytes(fb.DesktopName)); writer.Flush(); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Receives the format to be used when sending Framebuffer Updates. /// </summary> /// <returns>A Framebuffer telling the server how to encode pixel data. Typically this will be the same one sent by the server during initialization.</returns> public Framebuffer ReadSetPixelFormat(int w, int h) { Framebuffer ret = null; try { ReadPadding(3); byte[] pf = ReadBytes(16); ret = Framebuffer.FromPixelFormat(pf, w, h); return ret; } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); } return ret; } /// <summary> /// Reads the supported encodings from the client. /// </summary> public void ReadSetEncodings() { try { ReadPadding(1); ushort len = reader.ReadUInt16(); uint[] enc = new uint[(Int32)len]; for (int i = 0; i < (Int32)len; i++) enc[i] = reader.ReadUInt32(); _encodings = enc; } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Reads a request for an update of the area specified by (x, y, w, h). /// <param name="fb">The server's current Framebuffer.</param> /// </summary> public void ReadFrameBufferUpdateRequest(Framebuffer fb) { try { bool incremental = Convert.ToBoolean((int)(reader.ReadByte())); ushort x = reader.ReadUInt16(); ushort y = reader.ReadUInt16(); ushort width = reader.ReadUInt16(); ushort height = reader.ReadUInt16(); DoFrameBufferUpdate(fb, incremental, x, y, width, height); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } private int[] LastRectBackup = null; /// <summary> /// Creates the encoded pixel data in a form of an EncodedRectangle with the preferred encoding. /// </summary> private void DoFrameBufferUpdate(Framebuffer fb, bool incremental, int x, int y, int width, int height) { Console.WriteLine("X: " + x + " Y: " + y + " W: " + fb.Width + " H: " + fb.Height); int w = fb.Width; int h = fb.Height; if ((x < 0) || (y < 0) || (width <= 0) || (height <= 0)) { Console.WriteLine("Neg:" + x + ":" + y + ":" + width + ":" + height); return; } if (x + width > w) { Console.WriteLine("Too wide"); return; } if (y + height > h) { Console.WriteLine("Too high"); return; } Console.WriteLine("Bounds OK!"); List<EncodedRectangle> lst = new List<EncodedRectangle>(); try { System.Diagnostics.Stopwatch tip = System.Diagnostics.Stopwatch.StartNew(); EncodedRectangleFactory factory = new EncodedRectangleFactory(this, fb); EncodedRectangle localRect = factory.Build(new Rectangle(x,y,width, height), GetPreferredEncoding()); EncodedRectangle[] diffs = null; int[] backup = localRect.GetCopy(); if(incremental) { System.Diagnostics.Trace.WriteLine("Incremental requested"); if (LastRectBackup != null ) { diffs = localRect.ComputeChanges(LastRectBackup); } } LastRectBackup = backup; if (diffs != null) { foreach (EncodedRectangle er in diffs) { er.Encode(); lst.Add(er); } } else { localRect.Encode(); lst.Add(localRect); } Console.WriteLine("Encoding took: " + tip.Elapsed); } catch (Exception localException) { Console.WriteLine(localException.StackTrace.ToString()); if (localException is IOException) { this.Close(); return; } } if (lst.Count != 0) WriteFrameBufferUpdate(lst.ToArray()); } /// <summary> /// Writes the number of update rectangles being sent to the client. /// After that, for each rectangle, the encoded data is sent. /// </summary> public void WriteFrameBufferUpdate(EncodedRectangle[] arrRectangles) { System.Diagnostics.Stopwatch Watch = System.Diagnostics.Stopwatch.StartNew(); try { WriteServerMessageType(RfbProtocol.ServerMessages.FRAMEBUFFER_UPDATE); WritePadding(1); writer.Write(Convert.ToUInt16(arrRectangles.Length)); foreach (EncodedRectangle e in arrRectangles) e.WriteData(); writer.Flush(); Watch.Stop(); Console.WriteLine("Sending took: " + Watch.Elapsed); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Receives a key press or release event from the client. /// </summary> public void ReadKeyEvent() { try { bool pressed = (reader.ReadByte() == 1); ReadPadding(2); uint keysym = reader.ReadUInt32(); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Receives a mouse movement or button press/release from the client. /// </summary> public void ReadPointerEvent() { try { byte buttonMask = reader.ReadByte(); ushort X = reader.ReadUInt16(); ushort Y = reader.ReadUInt16(); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Receives the clipboard data from the client. /// </summary> public void ReadClientCutText() { try { ReadPadding(3); int len = Convert.ToInt32(reader.ReadUInt32()); string text = GetString(reader.ReadBytes(len)); CutText = text; System.Windows.Forms.Clipboard.SetDataObject(text.Replace("\n", Environment.NewLine), true); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Reads the type of message being sent by the client--all messages are prefixed with a message type. /// </summary> /// <returns>Returns the message type as an integer.</returns> public ClientMessages ReadServerMessageType() { byte x = 0; try { x = Convert.ToByte((int)reader.ReadByte()); return (ClientMessages)x; } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); } return (ClientMessages)x; } /// <summary> /// Writes the type of message being sent to the client--all messages are prefixed with a message type. /// </summary> private void WriteServerMessageType(RfbProtocol.ServerMessages message) { try { writer.Write(Convert.ToByte(message)); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } // TODO: this color map code should probably go in Framebuffer.cs private ushort[,] mapEntries = new ushort[256, 3]; public ushort[,] MapEntries { get { return mapEntries; } } /// <summary> /// Reads 8-bit RGB color values (or updated values) into the color map. /// </summary> public void ReadColorMapEntry() { ReadPadding(1); ushort firstColor = ReadUInt16(); ushort nbColors = ReadUInt16(); for (int i = 0; i < nbColors; i++, firstColor++) { mapEntries[firstColor, 0] = (byte)(ReadUInt16() * byte.MaxValue / ushort.MaxValue); // R mapEntries[firstColor, 1] = (byte)(ReadUInt16() * byte.MaxValue / ushort.MaxValue); // G mapEntries[firstColor, 2] = (byte)(ReadUInt16() * byte.MaxValue / ushort.MaxValue); // B } } /// <summary> /// Writes 8-bit RGB color values (or updated values) from the color map. /// </summary> public void WriteColorMapEntry(ushort firstColor, System.Drawing.Color[] colors) { try { WriteServerMessageType(ServerMessages.SET_COLOR_MAP_ENTRIES); WritePadding(1); writer.Write(firstColor); writer.Write((ushort)colors.Length); for (int i = 0; i < colors.Length; i++) { writer.Write((ushort)colors[i].R); writer.Write((ushort)colors[i].G); writer.Write((ushort)colors[i].B); } writer.Flush(); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } /// <summary> /// Writes the text from the Cut Buffer on the server. /// </summary> public void WriteServerCutText(String text) { try { WriteServerMessageType(ServerMessages.SERVER_CUT_TEXT); WritePadding(3); writer.Write((uint)text.Length); writer.Write(GetBytes(text)); writer.Flush(); } catch (IOException ex) { Console.WriteLine(ex.Message); this.Close(); return; } } // --------------------------------------------------------------------------------------- // Here's all the "low-level" protocol stuff so user objects can access the data directly /// <summary> /// Reads a single UInt32 value from the server, taking care of Big- to Little-Endian conversion. /// </summary> /// <returns>Returns a UInt32 value.</returns> public uint ReadUint32() { return reader.ReadUInt32(); } /// <summary> /// Reads a single UInt16 value from the server, taking care of Big- to Little-Endian conversion. /// </summary> /// <returns>Returns a UInt16 value.</returns> public ushort ReadUInt16() { return reader.ReadUInt16(); } /// <summary> /// Reads a single Byte value from the server. /// </summary> /// <returns>Returns a Byte value.</returns> public byte ReadByte() { return reader.ReadByte(); } /// <summary> /// Reads the specified number of bytes from the server, taking care of Big- to Little-Endian conversion. /// </summary> /// <param name="count">The number of bytes to be read.</param> /// <returns>Returns a Byte Array containing the values read.</returns> public byte[] ReadBytes(int count) { return reader.ReadBytes(count); } /// <summary> /// Writes a single UInt32 value to the server, taking care of Little- to Big-Endian conversion. /// </summary> /// <param name="value">The UInt32 value to be written.</param> public void WriteUint32(uint value) { writer.Write(value); } /// <summary> /// Writes a single unsigned short value to the server, taking care of Little- to Big-Endian conversion. /// </summary> /// <param name="value">The UInt16 value to be written.</param> public void WriteUInt16(ushort value) { writer.Write(value); } /// <summary> /// Writes a single unsigned integer value to the server, taking care of Little-to Big-Endian conversion. /// </summary> /// <param name="value">The UInt32 value to be written.</param> public void WriteUInt32(uint value) { writer.Write(value); } /// <summary> /// Writes a single Byte value to the server. /// </summary> /// <param name="value">The UInt32 value to be written.</param> public void WriteByte(byte value) { writer.Write(value); } /// <summary> /// Writes a byte array to the server. /// </summary> /// <param name="value">The byte array to be written.</param> public void Write(byte[] buffer) { writer.Write(buffer); } /// <summary> /// Reads the specified number of bytes of padding (i.e., garbage bytes) from the server. /// </summary> /// <param name="length">The number of bytes of padding to read.</param> public void ReadPadding(int length) { ReadBytes(length); } /// <summary> /// Writes the specified number of bytes of padding (i.e., garbage bytes) to the server. /// </summary> /// <param name="length">The number of bytes of padding to write.</param> public void WritePadding(int length) { byte[] padding = new byte[length]; writer.Write(padding, 0, padding.Length); } /// <summary> /// Converts a string to bytes for transfer to the server. /// </summary> /// <param name="text">The text to be converted to bytes.</param> /// <returns>Returns a Byte Array containing the text as bytes.</returns> protected static byte[] GetBytes(string text) { return System.Text.Encoding.ASCII.GetBytes(text); } /// <summary> /// Converts a series of bytes to a string. /// </summary> /// <param name="bytes">The Array of Bytes to be converted to a string.</param> /// <returns>Returns a String representation of bytes.</returns> protected static string GetString(byte[] bytes) { return System.Text.ASCIIEncoding.UTF8.GetString(bytes, 0, bytes.Length); } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using Shouldly.Configuration; namespace Shouldly { class ObsoleteMessages { public const string FuncCustomMessage = "Func based customMessage overloads have been removed. Pass in a string for the cusomMessage."; public const string DiffMessage = @"Diff tool management is now handled by https://github.com/VerifyTests/DiffEngine. Use the following for custom diff configuration. * Add a custom tool using `DiffTools.AddTool()`. https://github.com/VerifyTests/DiffEngine/blob/master/docs/diff-tool.custom.md. * Specify a custom order using a `DiffEngine.ToolOrder` environment variable (comma or pipe seperated), or use `DiffTools.UseOrder`. https://github.com/VerifyTests/DiffEngine/blob/master/docs/diff-tool.order.md#custom-order. * Disable all diffs by setting an environment variable `DiffEngine.Disabled` with the value `true`. https://github.com/VerifyTests/DiffEngine#disable-for-a-machineprocess. Diff launching can be controlled at the test level using `ShouldMatchConfiguration.PreventDiff`."; } public static partial class DynamicShould { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void HaveProperty(dynamic dynamicTestObject, string propertyName, Func<string?>? customMessage) { throw new NotImplementedException(); } } public static partial class ObjectGraphTestExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeEquivalentTo(this object? actual, object? expected, Func<string?>? customMessage) { throw new NotImplementedException(); } } public static partial class Should { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void CompleteIn(Action action, TimeSpan timeout, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void CompleteIn(Func<Task> actual, TimeSpan timeout, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void CompleteIn(Task actual, TimeSpan timeout, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T CompleteIn<T>(Func<Task<T>> actual, TimeSpan timeout, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T CompleteIn<T>(Func<T> function, TimeSpan timeout, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T CompleteIn<T>(Task<T> actual, TimeSpan timeout, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void NotThrow(Action action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void NotThrow(Func<Task> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void NotThrow(Task action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void NotThrow(Func<Task> action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void NotThrow(Task action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T NotThrow<T>(Func<Task<T>> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T NotThrow<T>(Func<T> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T NotThrow<T>(Task<T> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T NotThrow<T>(Func<Task<T>> action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T NotThrow<T>(Task<T> action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task NotThrowAsync(Func<Task> actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task NotThrowAsync(Task task, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception Throw(Action actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception Throw(Func<Task> actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception Throw(Func<object?> actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception Throw(Task actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception Throw(Func<Task> actual, TimeSpan timeoutAfter, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception Throw(Task actual, TimeSpan timeoutAfter, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException Throw<TException>(Action actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException Throw<TException>(Func<Task> actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException Throw<TException>(Func<object?> actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException Throw<TException>(Task actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException Throw<TException>(Func<Task> actual, TimeSpan timeoutAfter, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException Throw<TException>(Task actual, TimeSpan timeoutAfter, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<Exception> ThrowAsync(Func<Task> actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<Exception> ThrowAsync(Task task, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<TException> ThrowAsync<TException>(Func<Task> actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<TException> ThrowAsync<TException>(Task task, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } } public static partial class ShouldBeBooleanExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeFalse(this bool actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeTrue(this bool actual, Func<string?>? customMessage) { throw new NotImplementedException(); } } public static partial class ShouldBeDecoratedWithExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeDecoratedWith<T>(this Type actual, Func<string?>? customMessage) where T : Attribute { throw new NotImplementedException(); } } public static partial class ShouldBeDictionaryTestExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContainKey<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<string?>? customMessage) where TKey : notnull { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContainKeyAndValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue val, Func<string?>? customMessage) where TKey : notnull { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotContainKey<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<string?>? customMessage) where TKey : notnull { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotContainValueForKey<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue val, Func<string?>? customMessage) where TKey : notnull { throw new NotImplementedException(); } } public static partial class ShouldBeEnumerableTestExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldAllBe<T>(this IEnumerable<T> actual, Expression<Func<T, bool>> elementPredicate, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this IEnumerable<string> actual, IEnumerable<string> expected, Case caseSensitivity, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeEmpty<T>(this IEnumerable<T>? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeInOrder<T>(this IEnumerable<T> actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeInOrder<T>(this IEnumerable<T> actual, SortDirection expectedSortDirection, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeInOrder<T>(this IEnumerable<T> actual, SortDirection expectedSortDirection, IComparer<T>? customComparer, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeOfTypes<T>(this IEnumerable<T> actual, Type[] expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeSubsetOf<T>(this IEnumerable<T> actual, IEnumerable<T> expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeUnique<T>(this IEnumerable<T> actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContain(this IEnumerable<double> actual, double expected, double tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContain(this IEnumerable<float> actual, float expected, double tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContain<T>(this IEnumerable<T> actual, Expression<Func<T, bool>> elementPredicate, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContain<T>(this IEnumerable<T> actual, T expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContain<T>(this IEnumerable<T> actual, Expression<Func<T, bool>> elementPredicate, int expectedCount, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldHaveSingleItem<T>(this IEnumerable<T>? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeEmpty<T>(this IEnumerable<T>? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotContain<T>(this IEnumerable<T> actual, Expression<Func<T, bool>> elementPredicate, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotContain<T>(this IEnumerable<T> actual, T expected, Func<string?>? customMessage) { throw new NotImplementedException(); } } public static partial class ShouldBeNullExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNull<T>(this T? actual, Func<string?>? customMessage) where T : class { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeNull<T>(this T? actual, Func<string?>? customMessage) where T : class { throw new NotImplementedException(); } } public static partial class ShouldBeStringTestExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this string? actual, string? expected, Func<string?> customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this string? actual, string? expected, Func<string?> customMessage, StringCompareShould options) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNullOrEmpty(this string? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNullOrWhiteSpace(this string? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContain(this string actual, string expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContain(this string actual, string expected, Func<string?>? customMessage, Case caseSensitivity) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldContainWithoutWhitespace(this string actual, object? expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldEndWith(this string? actual, string expected, Func<string?>? customMessage, Case caseSensitivity = Case.Insensitive) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldMatch(this string actual, string regexPattern, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeNullOrEmpty(this string? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeNullOrWhiteSpace(this string? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotContain(this string actual, string expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotContain(this string actual, string expected, Func<string?>? customMessage, Case caseSensitivity) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotEndWith(this string? actual, string expected, Func<string?>? customMessage, Case caseSensitivity = Case.Insensitive) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotMatch(this string actual, string regexPattern, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotStartWith(this string? actual, string expected, Func<string?>? customMessage, Case caseSensitivity = Case.Insensitive) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldStartWith(this string? actual, string expected, Func<string?>? customMessage, Case caseSensitivity = Case.Insensitive) { throw new NotImplementedException(); } } public static partial class ShouldBeTestExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this IEnumerable<decimal> actual, IEnumerable<decimal> expected, decimal tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this IEnumerable<double> actual, IEnumerable<double> expected, double tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this IEnumerable<float> actual, IEnumerable<float> expected, double tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this DateTime actual, DateTime expected, TimeSpan tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this DateTimeOffset actual, DateTimeOffset expected, TimeSpan tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this TimeSpan actual, TimeSpan expected, TimeSpan tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this decimal actual, decimal expected, decimal tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this double actual, double expected, double tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe(this float actual, float expected, double tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe<T>(this T actual, T expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBe<T>(this IEnumerable<T>? actual, IEnumerable<T>? expected, bool ignoreOrder, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeAssignableTo(this object? actual, Type expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldBeAssignableTo<T>(this object? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeGreaterThan<T>(this T actual, T expected, Func<string?>? customMessage) where T : IComparable<T>? { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeGreaterThan<T>(this T actual, T expected, IComparer<T> comparer, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeGreaterThanOrEqualTo<T>(this T actual, T expected, Func<string?>? customMessage) where T : IComparable<T>? { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeGreaterThanOrEqualTo<T>(this T actual, T expected, IComparer<T> comparer, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeInRange<T>(this T actual, T from, T to, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeLessThan<T>(this T actual, T expected, Func<string?>? customMessage) where T : IComparable<T>? { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeLessThan<T>(this T actual, T expected, IComparer<T> comparer, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeLessThanOrEqualTo<T>(this T actual, T expected, Func<string?>? customMessage) where T : IComparable<T>? { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeLessThanOrEqualTo<T>(this T actual, T expected, IComparer<T> comparer, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNegative(this decimal actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNegative(this double actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNegative(this float actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNegative(this int actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNegative(this long actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeNegative(this short actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeOfType(this object? actual, Type expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldBeOfType<T>(this object? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeOneOf<T>(this T actual, T[] expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBePositive(this decimal actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBePositive(this double actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBePositive(this float actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBePositive(this int actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBePositive(this long actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBePositive(this short actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldBeSameAs(this object? actual, object? expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBe(this DateTime actual, DateTime expected, TimeSpan tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBe(this DateTimeOffset actual, DateTimeOffset expected, TimeSpan tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBe(this TimeSpan actual, TimeSpan expected, TimeSpan tolerance, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBe<T>(this T actual, T expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeAssignableTo(this object? actual, Type expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeAssignableTo<T>(this object? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeInRange<T>(this T actual, T from, T to, Func<string?>? customMessage) where T : IComparable<T> { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeOfType(this object? actual, Type expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeOfType<T>(this object? actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeOneOf<T>(this T actual, T[] expected, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotBeSameAs(this object? actual, object? expected, Func<string?>? customMessage) { throw new NotImplementedException(); } } public static partial class ShouldMatchApprovedTestExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldMatchApproved(this string actual, Func<string?> customMessage, Action<ShouldMatchConfigurationBuilder> configureOptions) { throw new NotImplementedException(); } } public static partial class ShouldNotThrowTaskAsyncExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task ShouldNotThrowAsync(this Func<Task> actual, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task ShouldNotThrowAsync(this Task task, Func<string?>? customMessage) { throw new NotImplementedException(); } } public static partial class ShouldSatisfyAllConditionsTestExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldSatisfyAllConditions(this object? actual, Func<string?>? customMessage, params Action[] conditions) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldSatisfyAllConditions<T>(this T actual, Func<string?>? customMessage, params Action<T>[] conditions) { throw new NotImplementedException(); } } public static partial class ShouldThrowAsyncExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<Exception> ShouldThrowAsync(this Func<Task> actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<Exception> ShouldThrowAsync(this Task task, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<TException> ShouldThrowAsync<TException>(this Func<Task> actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Task<TException> ShouldThrowAsync<TException>(this Task task, Func<string?>? customMessage) { throw new NotImplementedException(); } } public static partial class ShouldThrowExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotThrow(this Action action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldNotThrow<T>(this Func<T> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception ShouldThrow(this Action actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception ShouldThrow(this Func<object?> actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException ShouldThrow<TException>(this Action actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException ShouldThrow<TException>(this Func<object?> actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } } public static partial class ShouldThrowTaskExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotThrow(this Func<Task> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotThrow(this Task action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotThrow(this Func<Task> action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotThrow(this Task action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldNotThrow<T>(this Func<Task<T>> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldNotThrow<T>(this Task<T> action, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldNotThrow<T>(this Func<Task<T>> action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static T ShouldNotThrow<T>(this Task<T> action, TimeSpan timeoutAfter, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception ShouldThrow(this Func<Task> actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception ShouldThrow(this Task actual, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception ShouldThrow(this Func<Task> actual, TimeSpan timeoutAfter, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static Exception ShouldThrow(this Task actual, TimeSpan timeoutAfter, Func<string?>? customMessage, Type exceptionType) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException ShouldThrow<TException>(this Func<Task> actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException ShouldThrow<TException>(this Task actual, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException ShouldThrow<TException>(this Func<Task> actual, TimeSpan timeoutAfter, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static TException ShouldThrow<TException>(this Task actual, TimeSpan timeoutAfter, Func<string?>? customMessage) where TException : Exception { throw new NotImplementedException(); } } } namespace Shouldly.ShouldlyExtensionMethods { public static partial class ShouldHaveEnumExtensions { [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldHaveFlag(this Enum actual, Enum expectedFlag, Func<string?>? customMessage) { throw new NotImplementedException(); } [Obsolete(ObsoleteMessages.FuncCustomMessage, true)] public static void ShouldNotHaveFlag(this Enum actual, Enum expectedFlag, Func<string?>? customMessage) { throw new NotImplementedException(); } } } namespace Shouldly.Configuration { [Obsolete(ObsoleteMessages.DiffMessage, true)] public class DiffTool { } [Obsolete(ObsoleteMessages.DiffMessage, true)] public class DiffToolConfig { } [Obsolete(ObsoleteMessages.DiffMessage, true)] public class DiffToolConfiguration { } [Obsolete(ObsoleteMessages.DiffMessage, true)] public class DoNotLaunchWhenEnvVariableIsPresent { } [Obsolete(ObsoleteMessages.DiffMessage, true)] public class DoNotLaunchWhenPlatformIsNotWindows { } [Obsolete(ObsoleteMessages.DiffMessage, true)] public class DoNotLaunchWhenTypeIsLoaded { } [Obsolete(ObsoleteMessages.DiffMessage, true)] public class KnownDiffTools { } [Obsolete(ObsoleteMessages.DiffMessage, true)] public class KnownDoNotLaunchStrategies { } }
using System; using System.Collections; using System.Collections.Generic; using Server; using Server.Items; using Server.Guilds; using Server.Mobiles; using Server.Prompts; using Server.Targeting; using Server.Accounting; using Server.Commands; using Server.Commands.Generic; namespace Server.Factions { [CustomEnum( new string[]{ "Minax", "Council of Mages", "True Britannians", "Shadowlords" } )] public abstract class Faction : IComparable { public int ZeroRankOffset; private FactionDefinition m_Definition; private FactionState m_State; private StrongholdRegion m_StrongholdRegion; public StrongholdRegion StrongholdRegion { get{ return m_StrongholdRegion; } set{ m_StrongholdRegion = value; } } public FactionDefinition Definition { get{ return m_Definition; } set { m_Definition = value; m_StrongholdRegion = new StrongholdRegion( this ); } } public FactionState State { get{ return m_State; } set{ m_State = value; } } public Election Election { get{ return m_State.Election; } set{ m_State.Election = value; } } public Mobile Commander { get{ return m_State.Commander; } set{ m_State.Commander = value; } } public int Tithe { get{ return m_State.Tithe; } set{ m_State.Tithe = value; } } public int Silver { get{ return m_State.Silver; } set{ m_State.Silver = value; } } public List<PlayerState> Members { get{ return m_State.Members; } set{ m_State.Members = value; } } public static readonly TimeSpan LeavePeriod = TimeSpan.FromDays( 3.0 ); public bool FactionMessageReady { get{ return m_State.FactionMessageReady; } } public void Broadcast( string text ) { Broadcast( 0x3B2, text ); } public void Broadcast( int hue, string text ) { List<PlayerState> members = Members; for ( int i = 0; i < members.Count; ++i ) members[i].Mobile.SendMessage( hue, text ); } public void Broadcast( int number ) { List<PlayerState> members = Members; for ( int i = 0; i < members.Count; ++i ) members[i].Mobile.SendLocalizedMessage( number ); } public void Broadcast( string format, params object[] args ) { Broadcast( String.Format( format, args ) ); } public void Broadcast( int hue, string format, params object[] args ) { Broadcast( hue, String.Format( format, args ) ); } public void BeginBroadcast( Mobile from ) { from.SendLocalizedMessage( 1010265 ); // Enter Faction Message from.Prompt = new BroadcastPrompt( this ); } public void EndBroadcast( Mobile from, string text ) { if ( from.AccessLevel == AccessLevel.Player ) m_State.RegisterBroadcast(); Broadcast( Definition.HueBroadcast, "{0} [Commander] {1} : {2}", from.Name, Definition.FriendlyName, text ); } private class BroadcastPrompt : Prompt { private Faction m_Faction; public BroadcastPrompt( Faction faction ) { m_Faction = faction; } public override void OnResponse( Mobile from, string text ) { m_Faction.EndBroadcast( from, text ); } } public static void HandleAtrophy() { foreach ( Faction f in Factions ) { if ( !f.State.IsAtrophyReady ) return; } List<PlayerState> activePlayers = new List<PlayerState>(); foreach ( Faction f in Factions ) { foreach ( PlayerState ps in f.Members ) { if ( ps.KillPoints > 0 && ps.IsActive ) activePlayers.Add( ps ); } } int distrib = 0; foreach ( Faction f in Factions ) distrib += f.State.CheckAtrophy(); if ( activePlayers.Count == 0 ) return; for ( int i = 0; i < distrib; ++i ) activePlayers[Utility.Random( activePlayers.Count )].KillPoints++; } public static void DistributePoints( int distrib ) { List<PlayerState> activePlayers = new List<PlayerState>(); foreach ( Faction f in Factions ) { foreach ( PlayerState ps in f.Members ) { if ( ps.KillPoints > 0 && ps.IsActive ) { activePlayers.Add( ps ); } } } if ( activePlayers.Count > 0 ) { for ( int i = 0; i < distrib; ++i ) { activePlayers[Utility.Random( activePlayers.Count )].KillPoints++; } } } public void BeginHonorLeadership( Mobile from ) { from.SendLocalizedMessage( 502090 ); // Click on the player whom you wish to honor. from.BeginTarget( 12, false, TargetFlags.None, new TargetCallback( HonorLeadership_OnTarget ) ); } public void HonorLeadership_OnTarget( Mobile from, object obj ) { if ( obj is Mobile ) { Mobile recv = (Mobile) obj; PlayerState giveState = PlayerState.Find( from ); PlayerState recvState = PlayerState.Find( recv ); if ( giveState == null ) return; if ( recvState == null || recvState.Faction != giveState.Faction ) { from.SendLocalizedMessage( 1042497 ); // Only faction mates can be honored this way. } else if ( giveState.KillPoints < 5 ) { from.SendLocalizedMessage( 1042499 ); // You must have at least five kill points to honor them. } else { recvState.LastHonorTime = DateTime.Now; giveState.KillPoints -= 5; recvState.KillPoints += 4; // TODO: Confirm no message sent to giver recv.SendLocalizedMessage( 1042500 ); // You have been honored with four kill points. } } else { from.SendLocalizedMessage( 1042496 ); // You may only honor another player. } } public virtual void AddMember( Mobile mob ) { Members.Insert( ZeroRankOffset, new PlayerState( mob, this, Members ) ); mob.AddToBackpack( FactionItem.Imbue( new Robe(), this, false, Definition.HuePrimary ) ); mob.SendLocalizedMessage( 1010374 ); // You have been granted a robe which signifies your faction mob.InvalidateProperties(); mob.Delta( MobileDelta.Noto ); mob.FixedEffect( 0x373A, 10, 30 ); mob.PlaySound( 0x209 ); } public static bool IsNearType( Mobile mob, Type type, int range ) { bool mobs = type.IsSubclassOf( typeof( Mobile ) ); bool items = type.IsSubclassOf( typeof( Item ) ); IPooledEnumerable eable; if ( mobs ) eable = mob.GetMobilesInRange( range ); else if ( items ) eable = mob.GetItemsInRange( range ); else return false; foreach ( object obj in eable ) { if ( type.IsAssignableFrom( obj.GetType() ) ) { eable.Free(); return true; } } eable.Free(); return false; } public static bool IsNearType( Mobile mob, Type[] types, int range ) { IPooledEnumerable eable = mob.GetObjectsInRange( range ); foreach( object obj in eable ) { Type objType = obj.GetType(); for( int i = 0; i < types.Length; i++ ) { if( types[i].IsAssignableFrom( objType ) ) { eable.Free(); return true; } } } eable.Free(); return false; } public void RemovePlayerState( PlayerState pl ) { if ( pl == null || !Members.Contains( pl ) ) return; int killPoints = pl.KillPoints; if ( pl.RankIndex != -1 ) { while ( ( pl.RankIndex + 1 ) < ZeroRankOffset ) { PlayerState pNext = Members[pl.RankIndex+1] as PlayerState; Members[pl.RankIndex+1] = pl; Members[pl.RankIndex] = pNext; pl.RankIndex++; pNext.RankIndex--; } ZeroRankOffset--; } Members.Remove( pl ); PlayerMobile pm = (PlayerMobile)pl.Mobile; if ( pm == null ) return; Mobile mob = pl.Mobile; if ( pm.FactionPlayerState == pl ) { pm.FactionPlayerState = null; mob.InvalidateProperties(); mob.Delta( MobileDelta.Noto ); if ( Election.IsCandidate( mob ) ) Election.RemoveCandidate( mob ); if ( pl.Finance != null ) pl.Finance.Finance = null; if ( pl.Sheriff != null ) pl.Sheriff.Sheriff = null; Election.RemoveVoter( mob ); if ( Commander == mob ) Commander = null; pm.ValidateEquipment(); } if ( killPoints > 0 ) DistributePoints( killPoints ); } public void RemoveMember( Mobile mob ) { PlayerState pl = PlayerState.Find( mob ); if ( pl == null || !Members.Contains( pl ) ) return; int killPoints = pl.KillPoints; if( mob.Backpack != null ) { //Ordinarily, through normal faction removal, this will never find any sigils. //Only with a leave delay less than the ReturnPeriod or a Faction Kick/Ban, will this ever do anything Item[] sigils = mob.Backpack.FindItemsByType( typeof( Sigil ) ); for ( int i = 0; i < sigils.Length; ++i ) ((Sigil)sigils[i]).ReturnHome(); } if ( pl.RankIndex != -1 ) { while ( ( pl.RankIndex + 1 ) < ZeroRankOffset ) { PlayerState pNext = Members[pl.RankIndex+1]; Members[pl.RankIndex+1] = pl; Members[pl.RankIndex] = pNext; pl.RankIndex++; pNext.RankIndex--; } ZeroRankOffset--; } Members.Remove( pl ); if ( mob is PlayerMobile ) ((PlayerMobile)mob).FactionPlayerState = null; mob.InvalidateProperties(); mob.Delta( MobileDelta.Noto ); if ( Election.IsCandidate( mob ) ) Election.RemoveCandidate( mob ); Election.RemoveVoter( mob ); if ( pl.Finance != null ) pl.Finance.Finance = null; if ( pl.Sheriff != null ) pl.Sheriff.Sheriff = null; if ( Commander == mob ) Commander = null; if ( mob is PlayerMobile ) ((PlayerMobile)mob).ValidateEquipment(); if ( killPoints > 0 ) DistributePoints( killPoints ); } public void JoinGuilded( PlayerMobile mob, Guild guild ) { if ( mob.Young ) { guild.RemoveMember( mob ); mob.SendLocalizedMessage( 1042283 ); // You have been kicked out of your guild! Young players may not remain in a guild which is allied with a faction. } else if ( AlreadyHasCharInFaction( mob ) ) { guild.RemoveMember( mob ); mob.SendLocalizedMessage( 1005281 ); // You have been kicked out of your guild due to factional overlap } else if ( IsFactionBanned( mob ) ) { guild.RemoveMember( mob ); mob.SendLocalizedMessage( 1005052 ); // You are currently banned from the faction system } else { AddMember( mob ); mob.SendLocalizedMessage( 1042756, true, " " + m_Definition.FriendlyName ); // You are now joining a faction: } } public void JoinAlone( Mobile mob ) { AddMember( mob ); mob.SendLocalizedMessage( 1005058 ); // You have joined the faction } private bool AlreadyHasCharInFaction( Mobile mob ) { Account acct = mob.Account as Account; if ( acct != null ) { for ( int i = 0; i < acct.Length; ++i ) { Mobile c = acct[i]; if ( Find( c ) != null ) return true; } } return false; } public static bool IsFactionBanned( Mobile mob ) { Account acct = mob.Account as Account; if ( acct == null ) return false; return ( acct.GetTag( "FactionBanned" ) != null ); } public void OnJoinAccepted( Mobile mob ) { PlayerMobile pm = mob as PlayerMobile; if ( pm == null ) return; // sanity PlayerState pl = PlayerState.Find( pm ); if ( pm.Young ) pm.SendLocalizedMessage( 1010104 ); // You cannot join a faction as a young player else if ( pl != null && pl.IsLeaving ) pm.SendLocalizedMessage( 1005051 ); // You cannot use the faction stone until you have finished quitting your current faction else if ( AlreadyHasCharInFaction( pm ) ) pm.SendLocalizedMessage( 1005059 ); // You cannot join a faction because you already declared your allegiance with another character else if ( IsFactionBanned( mob ) ) pm.SendLocalizedMessage( 1005052 ); // You are currently banned from the faction system else if ( pm.Guild != null ) { Guild guild = pm.Guild as Guild; if ( guild.Leader != pm ) pm.SendLocalizedMessage( 1005057 ); // You cannot join a faction because you are in a guild and not the guildmaster else if (guild.Type != GuildType.Regular) pm.SendLocalizedMessage(1042161); // You cannot join a faction because your guild is an Order or Chaos type. else if ( !Guild.NewGuildSystem && guild.Enemies != null && guild.Enemies.Count > 0 ) //CAN join w/wars in new system pm.SendLocalizedMessage( 1005056 ); // You cannot join a faction with active Wars else if ( Guild.NewGuildSystem && guild.Alliance != null ) pm.SendLocalizedMessage( 1080454 ); // Your guild cannot join a faction while in alliance with non-factioned guilds. else if ( !CanHandleInflux( guild.Members.Count ) ) pm.SendLocalizedMessage( 1018031 ); // In the interest of faction stability, this faction declines to accept new members for now. else { List<Mobile> members = new List<Mobile>( guild.Members ); for ( int i = 0; i < members.Count; ++i ) { PlayerMobile member = members[i] as PlayerMobile; if ( member == null ) continue; JoinGuilded( member, guild ); } } } else if ( !CanHandleInflux( 1 ) ) { pm.SendLocalizedMessage( 1018031 ); // In the interest of faction stability, this faction declines to accept new members for now. } else { JoinAlone( mob ); } } public bool IsCommander( Mobile mob ) { if ( mob == null ) return false; return ( mob.AccessLevel >= AccessLevel.GameMaster || mob == Commander ); } public Faction() { m_State = new FactionState( this ); } public override string ToString() { return m_Definition.FriendlyName; } public int CompareTo( object obj ) { return m_Definition.Sort - ((Faction)obj).m_Definition.Sort; } public static bool CheckLeaveTimer( Mobile mob ) { PlayerState pl = PlayerState.Find( mob ); if ( pl == null || !pl.IsLeaving ) return false; if ( (pl.Leaving + LeavePeriod) >= DateTime.Now ) return false; mob.SendLocalizedMessage( 1005163 ); // You have now quit your faction pl.Faction.RemoveMember( mob ); return true; } public static void Initialize() { EventSink.Login += new LoginEventHandler( EventSink_Login ); EventSink.Logout += new LogoutEventHandler( EventSink_Logout ); Timer.DelayCall( TimeSpan.FromMinutes( 1.0 ), TimeSpan.FromMinutes( 10.0 ), new TimerCallback( HandleAtrophy ) ); Timer.DelayCall( TimeSpan.FromSeconds( 30.0 ), TimeSpan.FromSeconds( 30.0 ), new TimerCallback( ProcessTick ) ); CommandSystem.Register( "FactionElection", AccessLevel.GameMaster, new CommandEventHandler( FactionElection_OnCommand ) ); CommandSystem.Register( "FactionCommander", AccessLevel.Administrator, new CommandEventHandler( FactionCommander_OnCommand ) ); CommandSystem.Register( "FactionItemReset", AccessLevel.Administrator, new CommandEventHandler( FactionItemReset_OnCommand ) ); CommandSystem.Register( "FactionReset", AccessLevel.Administrator, new CommandEventHandler( FactionReset_OnCommand ) ); CommandSystem.Register( "FactionTownReset", AccessLevel.Administrator, new CommandEventHandler( FactionTownReset_OnCommand ) ); } public static void FactionTownReset_OnCommand( CommandEventArgs e ) { List<BaseMonolith> monoliths = BaseMonolith.Monoliths; for ( int i = 0; i < monoliths.Count; ++i ) monoliths[i].Sigil = null; List<Town> towns = Town.Towns; for ( int i = 0; i < towns.Count; ++i ) { towns[i].Silver = 0; towns[i].Sheriff = null; towns[i].Finance = null; towns[i].Tax = 0; towns[i].Owner = null; } List<Sigil> sigils = Sigil.Sigils; for ( int i = 0; i < sigils.Count; ++i ) { sigils[i].Corrupted = null; sigils[i].Corrupting = null; sigils[i].LastStolen = DateTime.MinValue; sigils[i].GraceStart = DateTime.MinValue; sigils[i].CorruptionStart = DateTime.MinValue; sigils[i].PurificationStart = DateTime.MinValue; sigils[i].LastMonolith = null; sigils[i].ReturnHome(); } List<Faction> factions = Faction.Factions; for ( int i = 0; i < factions.Count; ++i ) { Faction f = factions[i]; List<FactionItem> list = new List<FactionItem>( f.State.FactionItems ); for ( int j = 0; j < list.Count; ++j ) { FactionItem fi = list[j]; if ( fi.Expiration == DateTime.MinValue ) fi.Item.Delete(); else fi.Detach(); } } } public static void FactionReset_OnCommand( CommandEventArgs e ) { List<BaseMonolith> monoliths = BaseMonolith.Monoliths; for ( int i = 0; i < monoliths.Count; ++i ) monoliths[i].Sigil = null; List<Town> towns = Town.Towns; for ( int i = 0; i < towns.Count; ++i ) { towns[i].Silver = 0; towns[i].Sheriff = null; towns[i].Finance = null; towns[i].Tax = 0; towns[i].Owner = null; } List<Sigil> sigils = Sigil.Sigils; for ( int i = 0; i < sigils.Count; ++i ) { sigils[i].Corrupted = null; sigils[i].Corrupting = null; sigils[i].LastStolen = DateTime.MinValue; sigils[i].GraceStart = DateTime.MinValue; sigils[i].CorruptionStart = DateTime.MinValue; sigils[i].PurificationStart = DateTime.MinValue; sigils[i].LastMonolith = null; sigils[i].ReturnHome(); } List<Faction> factions = Faction.Factions; for ( int i = 0; i < factions.Count; ++i ) { Faction f = factions[i]; List<PlayerState> playerStateList = new List<PlayerState>( f.Members ); for( int j = 0; j < playerStateList.Count; ++j ) f.RemoveMember( playerStateList[j].Mobile ); List<FactionItem> factionItemList = new List<FactionItem>( f.State.FactionItems ); for( int j = 0; j < factionItemList.Count; ++j ) { FactionItem fi = (FactionItem)factionItemList[j]; if ( fi.Expiration == DateTime.MinValue ) fi.Item.Delete(); else fi.Detach(); } List<BaseFactionTrap> factionTrapList = new List<BaseFactionTrap>( f.Traps ); for( int j = 0; j < factionTrapList.Count; ++j ) factionTrapList[j].Delete(); } } public static void FactionItemReset_OnCommand( CommandEventArgs e ) { ArrayList pots = new ArrayList(); foreach ( Item item in World.Items.Values ) { if ( item is IFactionItem && !(item is HoodedShroudOfShadows) ) pots.Add( item ); } int[] hues = new int[Factions.Count * 2]; for ( int i = 0; i < Factions.Count; ++i ) { hues[0+(i*2)] = Factions[i].Definition.HuePrimary; hues[1+(i*2)] = Factions[i].Definition.HueSecondary; } int count = 0; for ( int i = 0; i < pots.Count; ++i ) { Item item = (Item)pots[i]; IFactionItem fci = (IFactionItem)item; if ( fci.FactionItemState != null || item.LootType != LootType.Blessed ) continue; bool isHued = false; for ( int j = 0; j < hues.Length; ++j ) { if ( item.Hue == hues[j] ) { isHued = true; break; } } if ( isHued ) { fci.FactionItemState = null; ++count; } } e.Mobile.SendMessage( "{0} items reset", count ); } public static void FactionCommander_OnCommand( CommandEventArgs e ) { e.Mobile.SendMessage( "Target a player to make them the faction commander." ); e.Mobile.BeginTarget( -1, false, TargetFlags.None, new TargetCallback( FactionCommander_OnTarget ) ); } public static void FactionCommander_OnTarget( Mobile from, object obj ) { if ( obj is PlayerMobile ) { Mobile targ = (Mobile)obj; PlayerState pl = PlayerState.Find( targ ); if ( pl != null ) { pl.Faction.Commander = targ; from.SendMessage( "You have appointed them as the faction commander." ); } else { from.SendMessage( "They are not in a faction." ); } } else { from.SendMessage( "That is not a player." ); } } public static void FactionElection_OnCommand( CommandEventArgs e ) { e.Mobile.SendMessage( "Target a faction stone to open its election properties." ); e.Mobile.BeginTarget( -1, false, TargetFlags.None, new TargetCallback( FactionElection_OnTarget ) ); } public static void FactionElection_OnTarget( Mobile from, object obj ) { if ( obj is FactionStone ) { Faction faction = ((FactionStone)obj).Faction; if ( faction != null ) from.SendGump( new ElectionManagementGump( faction.Election ) ); //from.SendGump( new Gumps.PropertiesGump( from, faction.Election ) ); else from.SendMessage( "That stone has no faction assigned." ); } else { from.SendMessage( "That is not a faction stone." ); } } public static void FactionKick_OnCommand( CommandEventArgs e ) { e.Mobile.SendMessage( "Target a player to remove them from their faction." ); e.Mobile.BeginTarget( -1, false, TargetFlags.None, new TargetCallback( FactionKick_OnTarget ) ); } public static void FactionKick_OnTarget( Mobile from, object obj ) { if ( obj is Mobile ) { Mobile mob = (Mobile) obj; PlayerState pl = PlayerState.Find( (Mobile) mob ); if ( pl != null ) { pl.Faction.RemoveMember( mob ); mob.SendMessage( "You have been kicked from your faction." ); from.SendMessage( "They have been kicked from their faction." ); } else { from.SendMessage( "They are not in a faction." ); } } else { from.SendMessage( "That is not a player." ); } } public static void ProcessTick() { List<Sigil> sigils = Sigil.Sigils; for ( int i = 0; i < sigils.Count; ++i ) { Sigil sigil = sigils[i]; if ( !sigil.IsBeingCorrupted && sigil.GraceStart != DateTime.MinValue && (sigil.GraceStart + Sigil.CorruptionGrace) < DateTime.Now ) { if ( sigil.LastMonolith is StrongholdMonolith && ( sigil.Corrupted == null || sigil.LastMonolith.Faction != sigil.Corrupted )) { sigil.Corrupting = sigil.LastMonolith.Faction; sigil.CorruptionStart = DateTime.Now; } else { sigil.Corrupting = null; sigil.CorruptionStart = DateTime.MinValue; } sigil.GraceStart = DateTime.MinValue; } if ( sigil.LastMonolith == null || sigil.LastMonolith.Sigil == null ) { if ( (sigil.LastStolen + Sigil.ReturnPeriod) < DateTime.Now ) sigil.ReturnHome(); } else { if ( sigil.IsBeingCorrupted && (sigil.CorruptionStart + Sigil.CorruptionPeriod) < DateTime.Now ) { sigil.Corrupted = sigil.Corrupting; sigil.Corrupting = null; sigil.CorruptionStart = DateTime.MinValue; sigil.GraceStart = DateTime.MinValue; } else if ( sigil.IsPurifying && (sigil.PurificationStart + Sigil.PurificationPeriod) < DateTime.Now ) { sigil.PurificationStart = DateTime.MinValue; sigil.Corrupted = null; sigil.Corrupting = null; sigil.CorruptionStart = DateTime.MinValue; sigil.GraceStart = DateTime.MinValue; } } } } public static void HandleDeath( Mobile mob ) { HandleDeath( mob, null ); } #region Skill Loss public const double SkillLossFactor = 1.0 / 3; public static readonly TimeSpan SkillLossPeriod = TimeSpan.FromMinutes( 20.0 ); private static Dictionary<Mobile, SkillLossContext> m_SkillLoss = new Dictionary<Mobile, SkillLossContext>(); private class SkillLossContext { public Timer m_Timer; public List<SkillMod> m_Mods; } public static bool InSkillLoss( Mobile mob ) { return m_SkillLoss.ContainsKey( mob ); } public static void ApplySkillLoss( Mobile mob ) { if ( InSkillLoss( mob ) ) return; SkillLossContext context = new SkillLossContext(); m_SkillLoss[mob] = context; List<SkillMod> mods = context.m_Mods = new List<SkillMod>(); for ( int i = 0; i < mob.Skills.Length; ++i ) { Skill sk = mob.Skills[i]; double baseValue = sk.Base; if ( baseValue > 0 ) { SkillMod mod = new DefaultSkillMod( sk.SkillName, true, -(baseValue * SkillLossFactor) ); mods.Add( mod ); mob.AddSkillMod( mod ); } } context.m_Timer = Timer.DelayCall( SkillLossPeriod, new TimerStateCallback( ClearSkillLoss_Callback ), mob ); } private static void ClearSkillLoss_Callback( object state ) { ClearSkillLoss( (Mobile) state ); } public static bool ClearSkillLoss( Mobile mob ) { SkillLossContext context; if ( !m_SkillLoss.TryGetValue( mob, out context ) ) return false; m_SkillLoss.Remove( mob ); List<SkillMod> mods = context.m_Mods; for ( int i = 0; i < mods.Count; ++i ) mob.RemoveSkillMod( mods[i] ); context.m_Timer.Stop(); return true; } #endregion public int AwardSilver( Mobile mob, int silver ) { if ( silver <= 0 ) return 0; int tithed = ( silver * Tithe ) / 100; Silver += tithed; silver = silver - tithed; if ( silver > 0 ) mob.AddToBackpack( new Silver( silver ) ); return silver; } public virtual int MaximumTraps{ get{ return 15; } } public List<BaseFactionTrap> Traps { get{ return m_State.Traps; } set{ m_State.Traps = value; } } public const int StabilityFactor = 300; // 300% greater (3 times) than smallest faction public const int StabilityActivation = 200; // Stablity code goes into effect when largest faction has > 200 people public static Faction FindSmallestFaction() { List<Faction> factions = Factions; Faction smallest = null; for ( int i = 0; i < factions.Count; ++i ) { Faction faction = factions[i]; if ( smallest == null || faction.Members.Count < smallest.Members.Count ) smallest = faction; } return smallest; } public static bool StabilityActive() { List<Faction> factions = Factions; for ( int i = 0; i < factions.Count; ++i ) { Faction faction = factions[i]; if ( faction.Members.Count > StabilityActivation ) return true; } return false; } public bool CanHandleInflux( int influx ) { if( !StabilityActive()) return true; Faction smallest = FindSmallestFaction(); if ( smallest == null ) return true; // sanity if ( StabilityFactor > 0 && (((this.Members.Count + influx) * 100) / StabilityFactor) > smallest.Members.Count ) return false; return true; } public static void HandleDeath( Mobile victim, Mobile killer ) { if ( killer == null ) killer = victim.FindMostRecentDamager( true ); PlayerState killerState = PlayerState.Find( killer ); Container pack = victim.Backpack; if ( pack != null ) { Container killerPack = ( killer == null ? null : killer.Backpack ); Item[] sigils = pack.FindItemsByType( typeof( Sigil ) ); for ( int i = 0; i < sigils.Length; ++i ) { Sigil sigil = (Sigil)sigils[i]; if ( killerState != null && killerPack != null ) { if ( killer.GetDistanceToSqrt( victim ) > 64 ) { sigil.ReturnHome(); killer.SendLocalizedMessage( 1042230 ); // The sigil has gone back to its home location. } else if ( Sigil.ExistsOn( killer ) ) { sigil.ReturnHome(); killer.SendLocalizedMessage( 1010258 ); // The sigil has gone back to its home location because you already have a sigil. } else if ( !killerPack.TryDropItem( killer, sigil, false ) ) { sigil.ReturnHome(); killer.SendLocalizedMessage( 1010259 ); // The sigil has gone home because your backpack is full. } } else { sigil.ReturnHome(); } } } if ( killerState == null ) return; if ( victim is BaseCreature ) { BaseCreature bc = (BaseCreature)victim; Faction victimFaction = bc.FactionAllegiance; if ( bc.Map == Faction.Facet && victimFaction != null && killerState.Faction != victimFaction ) { int silver = killerState.Faction.AwardSilver( killer, bc.FactionSilverWorth ); if ( silver > 0 ) killer.SendLocalizedMessage( 1042748, silver.ToString( "N0" ) ); // Thou hast earned ~1_AMOUNT~ silver for vanquishing the vile creature. } #region Ethics if ( bc.Map == Faction.Facet && bc.GetEthicAllegiance( killer ) == BaseCreature.Allegiance.Enemy ) { Ethics.Player killerEPL = Ethics.Player.Find( killer ); if ( killerEPL != null && ( 100 - killerEPL.Power ) > Utility.Random( 100 ) ) { ++killerEPL.Power; ++killerEPL.History; } } #endregion return; } PlayerState victimState = PlayerState.Find( victim ); if ( victimState == null ) return; #region Dueling if (victim.Region.IsPartOf(typeof(Engines.ConPVP.SafeZone))) return; #endregion if ( killer == victim || killerState.Faction != victimState.Faction ) ApplySkillLoss( victim ); if ( killerState.Faction != victimState.Faction ) { if ( victimState.KillPoints <= -6 ) { killer.SendLocalizedMessage( 501693 ); // This victim is not worth enough to get kill points from. #region Ethics Ethics.Player killerEPL = Ethics.Player.Find( killer ); Ethics.Player victimEPL = Ethics.Player.Find( victim ); if ( killerEPL != null && victimEPL != null && victimEPL.Power > 0 && victimState.CanGiveSilverTo( killer ) ) { int powerTransfer = Math.Max( 1, victimEPL.Power / 5 ); if ( powerTransfer > ( 100 - killerEPL.Power ) ) powerTransfer = 100 - killerEPL.Power; if ( powerTransfer > 0 ) { victimEPL.Power -= ( powerTransfer + 1 ) / 2; killerEPL.Power += powerTransfer; killerEPL.History += powerTransfer; victimState.OnGivenSilverTo( killer ); } } #endregion } else { int award = Math.Max( victimState.KillPoints / 10, 1 ); if ( award > 40 ) award = 40; if ( victimState.CanGiveSilverTo( killer ) ) { if ( victimState.KillPoints > 0 ) { victimState.IsActive = true; if ( 1 > Utility.Random( 3 ) ) killerState.IsActive = true; int silver = 0; silver = killerState.Faction.AwardSilver( killer, award * 40 ); if ( silver > 0 ) killer.SendLocalizedMessage( 1042736, String.Format( "{0:N0} silver\t{1}", silver, victim.Name ) ); // You have earned ~1_SILVER_AMOUNT~ pieces for vanquishing ~2_PLAYER_NAME~! } victimState.KillPoints -= award; killerState.KillPoints += award; int offset = ( award != 1 ? 0 : 2 ); // for pluralization string args = String.Format( "{0}\t{1}\t{2}", award, victim.Name, killer.Name ); killer.SendLocalizedMessage( 1042737 + offset, args ); // Thou hast been honored with ~1_KILL_POINTS~ kill point(s) for vanquishing ~2_DEAD_PLAYER~! victim.SendLocalizedMessage( 1042738 + offset, args ); // Thou has lost ~1_KILL_POINTS~ kill point(s) to ~3_ATTACKER_NAME~ for being vanquished! #region Ethics Ethics.Player killerEPL = Ethics.Player.Find( killer ); Ethics.Player victimEPL = Ethics.Player.Find( victim ); if ( killerEPL != null && victimEPL != null && victimEPL.Power > 0 ) { int powerTransfer = Math.Max( 1, victimEPL.Power / 5 ); if ( powerTransfer > ( 100 - killerEPL.Power ) ) powerTransfer = 100 - killerEPL.Power; if ( powerTransfer > 0 ) { victimEPL.Power -= ( powerTransfer + 1 ) / 2; killerEPL.Power += powerTransfer; killerEPL.History += powerTransfer; } } #endregion victimState.OnGivenSilverTo( killer ); } else { killer.SendLocalizedMessage( 1042231 ); // You have recently defeated this enemy and thus their death brings you no honor. } } } } private static void EventSink_Logout( LogoutEventArgs e ) { Mobile mob = e.Mobile; Container pack = mob.Backpack; if ( pack == null ) return; Item[] sigils = pack.FindItemsByType( typeof( Sigil ) ); for ( int i = 0; i < sigils.Length; ++i ) ((Sigil)sigils[i]).ReturnHome(); } private static void EventSink_Login( LoginEventArgs e ) { Mobile mob = e.Mobile; CheckLeaveTimer( mob ); } public static readonly Map Facet = Map.Felucca; public static void WriteReference( GenericWriter writer, Faction fact ) { int idx = Factions.IndexOf( fact ); writer.WriteEncodedInt( (int) (idx + 1) ); } public static List<Faction> Factions{ get{ return Reflector.Factions; } } public static Faction ReadReference( GenericReader reader ) { int idx = reader.ReadEncodedInt() - 1; if ( idx >= 0 && idx < Factions.Count ) return Factions[idx]; return null; } public static Faction Find( Mobile mob ) { return Find( mob, false, false ); } public static Faction Find( Mobile mob, bool inherit ) { return Find( mob, inherit, false ); } public static Faction Find( Mobile mob, bool inherit, bool creatureAllegiances ) { PlayerState pl = PlayerState.Find( mob ); if ( pl != null ) return pl.Faction; if ( inherit && mob is BaseCreature ) { BaseCreature bc = (BaseCreature)mob; if ( bc.Controlled ) return Find( bc.ControlMaster, false ); else if ( bc.Summoned ) return Find( bc.SummonMaster, false ); else if ( creatureAllegiances && mob is BaseFactionGuard ) return ((BaseFactionGuard)mob).Faction; else if ( creatureAllegiances ) return bc.FactionAllegiance; } return null; } public static Faction Parse( string name ) { List<Faction> factions = Factions; for ( int i = 0; i < factions.Count; ++i ) { Faction faction = factions[i]; if ( Insensitive.Equals( faction.Definition.FriendlyName, name ) ) return faction; } return null; } } public enum FactionKickType { Kick, Ban, Unban } public class FactionKickCommand : BaseCommand { private FactionKickType m_KickType; public FactionKickCommand( FactionKickType kickType ) { m_KickType = kickType; AccessLevel = AccessLevel.GameMaster; Supports = CommandSupport.AllMobiles; ObjectTypes = ObjectTypes.Mobiles; switch ( m_KickType ) { case FactionKickType.Kick: { Commands = new string[]{ "FactionKick" }; Usage = "FactionKick"; Description = "Kicks the targeted player out of his current faction. This does not prevent them from rejoining."; break; } case FactionKickType.Ban: { Commands = new string[]{ "FactionBan" }; Usage = "FactionBan"; Description = "Bans the account of a targeted player from joining factions. All players on the account are removed from their current faction, if any."; break; } case FactionKickType.Unban: { Commands = new string[]{ "FactionUnban" }; Usage = "FactionUnban"; Description = "Unbans the account of a targeted player from joining factions."; break; } } } public override void Execute( CommandEventArgs e, object obj ) { Mobile mob = (Mobile)obj; switch ( m_KickType ) { case FactionKickType.Kick: { PlayerState pl = PlayerState.Find( mob ); if ( pl != null ) { pl.Faction.RemoveMember( mob ); mob.SendMessage( "You have been kicked from your faction." ); AddResponse( "They have been kicked from their faction." ); } else { LogFailure( "They are not in a faction." ); } break; } case FactionKickType.Ban: { Account acct = mob.Account as Account; if ( acct != null ) { if ( acct.GetTag( "FactionBanned" ) == null ) { acct.SetTag( "FactionBanned", "true" ); AddResponse( "The account has been banned from joining factions." ); } else { AddResponse( "The account is already banned from joining factions." ); } for ( int i = 0; i < acct.Length; ++i ) { mob = acct[i]; if ( mob != null ) { PlayerState pl = PlayerState.Find( mob ); if ( pl != null ) { pl.Faction.RemoveMember( mob ); mob.SendMessage( "You have been kicked from your faction." ); AddResponse( "They have been kicked from their faction." ); } } } } else { LogFailure( "They have no assigned account." ); } break; } case FactionKickType.Unban: { Account acct = mob.Account as Account; if ( acct != null ) { if ( acct.GetTag( "FactionBanned" ) == null ) { AddResponse( "The account is not already banned from joining factions." ); } else { acct.RemoveTag( "FactionBanned" ); AddResponse( "The account may now freely join factions." ); } } else { LogFailure( "They have no assigned account." ); } break; } } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 the Aurora-Sim Project 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 DEVELOPERS ``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 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 Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.Framework.Scenes.Animation { /// <summary> /// Handle all animation duties for a scene presence /// </summary> public class Animator : IAnimator { private static AvatarAnimations m_defaultAnimations; protected int SLOWFLY_DELAY = 10; private float m_animTickFall; private float m_animTickStandup; private float m_animTickWalk; protected AnimationSet m_animations; protected string m_movementAnimation = "DEFAULT"; /// <value> /// The scene presence that this animator applies to /// </value> protected IScenePresence m_scenePresence; private int m_timesBeforeSlowFlyIsOff; protected bool m_useSplatAnimation = true; private bool wasLastFlying = false; public bool NeedsAnimationResent { get; set; } public Animator(IScenePresence sp) { m_scenePresence = sp; IConfig animationConfig = sp.Scene.Config.Configs["Animations"]; if (animationConfig != null) { SLOWFLY_DELAY = animationConfig.GetInt("SlowFlyDelay", SLOWFLY_DELAY); m_useSplatAnimation = animationConfig.GetBoolean("enableSplatAnimation", m_useSplatAnimation); } //This step makes sure that we don't waste almost 2.5! seconds on incoming agents m_animations = new AnimationSet(DefaultAnimations); } public static AvatarAnimations DefaultAnimations { get { if (m_defaultAnimations == null) m_defaultAnimations = new AvatarAnimations(); return m_defaultAnimations; } } #region IAnimator Members public AnimationSet Animations { get { return m_animations; } } /// <value> /// The current movement animation /// </value> public string CurrentMovementAnimation { get { return m_movementAnimation; } } public void AddAnimation(UUID animID, UUID objectID) { if (m_scenePresence.IsChildAgent) return; if (m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, objectID)) SendAnimPack(); } // Called from scripts public bool AddAnimation(string name, UUID objectID) { if (m_scenePresence.IsChildAgent) return false; UUID animID = m_scenePresence.ControllingClient.GetDefaultAnimation(name); if (animID == UUID.Zero) return false; AddAnimation(animID, objectID); return true; } /// <summary> /// Remove the given animation from the list of current animations /// </summary> /// <param name = "animID"></param> public void RemoveAnimation(UUID animID) { if (m_scenePresence.IsChildAgent) return; if (m_animations.Remove(animID)) SendAnimPack(); } /// <summary> /// Remove the given animation from the list of current animations /// </summary> /// <param name = "name"></param> public bool RemoveAnimation(string name) { if (m_scenePresence.IsChildAgent) return false; UUID animID = m_scenePresence.ControllingClient.GetDefaultAnimation(name); if (animID == UUID.Zero) { if (DefaultAnimations.AnimsUUID.ContainsKey(name.ToUpper())) animID = DefaultAnimations.AnimsUUID[name]; else return false; } RemoveAnimation(animID); return true; } /// <summary> /// Clear out all animations /// </summary> public void ResetAnimations() { m_animations.Clear(); } /// <summary> /// The movement animation is reserved for "main" animations /// that are mutually exclusive, e.g. flying and sitting. /// </summary> public void TrySetMovementAnimation(string anim) { TrySetMovementAnimation(anim, false); } /// <summary> /// The movement animation is reserved for "main" animations /// that are mutually exclusive, e.g. flying and sitting. /// </summary> public void TrySetMovementAnimation(string anim, bool sendTerseUpdateIfNotSending) { //MainConsole.Instance.DebugFormat("Updating movement animation to {0}", anim); if (!m_useSplatAnimation && anim == "STANDUP") anim = "LAND"; if (!m_scenePresence.IsChildAgent) { if (m_animations.TrySetDefaultAnimation( anim, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, m_scenePresence.UUID)) { // 16384 is CHANGED_ANIMATION IAttachmentsModule attMod = m_scenePresence.Scene.RequestModuleInterface<IAttachmentsModule>(); if (attMod != null) attMod.SendScriptEventToAttachments(m_scenePresence.UUID, "changed", new Object[] {(int) Changed.ANIMATION}); SendAnimPack(); } else if (sendTerseUpdateIfNotSending) m_scenePresence.SendTerseUpdateToAllClients(); //Send the terse update alone then } } /// <summary> /// This method determines the proper movement related animation /// </summary> public string GetMovementAnimation() { const float STANDUP_TIME = 2f; const float BRUSH_TIME = 3.5f; const float FALL_AFTER_MOVE_TIME = 0.75f; const float SOFTLAND_FORCE = 80; #region Inputs if (m_scenePresence.SitGround) { return "SIT_GROUND_CONSTRAINED"; } AgentManager.ControlFlags controlFlags = (AgentManager.ControlFlags) m_scenePresence.AgentControlFlags; PhysicsCharacter actor = m_scenePresence.PhysicsActor; // Create forward and left vectors from the current avatar rotation Vector3 fwd = Vector3.UnitX*m_scenePresence.Rotation; Vector3 left = Vector3.UnitY*m_scenePresence.Rotation; // Check control flags bool heldForward = (((controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) || ((controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS)); bool yawPos = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) == AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS; bool yawNeg = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG; bool heldBack = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG; bool heldLeft = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS; bool heldRight = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG; bool heldTurnLeft = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) == AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT; bool heldTurnRight = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) == AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT; bool heldUp = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) == AgentManager.ControlFlags.AGENT_CONTROL_UP_POS; bool heldDown = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG; //bool flying = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) == AgentManager.ControlFlags.AGENT_CONTROL_FLY; //bool mouselook = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) == AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK; // Direction in which the avatar is trying to move Vector3 move = Vector3.Zero; if (heldForward) { move.X += fwd.X; move.Y += fwd.Y; } if (heldBack) { move.X -= fwd.X; move.Y -= fwd.Y; } if (heldLeft) { move.X += left.X; move.Y += left.Y; } if (heldRight) { move.X -= left.X; move.Y -= left.Y; } if (heldUp) { move.Z += 1; } if (heldDown) { move.Z -= 1; } float fallVelocity = (actor != null) ? actor.Velocity.Z : 0.0f; if (heldTurnLeft && yawPos && !heldForward && !heldBack && actor != null && !actor.IsJumping && !actor.Flying && move.Z == 0 && fallVelocity == 0.0f && !heldUp && !heldDown && move.CompareTo(Vector3.Zero) == 0) { return "TURNLEFT"; } if (heldTurnRight && yawNeg && !heldForward && !heldBack && actor != null && !actor.IsJumping && !actor.Flying && move.Z == 0 && fallVelocity == 0.0f && !heldUp && !heldDown && move.CompareTo(Vector3.Zero) == 0) { return "TURNRIGHT"; } // Is the avatar trying to move? // bool moving = (move != Vector3.Zero); #endregion Inputs #region Standup float standupElapsed = (Util.EnvironmentTickCount() - m_animTickStandup)/1000f; if (m_scenePresence.PhysicsActor != null && standupElapsed < STANDUP_TIME && m_useSplatAnimation) { // Falling long enough to trigger the animation m_scenePresence.FallenStandUp = true; m_scenePresence.PhysicsActor.Velocity = Vector3.Zero; return "STANDUP"; } else if (standupElapsed < BRUSH_TIME && m_useSplatAnimation) { m_scenePresence.FallenStandUp = true; return "BRUSH"; } else if (m_animTickStandup != 0 || m_scenePresence.FallenStandUp) { m_scenePresence.FallenStandUp = false; m_animTickStandup = 0; } #endregion Standup #region Flying // if (actor != null && actor.Flying) if (actor != null && (m_scenePresence.AgentControlFlags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY) == (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY || m_scenePresence.ForceFly) { m_animTickFall = 0; if (move.X != 0f || move.Y != 0f) { if (move.Z == 0) { if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) { return "SWIM_FORWARD"; } else { if (m_timesBeforeSlowFlyIsOff < SLOWFLY_DELAY) { m_timesBeforeSlowFlyIsOff++; return "FLYSLOW"; } else return "FLY"; } } else if (move.Z > 0) { if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_UP"; else return "FLYSLOW"; } if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_DOWN"; else return "FLY"; } else if (move.Z > 0f) { //This is for the slow fly timer m_timesBeforeSlowFlyIsOff = 0; if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_UP"; else return "HOVER_UP"; } else if (move.Z < 0f) { wasLastFlying = true; //This is for the slow fly timer m_timesBeforeSlowFlyIsOff = 0; if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_DOWN"; else { ITerrainChannel channel = m_scenePresence.Scene.RequestModuleInterface<ITerrainChannel>(); if (channel != null) { float groundHeight = channel.GetNormalizedGroundHeight((int) m_scenePresence.AbsolutePosition.X, (int) m_scenePresence.AbsolutePosition.Y); if (actor != null && (m_scenePresence.AbsolutePosition.Z - groundHeight) < 2) return "LAND"; else return "HOVER_DOWN"; } else return "HOVER_DOWN"; } } else { //This is for the slow fly timer m_timesBeforeSlowFlyIsOff = 0; if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_HOVER"; else return "HOVER"; } } m_timesBeforeSlowFlyIsOff = 0; #endregion Flying #region Jumping if (actor != null && actor.IsJumping) { return "JUMP"; } if (actor != null && actor.IsPreJumping) { return "PREJUMP"; } #endregion #region Falling/Floating/Landing float walkElapsed = (Util.EnvironmentTickCount() - m_animTickWalk) / 1000f; if (actor != null && actor.IsPhysical && !actor.IsJumping && (!actor.IsColliding) && actor.Velocity.Z < -2 && walkElapsed > FALL_AFTER_MOVE_TIME) { //Always return falldown immediately as there shouldn't be a waiting period if (m_animTickFall == 0) m_animTickFall = Util.EnvironmentTickCount(); return "FALLDOWN"; } #endregion Falling/Floating/Landing #region Ground Movement if (m_movementAnimation == "FALLDOWN") { float fallElapsed = (Util.EnvironmentTickCount() - m_animTickFall)/1000f; if (fallElapsed < 0.75) { m_animTickFall = Util.EnvironmentTickCount(); return "SOFT_LAND"; } else if (fallElapsed < 1.1 || (Math.Abs(actor.Velocity.X) > 1 && Math.Abs(actor.Velocity.Y) > 1 && actor.Velocity.Z < 3)) { m_animTickFall = Util.EnvironmentTickCount(); return "LAND"; } else { if (m_useSplatAnimation) { m_animTickStandup = Util.EnvironmentTickCount(); return "STANDUP"; } else return "LAND"; } } else if (m_movementAnimation == "LAND") { if (actor != null && actor.Velocity.Z != 0) { if (actor.Velocity.Z < SOFTLAND_FORCE) return "LAND"; return "SOFT_LAND"; } //return "LAND"; } m_animTickFall = 0; if (move.Z <= 0f) { if (actor != null && (move.X != 0f || move.Y != 0f || actor.Velocity.X != 0 && actor.Velocity.Y != 0)) { wasLastFlying = false; if(actor.IsColliding) m_animTickWalk = Util.EnvironmentTickCount(); // Walking / crouchwalking / running if (move.Z < 0f) return "CROUCHWALK"; else if (m_scenePresence.SetAlwaysRun) return "RUN"; else return "WALK"; } else { // Not walking if (move.Z < 0f && !wasLastFlying) return "CROUCH"; else return "STAND"; } } #endregion Ground Movement return m_movementAnimation; } /// <summary> /// Update the movement animation of this avatar according to its current state /// </summary> public void UpdateMovementAnimations(bool sendTerseUpdate) { string oldanimation = m_movementAnimation; m_movementAnimation = GetMovementAnimation(); if (NeedsAnimationResent || oldanimation != m_movementAnimation || sendTerseUpdate) { NeedsAnimationResent = false; TrySetMovementAnimation(m_movementAnimation, sendTerseUpdate); } } /// <summary> /// Gets a list of the animations that are currently in use by this avatar /// </summary> /// <returns></returns> public UUID[] GetAnimationArray() { UUID[] animIDs; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs); return animIDs; } /// <summary> /// Sends all clients the given information for this avatar /// </summary> /// <param name = "animations"></param> /// <param name = "seqs"></param> /// <param name = "objectIDs"></param> public void SendAnimPack(UUID[] animations, int[] sequenceNums, UUID[] objectIDs) { if (m_scenePresence.IsChildAgent) return; AnimationGroup anis = new AnimationGroup { Animations = animations, SequenceNums = sequenceNums, ObjectIDs = objectIDs, AvatarID = m_scenePresence.UUID }; #if (!ISWIN) m_scenePresence.Scene.ForEachScenePresence( delegate(IScenePresence presence) { presence.SceneViewer.QueuePresenceForAnimationUpdate(m_scenePresence, anis); }); #else m_scenePresence.Scene.ForEachScenePresence( presence => presence.SceneViewer.QueuePresenceForAnimationUpdate(presence, anis)); #endif } /// <summary> /// Send an animation update to the given client /// </summary> /// <param name = "client"></param> public void SendAnimPackToClient(IClientAPI client) { if (m_scenePresence.IsChildAgent) return; UUID[] animations; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animations, out sequenceNums, out objectIDs); AnimationGroup anis = new AnimationGroup { Animations = animations, SequenceNums = sequenceNums, ObjectIDs = objectIDs, AvatarID = m_scenePresence.ControllingClient.AgentId }; m_scenePresence.Scene.GetScenePresence(client.AgentId).SceneViewer.QueuePresenceForAnimationUpdate( m_scenePresence, anis); } /// <summary> /// Send animation information about this avatar to all clients. /// </summary> public void SendAnimPack() { //MainConsole.Instance.Debug("Sending animation pack to all"); if (m_scenePresence.IsChildAgent) return; UUID[] animIDs; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs); SendAnimPack(animIDs, sequenceNums, objectIDs); } /// <summary> /// Close out and remove any current data /// </summary> public void Close() { m_animations = null; m_scenePresence = null; } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 11/17/2008 8:57:29 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using GeoAPI.Geometries; namespace DotSpatial.Symbology { /// <summary> /// ITextSymbolizer /// </summary> [TypeConverter(typeof(ExpandableObjectConverter))] public interface ILabelSymbolizer : ICloneable { #region Properties /// <summary> /// Gets or sets the the multi-line text alignment in the box. /// </summary> [Category("General"), Description("Gets or sets the horizontal relationship of the text to the anchorpoint.")] StringAlignment Alignment { get; set; } /// <summary> /// Gets or set the angle that the font should be drawn in /// </summary> [Category("General"), Description("Gets or sets the angle that the font should be drawn in.")] double Angle { get; set; } /// <summary> /// Gets or sets the background color /// </summary> [Category("General"), Description("Gets or sets the background color of a rectangle around the label.")] Color BackColor { get; set; } /// <summary> /// Gets or sets a boolean indicating whether or not a background color should be used /// </summary> [Category("General"), Description("Gets or sets a boolean indicating whether or not a background color should be used.")] bool BackColorEnabled { get; set; } /// <summary> /// Gets or sets the border color /// </summary> [Category("Border"), Description("Gets or sets the border color")] Color BorderColor { get; set; } /// <summary> /// Gets or sets a boolean indicating whether or not a border should be drawn around the label. /// </summary> [Category("Border"), Description("Gets or sets a boolean indicating whether or not a border should be drawn around the label.")] bool BorderVisible { get; set; } /// <summary> /// Gets or sets the color of the actual shadow. Use the alpha channel to specify opacity. /// </summary> [Category("Shadow"), Description("Gets or sets the color of the actual shadow. Use the alpha channel to specify opacity.")] Color DropShadowColor { get; set; } /// <summary> /// Gets or sets a boolean that will force a shadow to be drawn if this is true. /// </summary> [Category("Shadow"), Description("Gets or sets a boolean that will force a shadow to be drawn if this is true.")] bool DropShadowEnabled { get; set; } /// <summary> /// Gets or sets an X and Y geographic offset that is only used if ScaleMode is set to Geographic /// </summary> [Category("Shadow"), Description("Gets or sets an X and Y geographic offset that is only used if ScaleMode is set to Geographic.")] Coordinate DropShadowGeographicOffset { get; set; } /// <summary> /// Gets or sets an X and Y pixel offset that is used if the ScaleMode is set to Symbolic or Simple. /// </summary> [Category("Shadow"), Description("Gets or sets an X and Y pixel offset that is used if the ScaleMode is set to Symbolic or Simple.")] PointF DropShadowPixelOffset { get; set; } /// <summary> /// Gets or sets format string used to draw float fields. E.g.: /// #.##, 0.000. If empty - then format not used. /// </summary> string FloatingFormat { get; set; } /// <summary> /// Gets or set the color that the font should be drawn in. /// </summary> [Category("General"), Description("Gets or sets the color that the font should be drawn in.")] Color FontColor { get; set; } /// <summary> /// Gets or sets the string font family name /// </summary> string FontFamily { get; set; } /// <summary> /// gets or sets the font size /// </summary> float FontSize { get; set; } /// <summary> /// Gets or sets the font style. /// </summary> FontStyle FontStyle { get; set; } /// <summary> /// Gets or sets the color of the halo that surrounds the text. /// </summary> [Category("Halo"), Description("Gets or sets the color of the halo that surrounds the text.")] Color HaloColor { get; set; } /// <summary> /// Gets or sets a boolean that governs whether or not to draw a halo. /// </summary> [Category("Halo"), Description("Gets or sets a boolean that governs whether or not to draw a halo.")] bool HaloEnabled { get; set; } /// <summary> /// Gets or set the field with angle to draw label /// </summary> [Category("General"), Description("Gets or set the field with angle to draw label.")] string LabelAngleField { get; set; } /// <summary> /// Gets or sets the labeling method /// </summary> [Category("General"), Description("Gets or sets the labeling method.")] LabelPlacementMethod LabelPlacementMethod { get; set; } /// <summary> /// Gets or sets the labeling method /// </summary> [Category("General"), Description("Gets or sets the labeling method for line labels.")] LineLabelPlacementMethod LineLabelPlacementMethod { get; set; } /// <summary> /// Gets or sets the orientation of line labels. /// </summary> [Category("General"), Description("Gets or sets the orientation of line labels.")] LineOrientation LineOrientation { get; set; } /// <summary> /// Gets or sets the X offset in pixels from the center of each feature. /// </summary> [Category("General"), Description("Gets or sets the X offset in pixels from the center of each feature.")] float OffsetX { get; set; } /// <summary> /// Gets or sets the Y offset in pixels from the center of each feature. /// </summary> [Category("General"), Description("Gets or sets the Y offset in pixels from the center of each feature.")] float OffsetY { get; set; } /// <summary> /// Gets or sets the position of the label relative to the placement point /// </summary> [Category("General"), Description("Gets or sets the position of the label relative to the placement point.")] ContentAlignment Orientation { get; set; } /// <summary> /// Gets or sets the way features with multiple parts are labeled /// </summary> [Category("General"), Description("Gets or sets the way features with multiple parts are labeled.")] PartLabelingMethod PartsLabelingMethod { get; set; } /// <summary> /// Gets or sets a boolean. If true, as high priority labels are placed, they /// take up space and will not allow low priority labels that conflict for the /// space to be placed. /// </summary> bool PreventCollisions { get; set; } /// <summary> /// Gets or sets a boolean. Normally high values from the field are given /// a higher priority. If this is true, low values are given priority instead. /// </summary> bool PrioritizeLowValues { get; set; } /// <summary> /// Gets or sets the string field name for the field that controls which labels /// get placed first. If collision detection is on, a higher priority means /// will get placed first. If it is off, higher priority will be labeled /// on top of lower priority. /// </summary> string PriorityField { get; set; } /// <summary> /// Gets or sets the scaling behavior for the text /// </summary> [Category("General"), Description(" Gets or sets the scaling behavior for the text.")] ScaleMode ScaleMode { get; set; } /// <summary> /// Gets or sets a boolean indicating whether or not <see cref="Angle"/> should be used /// </summary> [Category("General"), Description("Gets or sets a boolean indicating whether or not Angle should be used.")] bool UseAngle { get; set; } /// <summary> /// Gets or set a boolean indicating whether or not <see cref="LabelAngleField"/> should be used /// </summary> [Category("General"), Description("Gets or set a boolean indicating whether or not LabelAngleField should be used.")] bool UseLabelAngleField { get; set; } /// <summary> /// Gets or sets a boolean indicating whether or not the LineOrientation gets used. /// </summary> [Category("General"), Description("Gets or sets a boolean indicating whether or not LineOrientation should be used.")] bool UseLineOrientation { get; set; } #endregion #region Methods /// <summary> /// Uses the properties defined on this symbolizer to return a font. /// </summary> /// <returns>A new font</returns> Font GetFont(); #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Globalization; using System.Linq; using System.Net; using System.Reactive.Linq; using System.Reactive.Subjects; using HyperQube.Library; using HyperQube.Library.Extensions; using HyperQube.Library.Questions; using Newtonsoft.Json; using WebSocketSharp; namespace HyperQube.Services { [Export(typeof(ISubscriptionService))] public class SubscriptionService : ISubscriptionService { const string DisabledQubesKey = "DisabledQubes"; const string LastModifiedTick = "LastModifiedTick"; private decimal _lastModified = -1; private readonly IOutputProvider _outputProvider; private readonly IInputProvider _inputProvider; private readonly IConfigurationProvider _configurationProvider; private readonly ReadOnlyCollection<IQube> _qubes; private readonly List<IQube> _enabledQubes = new List<IQube>(); private readonly Dictionary<IQube, IEnumerable<IDisposable>> _subscriptions = new Dictionary<IQube, IEnumerable<IDisposable>>(); private bool _disposed; private IDisposable _errorSubscription; private IDisposable _socketSubscription; private IDisposable _lastModifiedSubscription; private IDisposable _tickleSubscription; private readonly ISubject<dynamic> _subject = new Subject<dynamic>(); [ImportingConstructor] public SubscriptionService([Import("Connection", typeof(IDisposable))]WebSocket socket, IOutputProvider outputProvider, IInputProvider inputProvider, IConfigurationProvider configurationProvider, [ImportMany] IEnumerable<IQube> qubes) { _outputProvider = outputProvider; _inputProvider = inputProvider; _configurationProvider = configurationProvider; HookUpSocket(socket); _qubes = qubes.OrderBy(x => x.Title).ToList().AsReadOnly(); var fullnames = _configurationProvider.GetValue(DisabledQubesKey); var disabledQubes = string.IsNullOrWhiteSpace(fullnames) ? new string[0] : fullnames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var qube in _qubes.Where(qube => !disabledQubes.Contains(qube.GetType().FullName))) { Subscribe(qube); _enabledQubes.Add(qube); } var lastModified = _configurationProvider.GetValue(LastModifiedTick); if (!decimal.TryParse(lastModified, out _lastModified)) _lastModified = -1; _lastModifiedSubscription = _subject.Subscribe(SetLastModified); } public async void EnableOrDisableQubes() { var mapping = new Dictionary<Guid, dynamic>(); var questions = new List<BooleanQuestion>(); foreach (var qube in _qubes) { var enabled = _enabledQubes.Contains(qube); var question = new BooleanQuestion(qube.Title, initialValue: enabled, type: QuestionType.Togglable); mapping.Add(question.Tag, new { Qube = qube, Enabled = enabled }); questions.Add(question); } if (_inputProvider.Ask("Settings", "Enable or disable qubes.", questions.ToArray<IQuestion>())) { var disabledQubes = new List<IQube>(); foreach (var question in questions) { var map = mapping[question.Tag]; IQube qube = map.Qube; bool isEnabled = map.Enabled; if (question.Result) { if (!isEnabled) { Subscribe(qube); _enabledQubes.Add(qube); } } else { if (isEnabled) { foreach (var subscription in _subscriptions[qube]) subscription.Dispose(); _subscriptions.Remove(qube); _enabledQubes.Remove(qube); } disabledQubes.Add(qube); } } if (disabledQubes.Count > 0) { var fullnames = string.Join(";", disabledQubes.Select(x => x.GetType()).Select(x => x.FullName)); await _configurationProvider.SetValueAsync(DisabledQubesKey, fullnames); } else { await _configurationProvider.RemoveAsync(DisabledQubesKey); } await _configurationProvider.SaveAsync(); } } public void Subscribe(IQube qube) { var subscriptions = new List<IDisposable>(); var qubeInterests = qube.Interests; if ((qubeInterests & Interests.All) == Interests.All) { var subscription = _subject.Subscribe(qube.Receive); subscriptions.Add(subscription); } else { var interests = Enum.GetValues(typeof(Interests)) .Cast<Interests>() .Where(x => x != Interests.None && x != Interests.All) .Where(x => (qubeInterests & x) == x) .Select(x => x.AsPushType()); foreach (var interest in interests) { var copy = interest; var observable = _subject.Where(json => StringComparer.OrdinalIgnoreCase.Equals((string)json.type, copy)); var subscription = observable.Subscribe(qube.Receive); subscriptions.Add(subscription); } } _subscriptions[qube] = subscriptions; } private async void Tickle() { var address = @"https://api.pushbullet.com/v2/pushes"; var lastModified = _lastModified; if (lastModified > 0) { address += "?modified_after=" + lastModified; } using (var client = new WebClient()) { var apiKey = await _configurationProvider.GetAPIKeyAsync(); client.Headers["Authorization"] = "Bearer " + apiKey; client.UseDefaultCredentials = true; client.Proxy = WebRequest.DefaultWebProxy; var jsonString = await client.DownloadStringTaskAsync(address); var json = JsonConvert.DeserializeObject<dynamic>(jsonString); IEnumerable<dynamic> pushes = json.pushes; if (!pushes.Any()) return; var filteredPushes = pushes.Where(push => push.type != null) .Where(push => push.active != false) .Where(push => push.type != "dismissal") .Reverse(); //Reverse so we start with oldest push. foreach (object push in filteredPushes) Observe(push); } } private void Observe(object push) { _subject.OnNext(push); } private void SetLastModified(dynamic push) { var tick = push.modified ?? push.created; if (tick == null) return; string tickString = tick.ToString(); decimal tickDecimal; if (!decimal.TryParse(tickString, out tickDecimal) || tickDecimal <= _lastModified) return; _lastModified = tickDecimal; _configurationProvider.SetValue(LastModifiedTick, _lastModified.ToString("0.0000000", CultureInfo.InvariantCulture)); _configurationProvider.Save(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void HookUpSocket(WebSocket socket) { _outputProvider.Trace("Hooking up events"); _errorSubscription = Observable.FromEventPattern<ErrorEventArgs>(ev => socket.OnError += ev, ev => socket.OnError -= ev) .Select(x => x.EventArgs.Message) .Subscribe(OnError); var socketObserver = Observable.FromEventPattern<MessageEventArgs>(ev => socket.OnMessage += ev, ev => socket.OnMessage -= ev) .Select(x => x.EventArgs.Data) .Where(x => x != "{\"type\": \"nop\"}") //Ignore heartbeat, check as string so we don't spend time on deserializing it. .Select(JsonConvert.DeserializeObject<dynamic>); _socketSubscription = socketObserver.Where(x => x.type == "push") // New push .Select(x => x.push) //JSON Data from the push .Where(push => push.type != null) .Where(push => push.active != false) .Where(push => push.type != "dismissal") .Subscribe(Observe); _tickleSubscription = socketObserver.Where(x => x.type == "tickle" && x.subtype == "push") .Subscribe(_ => Tickle()); } private void OnError(string exception) { _outputProvider.TraceError(exception); } ~SubscriptionService() { Dispose(false); } private void Dispose(bool disposing) { if (_disposed) return; if (disposing) { if (_lastModifiedSubscription != null) { _lastModifiedSubscription.Dispose(); _lastModifiedSubscription = null; } if (_socketSubscription != null) { _socketSubscription.Dispose(); _socketSubscription = null; } if (_tickleSubscription != null) { _tickleSubscription.Dispose(); _tickleSubscription = null; } if (_errorSubscription != null) { _errorSubscription.Dispose(); _errorSubscription = null; } foreach (var subscription in _subscriptions.Values.SelectMany(x => x)) subscription.Dispose(); _subscriptions.Clear(); } _disposed = true; } } }
//------------------------------------------------------------------------------ // <copyright file="PropertyOverridesDialog.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Globalization; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Reflection; using System.Windows.Forms; using System.Windows.Forms.Design; using Control = System.Web.UI.Control; using System.Web.UI.MobileControls; using System.Web.UI.Design.MobileControls.Converters; using System.Web.UI.Design.MobileControls.Util; [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal sealed class PropertyOverridesDialog : DesignerForm, IRefreshableDeviceSpecificEditor, IDeviceSpecificDesigner { private bool _isDirty = true; private IDeviceSpecificDesigner _designer; private int _mergingContext; private System.Windows.Forms.Control _header; private String _currentDeviceSpecificID; private IDictionary _cachedDeviceSpecifics = new HybridDictionary(true /* make case-insensitive */); private bool _ignoreSelectionChanged = true; private System.Windows.Forms.Label _lblProperties; private System.Windows.Forms.PropertyGrid _pgProperties; private System.Windows.Forms.Button _btnEditFilters; private System.Windows.Forms.ComboBox _cbChoices; private System.Windows.Forms.Label _lblAppliedFilters; private System.Windows.Forms.Button _cmdOK; private System.Windows.Forms.Button _cmdCancel; private System.Windows.Forms.Panel _pnlMain; internal PropertyOverridesDialog( IDeviceSpecificDesigner designer, int mergingContext ) : base(designer.UnderlyingControl.Site) { _designer = designer; _mergingContext = mergingContext; // Required for Win Form Designer support InitializeComponent(); this._lblAppliedFilters.Text = SR.GetString(SR.PropertyOverridesDialog_AppliedDeviceFilters); this._btnEditFilters.Text = SR.GetString(SR.GenericDialog_Edit); this._lblProperties.Text = SR.GetString(SR.PropertyOverridesDialog_DeviceSpecificProperties); this._cmdOK.Text = SR.GetString(SR.GenericDialog_OKBtnCaption); this._cmdCancel.Text = SR.GetString(SR.GenericDialog_CancelBtnCaption); int tabOffset = GenericUI.InitDialog( this, _designer, _mergingContext ); this.Text = _designer.UnderlyingControl.ID + " - " + SR.GetString(SR.PropertyOverridesDialog_Title); SetTabIndexes(tabOffset); _designer.SetDeviceSpecificEditor(this); // Note that the following can cause an // IDeviceSpecificDesigner.Refresh() to occur as a side-effect. _designer.RefreshHeader(_mergingContext); _ignoreSelectionChanged = false; // NOTE: Calling CurrentDeviceSpecificID will cause a refresh to // happen as a side effect. _currentDeviceSpecificID = _designer.CurrentDeviceSpecificID; if(_currentDeviceSpecificID != null) { _cbChoices.Items.Clear(); LoadChoices(_currentDeviceSpecificID); if(!ValidateLoadedChoices()) { // Throw to prevent dialog from opening. Caught and hidden // by PropertyOverridesTypeEditor.cs throw new InvalidChoiceException( "Property overrides dialog can not open because there " + "are invalid choices defined in the page." ); } } // Register Event Handlers _cbChoices.SelectedIndexChanged += new EventHandler( OnFilterSelected ); _btnEditFilters.Click += new EventHandler(OnEditFilters); _cmdOK.Click += new EventHandler(OnOK); _cmdCancel.Click += new EventHandler(OnCancel); UpdateUI(); } protected override string HelpTopic { get { return "net.Mobile.PropertyOverridesDialog"; } } internal void SetTabIndexes(int tabOffset) { this._pnlMain.TabIndex = ++tabOffset; this._lblAppliedFilters.TabIndex = ++tabOffset; this._cbChoices.TabIndex = ++tabOffset; this._btnEditFilters.TabIndex = ++tabOffset; this._lblProperties.TabIndex = ++tabOffset; this._pgProperties.TabIndex = ++tabOffset; this._cmdOK.TabIndex = ++tabOffset; this._cmdCancel.TabIndex = ++tabOffset; } private void InitializeComponent() { this._cbChoices = new System.Windows.Forms.ComboBox(); this._cmdOK = new System.Windows.Forms.Button(); this._btnEditFilters = new System.Windows.Forms.Button(); this._pnlMain = new System.Windows.Forms.Panel(); this._pgProperties = new System.Windows.Forms.PropertyGrid(); this._lblProperties = new System.Windows.Forms.Label(); this._lblAppliedFilters = new System.Windows.Forms.Label(); this._cmdCancel = new System.Windows.Forms.Button(); this._cbChoices.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._cbChoices.DropDownWidth = 195; this._cbChoices.Location = new System.Drawing.Point(0, 16); this._cbChoices.Size = new System.Drawing.Size(195, 21); this._cmdOK.Location = new System.Drawing.Point(120, 290); this._cmdCancel.Location = new System.Drawing.Point(201, 290); this._btnEditFilters.Location = new System.Drawing.Point(201, 15); this._btnEditFilters.Size = new System.Drawing.Size(75, 23); this._pnlMain.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this._pnlMain.Controls.AddRange(new System.Windows.Forms.Control[] { this._cmdCancel, this._cmdOK, this._lblProperties, this._pgProperties, this._btnEditFilters, this._cbChoices, this._lblAppliedFilters}); this._pnlMain.Location = new System.Drawing.Point(6, 5); this._pnlMain.Size = new System.Drawing.Size(276, 313); this._pgProperties.CommandsVisibleIfAvailable = false; this._pgProperties.HelpVisible = false; this._pgProperties.LargeButtons = false; this._pgProperties.LineColor = System.Drawing.SystemColors.ScrollBar; this._pgProperties.Location = new System.Drawing.Point(0, 64); this._pgProperties.PropertySort = System.Windows.Forms.PropertySort.Alphabetical; this._pgProperties.Size = new System.Drawing.Size(275, 220); this._pgProperties.Text = "PropertyGrid"; this._pgProperties.ToolbarVisible = false; this._pgProperties.ViewBackColor = System.Drawing.SystemColors.Window; this._pgProperties.ViewForeColor = System.Drawing.SystemColors.WindowText; this._pgProperties.PropertyValueChanged += new PropertyValueChangedEventHandler(this.OnPropertyValueChanged); this._lblProperties.Location = new System.Drawing.Point(0, 48); this._lblProperties.Size = new System.Drawing.Size(275, 16); this._lblAppliedFilters.Size = new System.Drawing.Size(275, 16); this.AcceptButton = _cmdOK; this.CancelButton = _cmdCancel; this.ClientSize = new System.Drawing.Size(285, 325); this.Controls.AddRange(new System.Windows.Forms.Control[] {this._pnlMain}); } private void CacheState(String deviceSpecificID) { _cachedDeviceSpecifics[deviceSpecificID] = new PropertyOverridesCachedState(_cbChoices); } private void CacheCurrentState() { CacheState(_currentDeviceSpecificID); } private bool RestoreState(String deviceSpecificID) { if (null != deviceSpecificID) { _currentDeviceSpecificID = deviceSpecificID.ToLower(CultureInfo.InvariantCulture); PropertyOverridesCachedState state = (PropertyOverridesCachedState) _cachedDeviceSpecifics[ _currentDeviceSpecificID ]; if(state != null) { state.Restore(_cbChoices); foreach(ChoiceTreeNode node in state.Choices) { node.Choice.Refresh(); } return true; } } else { _currentDeviceSpecificID = null; } return false; } [Conditional("DEBUG")] private void debug_CheckChoicesForDuplicate(DeviceSpecificChoice runtimeChoice) { foreach(ChoiceTreeNode choiceNode in _cbChoices.Items) { if(choiceNode.Name == runtimeChoice.Filter && choiceNode.RuntimeChoice.Argument == runtimeChoice.Argument) { Debug.Fail("Loaded duplicate choice: " + DesignerUtility.ChoiceToUniqueIdentifier(runtimeChoice)); } } } private void LoadChoices(String deviceSpecificID) { DeviceSpecific ds; _designer.GetDeviceSpecific(deviceSpecificID, out ds); LoadChoices(ds); } private void LoadChoices(DeviceSpecific deviceSpecific) { if(deviceSpecific != null) { foreach(DeviceSpecificChoice runtimeChoice in deviceSpecific.Choices) { debug_CheckChoicesForDuplicate(runtimeChoice); ChoiceTreeNode newChoiceNode = new ChoiceTreeNode( null, runtimeChoice, _designer ); newChoiceNode.IncludeArgument = true; _cbChoices.Items.Add(newChoiceNode); } } UpdateUI(); } private bool ValidateLoadedChoices() { StringCollection duplicateChoices = DesignerUtility.GetDuplicateChoiceTreeNodes( _cbChoices.Items ); if(duplicateChoices.Count > 0) { if (!_ignoreSelectionChanged) { GenericUI.ShowWarningMessage( SR.GetString(SR.PropertyOverridesDialog_Title), SR.GetString(SR.PropertyOverridesDialog_DuplicateChoices, GenericUI.BuildCommaDelimitedList(duplicateChoices)) ); } return false; } return true; } private void SaveChoices() { if(_currentDeviceSpecificID != null) { CacheCurrentState(); } foreach (DictionaryEntry entry in _cachedDeviceSpecifics) { PropertyOverridesCachedState state = (PropertyOverridesCachedState) entry.Value; state.SaveChoicesFromComboBox( _designer, (String) entry.Key ); } } private void UpdateUI() { if(_cbChoices.SelectedItem == null && _cbChoices.Items.Count > 0) { _cbChoices.SelectedItem = _cbChoices.Items[0]; } ChoiceTreeNode choice = (ChoiceTreeNode) _cbChoices.SelectedItem; bool isChoiceSelected = (choice != null); if (isChoiceSelected) { _cbChoices.Text = choice.ToString(); _pgProperties.SelectedObject = choice.Choice; } else { _cbChoices.Text = String.Empty; _pgProperties.SelectedObject = null; } _cbChoices.Enabled = isChoiceSelected; _pgProperties.Enabled = isChoiceSelected; _btnEditFilters.Enabled = (_currentDeviceSpecificID != null); } private void SetDirty(bool dirty) { if (dirty) { if (false == _isDirty) { _isDirty = true; _cmdCancel.Text = SR.GetString(SR.GenericDialog_CancelBtnCaption); } } else { if (true == _isDirty) { _isDirty = false; _cmdCancel.Text = SR.GetString(SR.GenericDialog_CloseBtnCaption); } } } //////////////////////////////////////////////////////////////////////// // Begin Event Handling //////////////////////////////////////////////////////////////////////// private void OnEditFilters(Object sender, EventArgs e) { ISite componentSite = ((IComponent)(_designer.UnderlyingControl)).Site; Debug.Assert(componentSite != null, "Expected the runtime control to be sited."); IComponentChangeService changeService = (IComponentChangeService)componentSite.GetService(typeof(IComponentChangeService)); IMobileWebFormServices wfServices = (IMobileWebFormServices)componentSite.GetService(typeof(IMobileWebFormServices)); DialogResult result = DialogResult.Cancel; try { AppliedDeviceFiltersDialog dialog = new AppliedDeviceFiltersDialog( this, _mergingContext ); result = dialog.ShowDialog(); } finally { if (result != DialogResult.Cancel) { SaveChoices(); SetDirty(false); if (changeService != null) { changeService.OnComponentChanged(_designer.UnderlyingControl, null, null, null); } } } } private void OnFilterSelected(Object sender, EventArgs e) { UpdateUI(); } private void OnOK(Object sender, EventArgs e) { SaveChoices(); Close(); DialogResult = DialogResult.OK; } private void OnCancel(Object sender, EventArgs e) { Close(); DialogResult = DialogResult.Cancel; } private void OnPropertyValueChanged(Object sender, PropertyValueChangedEventArgs e) { SetDirty(true); } //////////////////////////////////////////////////////////////////////// // End Event Handling //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Begin IRefreshableComponentEditor Implementation //////////////////////////////////////////////////////////////////////// bool IRefreshableDeviceSpecificEditor.RequestRefresh() { return true; } void IRefreshableDeviceSpecificEditor.Refresh( String deviceSpecificID, DeviceSpecific deviceSpecific ) { if (_currentDeviceSpecificID != null) { CacheCurrentState(); } _cbChoices.Items.Clear(); if (!RestoreState(deviceSpecificID)) { LoadChoices(deviceSpecific); if(!ValidateLoadedChoices()) { _designer.RefreshHeader( MobileControlDesigner.MergingContextProperties ); } } UpdateUI(); } void IRefreshableDeviceSpecificEditor.UnderlyingObjectsChanged() { SaveChoices(); SetDirty(false); } private bool InExternalCacheEditMode { get { return _cacheBuffer != null; } } private IDictionary _cacheBuffer = null; void IRefreshableDeviceSpecificEditor.BeginExternalDeviceSpecificEdit() { Debug.Assert(!InExternalCacheEditMode, "Call to BeginExternalDeviceSpecificEdit() while already in external " + "cache edit mode."); if(_currentDeviceSpecificID != null) { CacheCurrentState(); _currentDeviceSpecificID = null; } _cacheBuffer = new HybridDictionary( true /* make case-insensitive*/ ); foreach(DictionaryEntry entry in _cachedDeviceSpecifics) { _cacheBuffer.Add(entry.Key, entry.Value); } } void IRefreshableDeviceSpecificEditor.EndExternalDeviceSpecificEdit( bool commitChanges) { Debug.Assert(InExternalCacheEditMode, "Call to EndExternalDeviceSpecificEdit() while not in external " + "cache edit mode."); if(commitChanges) { _cachedDeviceSpecifics = _cacheBuffer; } _cacheBuffer = null; } void IRefreshableDeviceSpecificEditor.DeviceSpecificRenamed( String oldDeviceSpecificID, String newDeviceSpecificID) { Debug.Assert(InExternalCacheEditMode, "Call to DeviceSpecificRenamed() while not in external " + "cache edit mode."); Object value = _cacheBuffer[oldDeviceSpecificID]; if(value != null) { _cacheBuffer.Remove(oldDeviceSpecificID); _cacheBuffer.Add(newDeviceSpecificID, value); } } void IRefreshableDeviceSpecificEditor.DeviceSpecificDeleted( String deviceSpecificID) { Debug.Assert(InExternalCacheEditMode, "Call to DeviceSpecificDeleted() while not in external " + "cache edit mode."); _cacheBuffer.Remove(deviceSpecificID); } //////////////////////////////////////////////////////////////////////// // End IRefreshableComponentEditor Implementation //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Begin IDeviceSpecificDesigner Implementation //////////////////////////////////////////////////////////////////////// void IDeviceSpecificDesigner.SetDeviceSpecificEditor (IRefreshableDeviceSpecificEditor editor) { } String IDeviceSpecificDesigner.CurrentDeviceSpecificID { get { return _currentDeviceSpecificID; } } System.Windows.Forms.Control IDeviceSpecificDesigner.Header { get { return _header; } } System.Web.UI.Control IDeviceSpecificDesigner.UnderlyingControl { get { return _designer.UnderlyingControl; } } Object IDeviceSpecificDesigner.UnderlyingObject { get { return _designer.UnderlyingObject; } } bool IDeviceSpecificDesigner.GetDeviceSpecific(String deviceSpecificParentID, out DeviceSpecific ds) { Debug.Assert(deviceSpecificParentID == _currentDeviceSpecificID); ds = null; if (_cbChoices.Items.Count > 0) { ds = new DeviceSpecific(); foreach (ChoiceTreeNode choiceNode in _cbChoices.Items) { DeviceSpecificChoice choice = choiceNode.Choice.RuntimeChoice; ds.Choices.Add(choice); } } return true; } void IDeviceSpecificDesigner.SetDeviceSpecific(String deviceSpecificParentID, DeviceSpecific ds) { Debug.Assert(_currentDeviceSpecificID != null); _cbChoices.Items.Clear(); LoadChoices(ds); UpdateUI(); } void IDeviceSpecificDesigner.InitHeader(int mergingContext) { HeaderPanel panel = new HeaderPanel(); HeaderLabel lblDescription = new HeaderLabel(); lblDescription.TabIndex = 0; lblDescription.Text = SR.GetString(SR.MobileControl_SettingGenericChoiceDescription); panel.Height = lblDescription.Height; panel.Width = lblDescription.Width; panel.Controls.Add(lblDescription); _header = panel; } void IDeviceSpecificDesigner.RefreshHeader(int mergingContext) { } void IDeviceSpecificDesigner.UseCurrentDeviceSpecificID() { } ///////////////////////////////////////////////////////////////////////// // End IDeviceSpecificDesigner Implementation ///////////////////////////////////////////////////////////////////////// } //////////////////////////////////////////////////////////////////////////// // Begin Internal Class //////////////////////////////////////////////////////////////////////////// [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class ChoicePropertyFilter : ICustomTypeDescriptor, IDeviceSpecificChoiceDesigner, IComponent { private DeviceSpecificChoice _choice; private Object _copyOfOriginalObject; private Object _underlyingObject; private IDeviceSpecificDesigner _designer; private Hashtable _specialProp_buffer = new Hashtable(); private EventHandler _specialProp_delegate = null; private ISite _site = null; private EventHandlerList _events; private static readonly Object _eventDisposed = new Object(); private static readonly String _alternateUrl = "AlternateUrl"; private static readonly String _navigateUrl = "NavigateUrl"; internal ChoicePropertyFilter( DeviceSpecificChoice choice, IDeviceSpecificDesigner designer, ISite site ) { _events = new EventHandlerList(); _choice = choice; _site = site; _designer = designer; CreateLocalCopiesOfObjects(); } private void CreateLocalCopiesOfObjects() { // We make this copy of the original to remove the object from // the inheritance chain. _copyOfOriginalObject = CloneTarget(_designer.UnderlyingObject); _underlyingObject = CloneTarget(_designer.UnderlyingObject); // We need to pop up editors when certain property values change RegisterForPropertyChangeEvents(); // Copy properties set on DeviceSpecificChoice ApplyChoiceToRuntimeControl(); } internal void Refresh() { ApplyChangesToRuntimeChoice(); CreateLocalCopiesOfObjects(); } private void RegisterForPropertyChangeEvents() { foreach(PropertyDescriptor property in TypeDescriptor.GetProperties( _underlyingObject.GetType() )) { if(property.Converter is NavigateUrlConverter && (property.Name == _navigateUrl || property.Name == _alternateUrl)) { // if (property.Name == _navigateUrl) { _specialProp_delegate = new EventHandler(OnNavigateUrlChanged); } else { _specialProp_delegate = new EventHandler(OnAlternateUrlChanged); } _specialProp_buffer[property.Name] = property.GetValue(_underlyingObject); property.AddValueChanged( _underlyingObject, _specialProp_delegate ); } } } private Object CloneTarget(Object target) { Object clone = Activator.CreateInstance( target.GetType() ); // We need to copy the Site over to the new object incase setting // properties has a side effect that requires the component model // to be intact. (e.g., Launching UrlPicker for NavigateUrl). if(clone is IComponent) { ((IComponent)clone).Site = ((IComponent)target).Site; } // We also need to copy the Page over in case runtime properties // try to access the page. if(clone is System.Web.UI.Control) { ((Control)clone).Page = ((Control)target).Page; } CopyOverridableProperties(target, clone); return clone; } private void CopyStyleProperties(Style source, Style dest) { // We copy the StateBag to duplicate the style properties without // walking the inheritance. dest.State.Clear(); foreach(String key in source.State.Keys) { dest.State[key] = source.State[key]; } } private void CopyOverridableProperties(Object source, Object dest) { MobileControl destControl = null; // HACK: To avoid copying expandable property FontInfo. We will // need to required that expandable properties implement // ICloneable for our designer extensibility story. if(source is Style) { CopyStyleProperties((Style)source, (Style)dest); return; } if(source is MobileControl) { // If the control is a MobileControl, we copy the style's // StateBag to get the non-inherited proprety values. destControl = (MobileControl) dest; MobileControl sourceControl = (MobileControl) source; CopyStyleProperties(sourceControl.Style, destControl.Style); } // Copy remaining properties not contained in the style (or // all properties if not a mobile control.) PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(dest.GetType()); foreach(PropertyDescriptor property in properties) { if(IsDeviceOverridable(property) && (destControl == null || !PropertyExistsInStyle(property, destControl.Style))) { CopyProperty(property, source, dest); } } } private void CopyProperty(PropertyDescriptor property, Object source, Object dest) { Object value = property.GetValue(source); if(property.Converter is ExpandableObjectConverter) { if(value is ICloneable) { value = ((ICloneable)value).Clone(); } else { throw new Exception( SR.GetString( SR.PropertyOverridesDialog_NotICloneable, property.Name, property.PropertyType.FullName ) ); } } property.SetValue(dest, value); } private bool PropertyExistsInStyle( PropertyDescriptor property, Style style) { return style.GetType().GetProperty(property.Name) != null; } public event EventHandler Disposed { add { _events.AddHandler(_eventDisposed, value); } remove { _events.RemoveHandler(_eventDisposed, value); } } public ISite Site { get { Debug.Assert(_site != null); return _site; } set { _site = value; } } public void Dispose() { if (_events != null) { EventHandler handler = (EventHandler)_events[_eventDisposed]; if (handler != null) handler(this, EventArgs.Empty); } } private void OnNavigateUrlChanged(Object sender, EventArgs e) { OnSpecialPropertyChanged(sender, true); } private void OnAlternateUrlChanged(Object sender, EventArgs e) { OnSpecialPropertyChanged(sender, false); } // private void OnSpecialPropertyChanged(Object sender, bool navigateUrl) { IComponent component = (IComponent) sender; PropertyDescriptor property = TypeDescriptor.GetProperties(component)[navigateUrl ? _navigateUrl : _alternateUrl]; String newValue = (String) property.GetValue(component); String oldValue = (String) _specialProp_buffer[navigateUrl ? _navigateUrl : _alternateUrl]; newValue = NavigateUrlConverter.GetUrl( component, newValue, oldValue ); property.RemoveValueChanged( _underlyingObject, _specialProp_delegate ); property.SetValue(component, newValue); property.AddValueChanged( _underlyingObject, _specialProp_delegate ); } private static bool IsDeviceOverridable(PropertyDescriptor property) { // return ( property.IsBrowsable && ((!property.IsReadOnly) || (property.Converter is ExpandableObjectConverter)) && !property.SerializationVisibility.Equals( DesignerSerializationVisibility.Hidden) && property.Name != "ID" ); } private void ApplyChoiceToRuntimeControl() { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( _underlyingObject.GetType()); foreach(PropertyDescriptor property in properties) { if(IsDeviceOverridable(property)) { ApplyChoiceToRuntimeControl_helper( property, _underlyingObject, "" ); } } } private void ApplyChoiceToRuntimeControl_helper( PropertyDescriptor property, Object target, String prefix ) { String propertyName = prefix + property.Name; String value = ((IAttributeAccessor)_choice).GetAttribute(propertyName) as String; if(property.Converter is ExpandableObjectConverter) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( property.PropertyType ); foreach(PropertyDescriptor embeddedProperty in properties) { if(IsDeviceOverridable(embeddedProperty)) { ApplyChoiceToRuntimeControl_helper( embeddedProperty, property.GetValue(target), propertyName + "-" ); } } return; } if(value != null) { try { property.SetValue( target, property.Converter.ConvertFromString(value) ); } catch { GenericUI.ShowWarningMessage( SR.GetString(SR.PropertyOverridesDialog_Title), SR.GetString( SR.PropertyOverridesDialog_InvalidPropertyValue, value, propertyName ) ); } } } private void ApplyChangesToRuntimeChoice() { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( _underlyingObject.GetType() ); foreach(PropertyDescriptor property in properties) { if (IsDeviceOverridable(property)) { ApplyChangesToRuntimeChoice_helper( property, _copyOfOriginalObject, _underlyingObject, ""); } } } private void ApplyChangesToRuntimeChoice_helper( PropertyDescriptor property, Object sourceTarget, Object destTarget, String prefix ) { Object oldValue = property.GetValue(sourceTarget); Object newValue = property.GetValue(destTarget); String propertyName = prefix + property.Name; if(property.Converter is ExpandableObjectConverter) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( newValue.GetType() ); foreach(PropertyDescriptor embeddedProperty in properties) { if(IsDeviceOverridable(embeddedProperty)) { ApplyChangesToRuntimeChoice_helper( embeddedProperty, oldValue, newValue, propertyName + "-" ); } } } else if(IsDeviceOverridable(property)) { IAttributeAccessor overrides = (IAttributeAccessor)_choice; String oldValueString = property.Converter.ConvertToInvariantString( oldValue ); String newValueString = property.Converter.ConvertToInvariantString( newValue ); if(newValueString != oldValueString) { overrides.SetAttribute(propertyName, newValueString); } else { // Clear any previous values we might have loaded overrides.SetAttribute(propertyName, null); } } } internal DeviceSpecificChoice RuntimeChoice { get { ApplyChangesToRuntimeChoice(); return _choice; } } internal IDeviceSpecificDesigner Designer { get { return _designer; } } internal Object Owner { get { return _underlyingObject; } } private PropertyDescriptorCollection PreFilterProperties( PropertyDescriptorCollection originalProperties ) { PropertyDescriptorCollection newProperties = new PropertyDescriptorCollection( new PropertyDescriptor[] {} ); foreach(PropertyDescriptor property in originalProperties) { if (IsDeviceOverridable(property)) { newProperties.Add(property); } } PropertyDescriptor[] arpd = new PropertyDescriptor[newProperties.Count]; for(int i = 0; i < newProperties.Count; i++) { arpd[i] = newProperties[i]; } newProperties = new PropertyDescriptorCollection(arpd); return newProperties; } //////////////////////////////////////////////////////////////////// // Begin ICustomTypeDescriptor Implementation //////////////////////////////////////////////////////////////////// System.ComponentModel.AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this.GetType()); } String ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this.GetType()); } String ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this.GetType()); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this.GetType()); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this.GetType()); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this.GetType()); } Object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this.GetType(), editorBaseType); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this.GetType()); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this.GetType(), attributes); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { PropertyDescriptorCollection collection = TypeDescriptor.GetProperties( _underlyingObject.GetType() ); collection = PreFilterProperties(collection); return collection; } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection collection = TypeDescriptor.GetProperties( _underlyingObject.GetType(), attributes ); collection = PreFilterProperties(collection); return collection; } Object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor property) { return _underlyingObject; } //////////////////////////////////////////////////////////////////////// // End ICustomTypeDescriptor Implementation //////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Begin IDeviceSpecificChoiceDesigner Implementation /////////////////////////////////////////////////////////////////////// Object IDeviceSpecificChoiceDesigner.UnderlyingObject { get { return _designer.UnderlyingObject; } } Control IDeviceSpecificChoiceDesigner.UnderlyingControl { get { return _designer.UnderlyingControl; } } /////////////////////////////////////////////////////////////////////// // End IDeviceSpecificChoiceDesigner Implementation /////////////////////////////////////////////////////////////////////// } //////////////////////////////////////////////////////////////////////////// // End Internal Class //////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // Begin Internal Class ///////////////////////////////////////////////////////////////////////// [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class PropertyOverridesCachedState : DeviceSpecificDialogCachedState { private ArrayList _cachedComboBox = null; internal PropertyOverridesCachedState( ComboBox comboBox ) { _cachedComboBox = new ArrayList(); foreach(Object o in comboBox.Items) { _cachedComboBox.Add(o); } } internal void Restore( ComboBox comboBox ) { Object selectedItem = comboBox.SelectedItem; comboBox.Items.Clear(); comboBox.Items.AddRange(_cachedComboBox.ToArray()); if(selectedItem != null) { int index = comboBox.Items.IndexOf(selectedItem); if(index >= 0) { comboBox.SelectedItem = comboBox.Items[index]; } } } internal bool FilterExistsInComboBox(DeviceFilterNode filter) { foreach(DeviceFilterNode availableFilter in _cachedComboBox) { if(availableFilter.Name == filter.Name) { return true; } } return false; } internal void SaveChoicesFromComboBox( IDeviceSpecificDesigner designer, String deviceSpecificID ) { SaveChoices(designer, deviceSpecificID, _cachedComboBox); } internal ArrayList Choices { get { return _cachedComboBox; } } } ///////////////////////////////////////////////////////////////////////// // End Internal Class ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // Begin Internal Class ///////////////////////////////////////////////////////////////////////// [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class InvalidChoiceException : ApplicationException { internal InvalidChoiceException(String message) : base(message) { } } ///////////////////////////////////////////////////////////////////////// // End Internal Class ///////////////////////////////////////////////////////////////////////// }
// 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.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeInfos.EcmaFormat; using System.Reflection.Runtime.ParameterInfos; using System.Reflection.Runtime.ParameterInfos.EcmaFormat; using System.Reflection.Runtime.CustomAttributes; using System.Runtime; using System.Runtime.InteropServices; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Runtime.CompilerServices; using Internal.Runtime.TypeLoader; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Runtime.MethodInfos.EcmaFormat { // // Implements methods and properties common to RuntimeMethodInfo and RuntimeConstructorInfo. // internal struct EcmaFormatMethodCommon : IRuntimeMethodCommon<EcmaFormatMethodCommon>, IEquatable<EcmaFormatMethodCommon> { public bool IsGenericMethodDefinition { get { return _method.GetGenericParameters().Count > 0; } } public MethodInvoker GetUncachedMethodInvoker(RuntimeTypeInfo[] methodArguments, MemberInfo exceptionPertainant) { return ReflectionCoreExecution.ExecutionEnvironment.GetMethodInvoker(DeclaringType, new QMethodDefinition(Reader, MethodHandle), methodArguments, exceptionPertainant); } public QSignatureTypeHandle[] QualifiedMethodSignature { get { return this.MethodSignature; } } public EcmaFormatMethodCommon RuntimeMethodCommonOfUninstantiatedMethod { get { return new EcmaFormatMethodCommon(MethodHandle, _definingTypeInfo, _definingTypeInfo); } } public void FillInMetadataDescribedParameters(ref VirtualRuntimeParameterInfoArray result, QSignatureTypeHandle[] typeSignatures, MethodBase contextMethod, TypeContext typeContext) { foreach (ParameterHandle parameterHandle in _method.GetParameters()) { Parameter parameterRecord = _reader.GetParameter(parameterHandle); int index = parameterRecord.SequenceNumber; result[index] = EcmaFormatMethodParameterInfo.GetEcmaFormatMethodParameterInfo( contextMethod, _methodHandle, index - 1, parameterHandle, typeSignatures[index], typeContext); } } public RuntimeTypeInfo[] GetGenericTypeParametersWithSpecifiedOwningMethod(RuntimeNamedMethodInfo<EcmaFormatMethodCommon> owningMethod) { GenericParameterHandleCollection genericParameters = _method.GetGenericParameters(); int genericParametersCount = genericParameters.Count; if (genericParametersCount == 0) return Array.Empty<RuntimeTypeInfo>(); RuntimeTypeInfo[] genericTypeParameters = new RuntimeTypeInfo[genericParametersCount]; int i = 0; foreach (GenericParameterHandle genericParameterHandle in genericParameters) { RuntimeTypeInfo genericParameterType = EcmaFormatRuntimeGenericParameterTypeInfoForMethods.GetRuntimeGenericParameterTypeInfoForMethods(owningMethod, Reader, genericParameterHandle); genericTypeParameters[i++] = genericParameterType; } return genericTypeParameters; } // // methodHandle - the "tkMethodDef" that identifies the method. // definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // public EcmaFormatMethodCommon(MethodDefinitionHandle methodHandle, EcmaFormatRuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo) { _definingTypeInfo = definingTypeInfo; _methodHandle = methodHandle; _contextTypeInfo = contextTypeInfo; _reader = definingTypeInfo.Reader; _method = _reader.GetMethodDefinition(methodHandle); } public MethodAttributes Attributes { get { return _method.Attributes; } } public CallingConventions CallingConvention { get { BlobReader signatureBlob = _reader.GetBlobReader(_method.Signature); CallingConventions result; SignatureHeader sigHeader = signatureBlob.ReadSignatureHeader(); if (sigHeader.CallingConvention == SignatureCallingConvention.VarArgs) result = CallingConventions.VarArgs; else result = CallingConventions.Standard; if (sigHeader.IsInstance) result |= CallingConventions.HasThis; if (sigHeader.HasExplicitThis) result |= CallingConventions.ExplicitThis; return result; } } public RuntimeTypeInfo ContextTypeInfo { get { return _contextTypeInfo; } } public IEnumerable<CustomAttributeData> CustomAttributes { get { IEnumerable<CustomAttributeData> customAttributes = RuntimeCustomAttributeData.GetCustomAttributes(_reader, _method.GetCustomAttributes()); foreach (CustomAttributeData cad in customAttributes) yield return cad; if (0 != (_method.ImplAttributes & MethodImplAttributes.PreserveSig)) yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(PreserveSigAttribute), null, null); } } public RuntimeTypeInfo DeclaringType { get { return _contextTypeInfo; } } public RuntimeNamedTypeInfo DefiningTypeInfo { get { return _definingTypeInfo; } } public MethodImplAttributes MethodImplementationFlags { get { return _method.ImplAttributes; } } public Module Module { get { return _definingTypeInfo.Module; } } public int MetadataToken { get { return MetadataTokens.GetToken(_methodHandle); } } public RuntimeMethodHandle GetRuntimeMethodHandle(Type[] genericArgs) { Debug.Assert(genericArgs == null || genericArgs.Length > 0); RuntimeTypeHandle[] genericArgHandles; if (genericArgs != null) { genericArgHandles = new RuntimeTypeHandle[genericArgs.Length]; for (int i = 0; i < genericArgHandles.Length; i++) genericArgHandles[i] = genericArgs[i].TypeHandle; } else { genericArgHandles = null; } IntPtr dynamicModule = ModuleList.Instance.GetModuleInfoForMetadataReader(Reader).DynamicModulePtrAsIntPtr; return TypeLoaderEnvironment.Instance.GetRuntimeMethodHandleForComponents( DeclaringType.TypeHandle, Name, RuntimeSignature.CreateFromMethodHandle(dynamicModule, MetadataToken), genericArgHandles); } // // Returns the ParameterInfo objects for the method parameters and return parameter. // // The ParameterInfo objects will report "contextMethod" as their Member property and use it to get type variable information from // the contextMethod's declaring type. The actual metadata, however, comes from "this." // // The methodTypeArguments provides the fill-ins for any method type variable elements in the parameter type signatures. // // Does not array-copy. // public RuntimeParameterInfo[] GetRuntimeParameters(MethodBase contextMethod, RuntimeTypeInfo[] methodTypeArguments, out RuntimeParameterInfo returnParameter) { MetadataReader reader = _reader; TypeContext typeContext = contextMethod.DeclaringType.CastToRuntimeTypeInfo().TypeContext; typeContext = new TypeContext(typeContext.GenericTypeArguments, methodTypeArguments); QSignatureTypeHandle[] typeSignatures = this.MethodSignature; int count = typeSignatures.Length; VirtualRuntimeParameterInfoArray result = new VirtualRuntimeParameterInfoArray(count); foreach (ParameterHandle parameterHandle in _method.GetParameters()) { Parameter parameterRecord = _reader.GetParameter(parameterHandle); int index = parameterRecord.SequenceNumber; result[index] = EcmaFormatMethodParameterInfo.GetEcmaFormatMethodParameterInfo( contextMethod, _methodHandle, index - 1, parameterHandle, typeSignatures[index], typeContext); } for (int i = 0; i < count; i++) { if (result[i] == null) { result[i] = RuntimeThinMethodParameterInfo.GetRuntimeThinMethodParameterInfo( contextMethod, i - 1, typeSignatures[i], typeContext); } } returnParameter = result.First; return result.Remainder; } public String Name { get { return _method.Name.GetString(_reader); } } public MetadataReader Reader { get { return _reader; } } public MethodDefinitionHandle MethodHandle { get { return _methodHandle; } } public override bool Equals(Object obj) { if (!(obj is EcmaFormatMethodCommon)) return false; return Equals((EcmaFormatMethodCommon)obj); } public bool Equals(EcmaFormatMethodCommon other) { if (!(_reader == other._reader)) return false; if (!(_methodHandle.Equals(other._methodHandle))) return false; if (!(_contextTypeInfo.Equals(other._contextTypeInfo))) return false; return true; } public override int GetHashCode() { return _methodHandle.GetHashCode() ^ _contextTypeInfo.GetHashCode(); } private QSignatureTypeHandle[] MethodSignature { get { BlobReader signatureBlob = _reader.GetBlobReader(_method.Signature); SignatureHeader header = signatureBlob.ReadSignatureHeader(); if (header.Kind != SignatureKind.Method) throw new BadImageFormatException(); int genericParameterCount = 0; if (header.IsGeneric) genericParameterCount = signatureBlob.ReadCompressedInteger(); int numParameters = signatureBlob.ReadCompressedInteger(); QSignatureTypeHandle[] signatureHandles = new QSignatureTypeHandle[checked(numParameters + 1)]; signatureHandles[0] = new QSignatureTypeHandle(_reader, signatureBlob); EcmaMetadataHelpers.SkipType(ref signatureBlob); for (int i = 0 ; i < numParameters; i++) { signatureHandles[i + 1] = new QSignatureTypeHandle(_reader, signatureBlob); } return signatureHandles; } } private readonly EcmaFormatRuntimeNamedTypeInfo _definingTypeInfo; private readonly MethodDefinitionHandle _methodHandle; private readonly RuntimeTypeInfo _contextTypeInfo; private readonly MetadataReader _reader; private readonly MethodDefinition _method; } }
// 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.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private class PostProcessor { private readonly SemanticModel _semanticModel; private readonly int _contextPosition; public PostProcessor(SemanticModel semanticModel, int contextPosition) { Contract.ThrowIfNull(semanticModel); _semanticModel = semanticModel; _contextPosition = contextPosition; } public IEnumerable<StatementSyntax> RemoveRedundantBlock(IEnumerable<StatementSyntax> statements) { // it must have only one statement if (statements.Count() != 1) { return statements; } // that statement must be a block var block = statements.Single() as BlockSyntax; if (block == null) { return statements; } // we have a block, remove them return RemoveRedundantBlock(block); } private IEnumerable<StatementSyntax> RemoveRedundantBlock(BlockSyntax block) { // if block doesn't have any statement if (block.Statements.Count == 0) { // either remove the block if it doesn't have any trivia, or return as it is if // there are trivia attached to block return (block.OpenBraceToken.GetAllTrivia().IsEmpty() && block.CloseBraceToken.GetAllTrivia().IsEmpty()) ? SpecializedCollections.EmptyEnumerable<StatementSyntax>() : SpecializedCollections.SingletonEnumerable<StatementSyntax>(block); } // okay transfer asset attached to block to statements var firstStatement = block.Statements.First(); var firstToken = firstStatement.GetFirstToken(includeZeroWidth: true); var firstTokenWithAsset = block.OpenBraceToken.CopyAnnotationsTo(firstToken).WithPrependedLeadingTrivia(block.OpenBraceToken.GetAllTrivia()); var lastStatement = block.Statements.Last(); var lastToken = lastStatement.GetLastToken(includeZeroWidth: true); var lastTokenWithAsset = block.CloseBraceToken.CopyAnnotationsTo(lastToken).WithAppendedTrailingTrivia(block.CloseBraceToken.GetAllTrivia()); // create new block with new tokens block = block.ReplaceTokens(new[] { firstToken, lastToken }, (o, c) => (o == firstToken) ? firstTokenWithAsset : lastTokenWithAsset); // return only statements without the wrapping block return block.Statements; } public IEnumerable<StatementSyntax> MergeDeclarationStatements(IEnumerable<StatementSyntax> statements) { if (statements.FirstOrDefault() == null) { return statements; } return MergeDeclarationStatementsWorker(statements); } private IEnumerable<StatementSyntax> MergeDeclarationStatementsWorker(IEnumerable<StatementSyntax> statements) { var map = new Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>>(); foreach (var statement in statements) { if (!IsDeclarationMergable(statement)) { foreach (var declStatement in GetMergedDeclarationStatements(map)) { yield return declStatement; } yield return statement; continue; } AppendDeclarationStatementToMap(statement as LocalDeclarationStatementSyntax, map); } // merge leftover if (map.Count <= 0) { yield break; } foreach (var declStatement in GetMergedDeclarationStatements(map)) { yield return declStatement; } } private void AppendDeclarationStatementToMap( LocalDeclarationStatementSyntax statement, Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map) { Contract.ThrowIfNull(statement); var type = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, statement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; Contract.ThrowIfNull(type); map.GetOrAdd(type, _ => new List<LocalDeclarationStatementSyntax>()).Add(statement); } private IEnumerable<LocalDeclarationStatementSyntax> GetMergedDeclarationStatements( Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map) { foreach (var keyValuePair in map) { Contract.ThrowIfFalse(keyValuePair.Value.Count > 0); // merge all variable decl for current type var variables = new List<VariableDeclaratorSyntax>(); foreach (var statement in keyValuePair.Value) { foreach (var variable in statement.Declaration.Variables) { variables.Add(variable); } } // and create one decl statement // use type name from the first decl statement yield return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(keyValuePair.Value.First().Declaration.Type, SyntaxFactory.SeparatedList(variables))); } map.Clear(); } private bool IsDeclarationMergable(StatementSyntax statement) { Contract.ThrowIfNull(statement); // to be mergable, statement must be // 1. decl statement without any extra info // 2. no initialization on any of its decls // 3. no trivia except whitespace // 4. type must be known var declarationStatement = statement as LocalDeclarationStatementSyntax; if (declarationStatement == null) { return false; } if (declarationStatement.Modifiers.Count > 0 || declarationStatement.IsConst || declarationStatement.IsMissing) { return false; } if (ContainsAnyInitialization(declarationStatement)) { return false; } if (!ContainsOnlyWhitespaceTrivia(declarationStatement)) { return false; } var semanticInfo = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, declarationStatement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; if (semanticInfo == null || semanticInfo.TypeKind == TypeKind.Error || semanticInfo.TypeKind == TypeKind.Unknown) { return false; } return true; } private bool ContainsAnyInitialization(LocalDeclarationStatementSyntax statement) { foreach (var variable in statement.Declaration.Variables) { if (variable.Initializer != null) { return true; } } return false; } private static bool ContainsOnlyWhitespaceTrivia(StatementSyntax statement) { foreach (var token in statement.DescendantTokens()) { foreach (var trivia in token.LeadingTrivia.Concat(token.TrailingTrivia)) { if (trivia.Kind() != SyntaxKind.WhitespaceTrivia && trivia.Kind() != SyntaxKind.EndOfLineTrivia) { return false; } } } return true; } public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern(IEnumerable<StatementSyntax> statements) { // if we have inline temp variable as service, we could just use that service here. // since it is not a service right now, do very simple clean up if (statements.ElementAtOrDefault(2) != null) { return statements; } var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax; var returnStatement = statements.ElementAtOrDefault(1) as ReturnStatementSyntax; if (declaration == null || returnStatement == null) { return statements; } if (declaration.Declaration == null || declaration.Declaration.Variables.Count != 1 || declaration.Declaration.Variables[0].Initializer == null || declaration.Declaration.Variables[0].Initializer.Value == null || declaration.Declaration.Variables[0].Initializer.Value is StackAllocArrayCreationExpressionSyntax || returnStatement.Expression == null) { return statements; } if (!ContainsOnlyWhitespaceTrivia(declaration) || !ContainsOnlyWhitespaceTrivia(returnStatement)) { return statements; } var variableName = declaration.Declaration.Variables[0].Identifier.ToString(); if (returnStatement.Expression.ToString() != variableName) { return statements; } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value)); } public IEnumerable<StatementSyntax> RemoveDeclarationAssignmentPattern(IEnumerable<StatementSyntax> statements) { // if we have inline temp variable as service, we could just use that service here. // since it is not a service right now, do very simple clean up var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax; var assignment = statements.ElementAtOrDefault(1) as ExpressionStatementSyntax; if (declaration == null || assignment == null) { return statements; } if (ContainsAnyInitialization(declaration) || declaration.Declaration == null || declaration.Declaration.Variables.Count != 1 || assignment.Expression == null || assignment.Expression.Kind() != SyntaxKind.SimpleAssignmentExpression) { return statements; } if (!ContainsOnlyWhitespaceTrivia(declaration) || !ContainsOnlyWhitespaceTrivia(assignment)) { return statements; } var variableName = declaration.Declaration.Variables[0].Identifier.ToString(); var assignmentExpression = assignment.Expression as AssignmentExpressionSyntax; if (assignmentExpression.Left == null || assignmentExpression.Right == null || assignmentExpression.Left.ToString() != variableName) { return statements; } var variable = declaration.Declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(assignmentExpression.Right)); return SpecializedCollections.SingletonEnumerable<StatementSyntax>( declaration.WithDeclaration( declaration.Declaration.WithVariables( SyntaxFactory.SingletonSeparatedList(variable)))).Concat(statements.Skip(2)); } } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.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. // * 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 Rodrigo B. de Oliveira 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 Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.Services; using Boo.Lang.Compiler.TypeSystem; using Boo.Lang.Environments; using Boo.Lang.Resources; namespace Boo.Lang.Compiler { public static class CompilerWarningFactory { public static class Codes { public const string ImplicitReturn = "BCW0023"; public const string VisibleMemberDoesNotDeclareTypeExplicitely = "BCW0024"; public const string ImplicitDowncast = "BCW0028"; } public static CompilerWarning CustomWarning(Node node, string msg) { return CustomWarning(AstUtil.SafeLexicalInfo(node), msg); } public static CompilerWarning CustomWarning(LexicalInfo lexicalInfo, string msg) { return new CompilerWarning(lexicalInfo, msg); } public static CompilerWarning CustomWarning(string msg) { return new CompilerWarning(msg); } public static CompilerWarning AbstractMemberNotImplemented(Node node, IType type, IMember member) { return Instantiate("BCW0001", AstUtil.SafeLexicalInfo(node), type, member); } public static CompilerWarning ModifiersInLabelsHaveNoEffect(Node node) { return Instantiate("BCW0002", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning UnusedLocalVariable(Node node, string name) { return Instantiate("BCW0003", AstUtil.SafeLexicalInfo(node), name); } public static CompilerWarning IsInsteadOfIsa(Node node) { return Instantiate("BCW0004", AstUtil.SafeLexicalInfo(node), LanguageAmbiance.IsKeyword, LanguageAmbiance.IsaKeyword); } private static LanguageAmbiance LanguageAmbiance { get { return My<LanguageAmbiance>.Instance; } } public static CompilerWarning InvalidEventUnsubscribe(Node node, IEvent eventName, CallableSignature expected) { return Instantiate("BCW0005", AstUtil.SafeLexicalInfo(node), eventName, expected); } public static CompilerWarning AssignmentToTemporary(Node node) { return Instantiate("BCW0006", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning EqualsInsteadOfAssign(BinaryExpression node) { return Instantiate("BCW0007", AstUtil.SafeLexicalInfo(node), node.ToCodeString()); } public static CompilerWarning DuplicateNamespace(Import import, string name) { return Instantiate("BCW0008", AstUtil.SafeLexicalInfo(import.Expression), name); } public static CompilerWarning HaveBothKeyFileAndAttribute(Node node) { return Instantiate("BCW0009", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning HaveBothKeyNameAndAttribute(Node node) { return Instantiate("BCW0010", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning AbstractMemberNotImplementedStubCreated(Node node, IType type, IMember abstractMember) { return Instantiate("BCW0011", AstUtil.SafeLexicalInfo(node), type, abstractMember); } public static CompilerWarning Obsolete(Node node, object entity, string message) { return Instantiate("BCW0012", AstUtil.SafeLexicalInfo(node), entity ?? node, message); } public static CompilerWarning StaticClassMemberRedundantlyMarkedStatic(Node node, string typeName, string memberName) { return Instantiate("BCW0013", AstUtil.SafeLexicalInfo(node), typeName, memberName); } public static CompilerWarning PrivateMemberNeverUsed(TypeMember member) { return Instantiate("BCW0014", AstUtil.SafeLexicalInfo(member), MemberVisibilityString(member), NodeTypeString(member), member.FullName); } public static CompilerWarning UnreachableCodeDetected(Node node) { return Instantiate("BCW0015", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning NamespaceNeverUsed(Import node) { return Instantiate("BCW0016", AstUtil.SafeLexicalInfo(node.Expression), node.Expression.ToCodeString()); } public static CompilerWarning NewProtectedMemberInSealedType(TypeMember member) { return Instantiate("BCW0017", AstUtil.SafeLexicalInfo(member), NodeTypeString(member), member.Name, member.DeclaringType.Name); } public static CompilerWarning OverridingFinalizeIsBadPractice(TypeMember member) { return Instantiate("BCW0018", AstUtil.SafeLexicalInfo(member)); } public static CompilerWarning AmbiguousExceptionName(ExceptionHandler node) { return Instantiate("BCW0019", AstUtil.SafeLexicalInfo(node), node.Declaration.Name); } public static CompilerWarning AssignmentToSameVariable(BinaryExpression node) { return Instantiate("BCW0020", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning ComparisonWithSameVariable(BinaryExpression node) { return Instantiate("BCW0021", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning ConstantExpression(Expression node) { return Instantiate("BCW0022", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning ImplicitReturn(Method node) { return Instantiate(Codes.ImplicitReturn, AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning VisibleMemberDoesNotDeclareTypeExplicitely(TypeMember node) { return VisibleMemberDoesNotDeclareTypeExplicitely(node, null); } public static CompilerWarning VisibleMemberDoesNotDeclareTypeExplicitely(TypeMember node, string argument) { string details = (null == argument) ? StringResources.BooC_Return : string.Format(StringResources.BooC_NamedArgument, argument); return Instantiate(Codes.VisibleMemberDoesNotDeclareTypeExplicitely, AstUtil.SafeLexicalInfo(node), NodeTypeString(node), details); } public static CompilerWarning AmbiguousVariableName(Local node, string localName, string baseName) { return Instantiate("BCW0025", AstUtil.SafeLexicalInfo(node), localName, baseName); } public static CompilerWarning LikelyTypoInTypeMemberName(TypeMember node, string suggestion) { return Instantiate("BCW0026", AstUtil.SafeLexicalInfo(node), node.Name, suggestion); } public static CompilerWarning ObsoleteSyntax(Node anchor, string obsoleteSyntax, string newSyntax) { return ObsoleteSyntax(AstUtil.SafeLexicalInfo(anchor), obsoleteSyntax, newSyntax); } public static CompilerWarning ObsoleteSyntax(LexicalInfo location, string obsoleteSyntax, string newSyntax) { return Instantiate("BCW0027", location, obsoleteSyntax, newSyntax); } public static CompilerWarning ImplicitDowncast(Node node, IType expectedType, IType actualType) { return Instantiate(Codes.ImplicitDowncast, AstUtil.SafeLexicalInfo(node), actualType, expectedType); } public static CompilerWarning MethodHidesInheritedNonVirtual(Node anchor, IMethod hidingMethod, IMethod hiddenMethod) { return Instantiate("BCW0029", AstUtil.SafeLexicalInfo(anchor), hidingMethod, hiddenMethod); } private static CompilerWarning Instantiate(string code, LexicalInfo location, params object[] args) { return new CompilerWarning(code, location, Array.ConvertAll<object, string>(args, CompilerErrorFactory.DisplayStringFor)); } private static string NodeTypeString(Node node) { return node.NodeType.ToString().ToLower(); } private static string MemberVisibilityString(TypeMember member) { switch (member.Modifiers & TypeMemberModifiers.VisibilityMask) { case TypeMemberModifiers.Private: return "Private"; case TypeMemberModifiers.Internal: return "Internal"; case TypeMemberModifiers.Protected: return "Protected"; } return "Public"; } } }
using UnityEngine; namespace Pathfinding { [AddComponentMenu("Pathfinding/GraphUpdateScene")] /** Helper class for easily updating graphs. * * The GraphUpdateScene component is really easy to use. Create a new empty GameObject and add the component to it, it can be found in Components-->Pathfinding-->GraphUpdateScene.\n * When you have added the component, you should see something like the image below. * \shadowimage{graphUpdateScene.png} * The region which the component will affect is defined by creating a polygon in the scene. * If you make sure you have the Position tool enabled (top-left corner of the Unity window) you can shift+click in the scene view to add more points to the polygon. * You can remove points using shift+alt+click. * By clicking on the points you can bring up a positioning tool. You can also open the "points" array in the inspector to set each point's coordinates manually. * \shadowimage{graphUpdateScenePoly.png} * In the inspector there are a number of variables. The first one is named "Convex", it sets if the convex hull of the points should be calculated or if the polygon should be used as-is. * Using the convex hull is faster when applying the changes to the graph, but with a non-convex polygon you can specify more complicated areas.\n * The next two variables, called "Apply On Start" and "Apply On Scan" determine when to apply the changes. If the object is in the scene from the beginning, both can be left on, it doesn't * matter since the graph is also scanned at start. However if you instantiate it later in the game, you can make it apply it's setting directly, or wait until the next scan (if any). * If the graph is rescanned, all GraphUpdateScene components which have the Apply On Scan variable toggled will apply their settings again to the graph since rescanning clears all previous changes.\n * You can also make it apply it's changes using scripting. * \code GetComponent<GraphUpdateScene>().Apply (); \endcode * The above code will make it apply its changes to the graph (assuming a GraphUpdateScene component is attached to the same GameObject). * * Next there is "Modify Walkability" and "Set Walkability" (which appears when "Modify Walkability" is toggled). * If Modify Walkability is set, then all nodes inside the area will either be set to walkable or unwalkable depending on the value of the "Set Walkability" variable. * * Penalty can also be applied to the nodes. A higher penalty (aka weight) makes the nodes harder to traverse so it will try to avoid those areas. * * The tagging variables can be read more about on this page: \ref tags "Working with tags". * * \note The Y (up) axis of the transform that this component is attached to should be in the same direction as the up direction of the graph. * So if you for example have a grid in the XY plane then the transform should have the rotation (-90,0,0). */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_graph_update_scene.php")] public class GraphUpdateScene : GraphModifier { /** Points which define the region to update */ public Vector3[] points; /** Private cached convex hull of the #points */ private Vector3[] convexPoints; /** Use the convex hull of the points. */ public bool convex = true; /** Minumum height of the bounds of the resulting Graph Update Object. * Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a * zero height graph update object would usually result in no nodes being updated. */ public float minBoundsHeight = 1; /** Penalty to add to nodes. * Be careful when setting negative values since if a node get's a negative penalty it will underflow and instead get * really large. In most cases a warning will be logged if that happens. */ public int penaltyDelta; /** Set to true to set all targeted nodese walkability to #setWalkability */ public bool modifyWalkability; /** See #modifyWalkability */ public bool setWalkability; /** Apply this graph update object on start */ public bool applyOnStart = true; /** Apply this graph update object whenever a graph is rescanned */ public bool applyOnScan = true; /** Update node's walkability and connectivity using physics functions. * For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph. * If enabled for grid graphs, #modifyWalkability will be ignored. * * For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object * using raycasts (if enabled). * */ public bool updatePhysics; /** \copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics */ public bool resetPenaltyOnPhysics = true; /** \copydoc Pathfinding::GraphUpdateObject::updateErosion */ public bool updateErosion = true; /** If enabled, set all nodes' tags to #setTag */ public bool modifyTag; /** If #modifyTag is enabled, set all nodes' tags to this value */ public int setTag; /** Emulates behavior from before version 4.0 */ [HideInInspector] public bool legacyMode = false; /** Private cached inversion of #setTag. * Used for InvertSettings() */ private int setTagInvert; /** Has apply been called yet. * Used to prevent applying twice when both applyOnScan and applyOnStart are enabled */ private bool firstApplied; [SerializeField] private int serializedVersion = 0; /** Use world space for coordinates. * If true, the shape will not follow when moving around the transform. * * \see #ToggleUseWorldSpace */ [SerializeField] [UnityEngine.Serialization.FormerlySerializedAs("useWorldSpace")] private bool legacyUseWorldSpace; /** Do some stuff at start */ public void Start () { if (!Application.isPlaying) return; // If firstApplied is true, that means the graph was scanned during Awake. // So we shouldn't apply it again because then we would end up applying it two times if (!firstApplied && applyOnStart) { Apply(); } } public override void OnPostScan () { if (applyOnScan) Apply(); } /** Inverts all invertable settings for this GUS. * Namely: penalty delta, walkability, tags. * * Penalty delta will be changed to negative penalty delta.\n * #setWalkability will be inverted.\n * #setTag will be stored in a private variable, and the new value will be 0. When calling this function again, the saved * value will be the new value. * * Calling this function an even number of times without changing any settings in between will be identical to no change in settings. */ public virtual void InvertSettings () { setWalkability = !setWalkability; penaltyDelta = -penaltyDelta; if (setTagInvert == 0) { setTagInvert = setTag; setTag = 0; } else { setTag = setTagInvert; setTagInvert = 0; } } /** Recalculate convex hull. * Will not do anything if #convex is disabled. */ public void RecalcConvex () { convexPoints = convex ? Polygon.ConvexHullXZ(points) : null; } /** Switches between using world space and using local space. * \deprecated World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space. */ [System.ObsoleteAttribute("World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space.", true)] void ToggleUseWorldSpace () { } /** Lock all points to a specific Y value. * \deprecated The Y coordinate is no longer important. Use the position of the object instead. */ [System.ObsoleteAttribute("The Y coordinate is no longer important. Use the position of the object instead", true)] public void LockToY () { } /** Calculates the bounds for this component. * This is a relatively expensive operation, it needs to go through all points and * run matrix multiplications. */ public Bounds GetBounds () { if (points == null || points.Length == 0) { Bounds bounds; var coll = GetComponent<Collider>(); var coll2D = GetComponent<Collider2D>(); var rend = GetComponent<Renderer>(); if (coll != null) bounds = coll.bounds; else if (coll2D != null) { bounds = coll2D.bounds; bounds.size = new Vector3(bounds.size.x, bounds.size.y, Mathf.Max(bounds.size.z, 1f)); } else if (rend != null) { bounds = rend.bounds; } else { return new Bounds(Vector3.zero, Vector3.zero); } if (legacyMode && bounds.size.y < minBoundsHeight) bounds.size = new Vector3(bounds.size.x, minBoundsHeight, bounds.size.z); return bounds; } else { return GraphUpdateShape.GetBounds(convex ? convexPoints : points, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight); } } /** Updates graphs with a created GUO. * Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape * representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs. * This will not update graphs immediately. See AstarPath.UpdateGraph for more info. */ public void Apply () { if (AstarPath.active == null) { Debug.LogError("There is no AstarPath object in the scene", this); return; } GraphUpdateObject guo; if (points == null || points.Length == 0) { var polygonCollider = GetComponent<PolygonCollider2D>(); if (polygonCollider != null) { var points2D = polygonCollider.points; Vector3[] pts = new Vector3[points2D.Length]; for (int i = 0; i < pts.Length; i++) { var p = points2D[i] + polygonCollider.offset; pts[i] = new Vector3(p.x, 0, p.y); } var mat = transform.localToWorldMatrix * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 0, 0), Vector3.one); var shape = new GraphUpdateShape(points, convex, mat, minBoundsHeight); guo = new GraphUpdateObject(GetBounds()); guo.shape = shape; } else { var bounds = GetBounds(); if (bounds.center == Vector3.zero && bounds.size == Vector3.zero) { Debug.LogError("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached", this); return; } guo = new GraphUpdateObject(bounds); } } else { GraphUpdateShape shape; if (legacyMode && !legacyUseWorldSpace) { // Used for compatibility with older versions var worldPoints = new Vector3[points.Length]; for (int i = 0; i < points.Length; i++) worldPoints[i] = transform.TransformPoint(points[i]); shape = new GraphUpdateShape(worldPoints, convex, Matrix4x4.identity, minBoundsHeight); } else { shape = new GraphUpdateShape(points, convex, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight); } var bounds = shape.GetBounds(); guo = new GraphUpdateObject(bounds); guo.shape = shape; } firstApplied = true; guo.modifyWalkability = modifyWalkability; guo.setWalkability = setWalkability; guo.addPenalty = penaltyDelta; guo.updatePhysics = updatePhysics; guo.updateErosion = updateErosion; guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics; guo.modifyTag = modifyTag; guo.setTag = setTag; AstarPath.active.UpdateGraphs(guo); } /** Draws some gizmos */ void OnDrawGizmos () { OnDrawGizmos(false); } /** Draws some gizmos */ void OnDrawGizmosSelected () { OnDrawGizmos(true); } /** Draws some gizmos */ void OnDrawGizmos (bool selected) { Color c = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f); if (selected) { Gizmos.color = Color.Lerp(c, new Color(1, 1, 1, 0.2f), 0.9f); Bounds b = GetBounds(); Gizmos.DrawCube(b.center, b.size); Gizmos.DrawWireCube(b.center, b.size); } if (points == null) return; if (convex) c.a *= 0.5f; Gizmos.color = c; Matrix4x4 matrix = legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix; if (convex) { c.r -= 0.1f; c.g -= 0.2f; c.b -= 0.1f; Gizmos.color = c; } if (selected || !convex) { for (int i = 0; i < points.Length; i++) { Gizmos.DrawLine(matrix.MultiplyPoint3x4(points[i]), matrix.MultiplyPoint3x4(points[(i+1)%points.Length])); } } if (convex) { if (convexPoints == null) RecalcConvex(); Gizmos.color = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f); for (int i = 0; i < convexPoints.Length; i++) { Gizmos.DrawLine(matrix.MultiplyPoint3x4(convexPoints[i]), matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length])); } } // Draw the full 3D shape var pts = convex ? convexPoints : points; if (selected && pts != null && pts.Length > 0) { Gizmos.color = new Color(1, 1, 1, 0.2f); float miny = pts[0].y, maxy = pts[0].y; for (int i = 0; i < pts.Length; i++) { miny = Mathf.Min(miny, pts[i].y); maxy = Mathf.Max(maxy, pts[i].y); } var extraHeight = Mathf.Max(minBoundsHeight - (maxy - miny), 0) * 0.5f; miny -= extraHeight; maxy += extraHeight; for (int i = 0; i < pts.Length; i++) { var next = (i+1) % pts.Length; var p1 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(miny - pts[i].y)); var p2 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(maxy - pts[i].y)); var p1n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(miny - pts[next].y)); var p2n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(maxy - pts[next].y)); Gizmos.DrawLine(p1, p2); Gizmos.DrawLine(p1, p1n); Gizmos.DrawLine(p2, p2n); } } } /** Disables legacy mode if it is enabled. * Legacy mode is automatically enabled for components when upgrading from an earlier version than 3.8.6. */ public void DisableLegacyMode () { if (legacyMode) { legacyMode = false; if (legacyUseWorldSpace) { legacyUseWorldSpace = false; for (int i = 0; i < points.Length; i++) { points[i] = transform.InverseTransformPoint(points[i]); } RecalcConvex(); } } } protected override void Awake () { if (serializedVersion == 0) { // Use the old behavior if some points are already set if (points != null && points.Length > 0) legacyMode = true; serializedVersion = 1; } base.Awake(); } } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * 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. ******************************************************************************/ using SharpBox2D.Callbacks; using SharpBox2D.Collision.Broadphase; using SharpBox2D.Dynamics.Contacts; namespace SharpBox2D.Dynamics { /** * Delegate of World. * * @author Daniel Murphy */ public class ContactManager : PairCallback { public BroadPhase m_broadPhase; public Contact m_contactList; public int m_contactCount; public ContactFilter m_contactFilter; public ContactListener m_contactListener; private World pool; public ContactManager(World argPool, BroadPhase broadPhase) { m_contactList = null; m_contactCount = 0; m_contactFilter = new ContactFilter(); m_contactListener = null; m_broadPhase = broadPhase; pool = argPool; } /** * Broad-phase callback. * * @param proxyUserDataA * @param proxyUserDataB */ public void addPair(object proxyUserDataA, object proxyUserDataB) { FixtureProxy proxyA = (FixtureProxy) proxyUserDataA; FixtureProxy proxyB = (FixtureProxy) proxyUserDataB; Fixture fixtureA = proxyA.fixture; Fixture fixtureB = proxyB.fixture; int indexA = proxyA.childIndex; int indexB = proxyB.childIndex; Body bodyA = fixtureA.getBody(); Body bodyB = fixtureB.getBody(); // Are the fixtures on the same body? if (bodyA == bodyB) { return; } // TODO_ERIN use a hash table to remove a potential bottleneck when both // bodies have a lot of contacts. // Does a contact already exist? ContactEdge edge = bodyB.getContactList(); while (edge != null) { if (edge.other == bodyA) { Fixture fA = edge.contact.getFixtureA(); Fixture fB = edge.contact.getFixtureB(); int iA = edge.contact.getChildIndexA(); int iB = edge.contact.getChildIndexB(); if (fA == fixtureA && iA == indexA && fB == fixtureB && iB == indexB) { // A contact already exists. return; } if (fA == fixtureB && iA == indexB && fB == fixtureA && iB == indexA) { // A contact already exists. return; } } edge = edge.next; } // Does a joint override collision? is at least one body dynamic? if (bodyB.shouldCollide(bodyA) == false) { return; } // Check user filtering. if (m_contactFilter != null && m_contactFilter.shouldCollide(fixtureA, fixtureB) == false) { return; } // Call the factory. Contact c = pool.popContact(fixtureA, indexA, fixtureB, indexB); if (c == null) { return; } // Contact creation may swap fixtures. fixtureA = c.getFixtureA(); fixtureB = c.getFixtureB(); indexA = c.getChildIndexA(); indexB = c.getChildIndexB(); bodyA = fixtureA.getBody(); bodyB = fixtureB.getBody(); // Insert into the world. c.m_prev = null; c.m_next = m_contactList; if (m_contactList != null) { m_contactList.m_prev = c; } m_contactList = c; // Connect to island graph. // Connect to body A c.m_nodeA.contact = c; c.m_nodeA.other = bodyB; c.m_nodeA.prev = null; c.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = c.m_nodeA; } bodyA.m_contactList = c.m_nodeA; // Connect to body B c.m_nodeB.contact = c; c.m_nodeB.other = bodyA; c.m_nodeB.prev = null; c.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = c.m_nodeB; } bodyB.m_contactList = c.m_nodeB; // wake up the bodies if (!fixtureA.isSensor() && !fixtureB.isSensor()) { bodyA.setAwake(true); bodyB.setAwake(true); } ++m_contactCount; } public void findNewContacts() { m_broadPhase.updatePairs(this); } public void destroy(Contact c) { Fixture fixtureA = c.getFixtureA(); Fixture fixtureB = c.getFixtureB(); Body bodyA = fixtureA.getBody(); Body bodyB = fixtureB.getBody(); if (m_contactListener != null && c.isTouching()) { m_contactListener.endContact(c); } // Remove from the world. if (c.m_prev != null) { c.m_prev.m_next = c.m_next; } if (c.m_next != null) { c.m_next.m_prev = c.m_prev; } if (c == m_contactList) { m_contactList = c.m_next; } // Remove from body 1 if (c.m_nodeA.prev != null) { c.m_nodeA.prev.next = c.m_nodeA.next; } if (c.m_nodeA.next != null) { c.m_nodeA.next.prev = c.m_nodeA.prev; } if (c.m_nodeA == bodyA.m_contactList) { bodyA.m_contactList = c.m_nodeA.next; } // Remove from body 2 if (c.m_nodeB.prev != null) { c.m_nodeB.prev.next = c.m_nodeB.next; } if (c.m_nodeB.next != null) { c.m_nodeB.next.prev = c.m_nodeB.prev; } if (c.m_nodeB == bodyB.m_contactList) { bodyB.m_contactList = c.m_nodeB.next; } // Call the factory. pool.pushContact(c); --m_contactCount; } /** * This is the top level collision call for the time step. Here all the narrow phase collision is * processed for the world contact list. */ public void collide() { // Update awake contacts. Contact c = m_contactList; while (c != null) { Fixture fixtureA = c.getFixtureA(); Fixture fixtureB = c.getFixtureB(); int indexA = c.getChildIndexA(); int indexB = c.getChildIndexB(); Body bodyA = fixtureA.getBody(); Body bodyB = fixtureB.getBody(); // is this contact flagged for filtering? if ((c.m_flags & Contact.FILTER_FLAG) == Contact.FILTER_FLAG) { // Should these bodies collide? if (bodyB.shouldCollide(bodyA) == false) { Contact cNuke = c; c = cNuke.getNext(); destroy(cNuke); continue; } // Check user filtering. if (m_contactFilter != null && m_contactFilter.shouldCollide(fixtureA, fixtureB) == false) { Contact cNuke = c; c = cNuke.getNext(); destroy(cNuke); continue; } // Clear the filtering flag. c.m_flags &= ~Contact.FILTER_FLAG; } bool activeA = bodyA.isAwake() && bodyA.m_type != BodyType.STATIC; bool activeB = bodyB.isAwake() && bodyB.m_type != BodyType.STATIC; // At least one body must be awake and it must be dynamic or kinematic. if (activeA == false && activeB == false) { c = c.getNext(); continue; } int proxyIdA = fixtureA.m_proxies[indexA].proxyId; int proxyIdB = fixtureB.m_proxies[indexB].proxyId; bool overlap = m_broadPhase.testOverlap(proxyIdA, proxyIdB); // Here we destroy contacts that cease to overlap in the broad-phase. if (overlap == false) { Contact cNuke = c; c = cNuke.getNext(); destroy(cNuke); continue; } // The contact persists. c.update(m_contactListener); c = c.getNext(); } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter // and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g. // // await nonGenericTask; // ===================== // var $awaiter = nonGenericTask.GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL: // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // $awaiter.GetResult(); // // result += await genericTask.ConfigureAwait(false); // =================================================================================== // var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL; // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // result += $awaiter.GetResult(); // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Diagnostics.Tracing; using System.Threading; using System.Threading.Tasks; // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, // NullReferenceExceptions may be generated (the alternative would be for us to detect // this case and then throw a different exception instead). This is the same tradeoff // that's made with other compiler-focused value types like List<T>.Enumerator. namespace System.Runtime.CompilerServices { /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access the generic TaskAwaiter<> as TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param> internal TaskAwaiter(Task task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { ValidateEnd(m_task); } /// <summary> /// Fast checks for the end of an await operation to determine whether more needs to be done /// prior to completing the await. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] internal static void ValidateEnd(Task task) { // Fast checks that can be inlined. if (task.IsWaitNotificationEnabledOrNotRanToCompletion) { // If either the end await bit is set or we're not completed successfully, // fall back to the slower path. HandleNonSuccessAndDebuggerNotification(task); } } /// <summary> /// Ensures the task is completed, triggers any necessary debugger breakpoints for completing /// the await on the task, and throws an exception if the task did not complete successfully. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] private static void HandleNonSuccessAndDebuggerNotification(Task task) { // NOTE: The JIT refuses to inline ValidateEnd when it contains the contents // of HandleNonSuccessAndDebuggerNotification, hence the separation. // Synchronously wait for the task to complete. When used by the compiler, // the task will already be complete. This code exists only for direct GetResult use, // for cases where the same exception propagation semantics used by "await" are desired, // but where for one reason or another synchronous rather than asynchronous waiting is needed. if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default); Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested task.NotifyDebuggerOfWaitCompletionIfNecessary(); // And throw an exception if the task is faulted or canceled. if (!task.IsCompletedSuccessfully) ThrowForNonSuccess(task); } /// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary> [StackTraceHidden] private static void ThrowForNonSuccess(Task task) { Debug.Assert(task.IsCompleted, "Task must have been completed by now."); Debug.Assert(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); // Handle whether the task has been canceled or faulted switch (task.Status) { // If the task completed in a canceled state, throw an OperationCanceledException. // This will either be the OCE that actually caused the task to cancel, or it will be a new // TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the // completed task's CancellationToken if it has one, including that CT in the OCE. case TaskStatus.Canceled: var oceEdi = task.GetCancellationExceptionDispatchInfo(); if (oceEdi != null) { oceEdi.Throw(); Debug.Fail("Throw() should have thrown"); } throw new TaskCanceledException(task); // If the task faulted, throw its first exception, // even if it contained more than one. case TaskStatus.Faulted: var edis = task.GetExceptionDispatchInfos(); if (edis.Count > 0) { edis[0].Throw(); Debug.Fail("Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { Debug.Fail("There should be exceptions if we're Faulted."); throw task.Exception!; } } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) throw new ArgumentNullException(nameof(continuation)); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { continuation = OutputWaitEtwEvents(task, continuation); } // Set the continuation onto the awaited task. task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="stateMachineBox">The box to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> internal static void UnsafeOnCompletedInternal(Task task, IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) { Debug.Assert(stateMachineBox != null); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { task.SetContinuationForAwait(OutputWaitEtwEvents(task, stateMachineBox.MoveNextAction), continueOnCapturedContext, flowExecutionContext: false); } else { task.UnsafeSetContinuationForAwait(stateMachineBox, continueOnCapturedContext); } } /// <summary> /// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event. /// </summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <returns>The action to use as the actual continuation.</returns> private static Action OutputWaitEtwEvents(Task task, Action continuation) { Debug.Assert(task != null, "Need a task to wait on"); Debug.Assert(continuation != null, "Need a continuation to invoke when the wait completes"); if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(task); } var log = TplEventSource.Log; if (log.IsEnabled()) { // ETW event for Task Wait Begin var currentTaskAtBegin = Task.InternalCurrent; // If this task's continuation is another task, get it. var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); log.TaskWaitBegin( (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler!.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id, TplEventSource.TaskWaitBehavior.Asynchronous, (continuationTask != null ? continuationTask.Id : 0)); } // Create a continuation action that outputs the end event and then invokes the user // provided delegate. This incurs the allocations for the closure/delegate, but only if the event // is enabled, and in doing so it allows us to pass the awaited task's information into the end event // in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter // just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred). return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, (innerContinuation,innerTask) => { if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(innerTask); } TplEventSource innerEtwLog = TplEventSource.Log; // ETW event for Task Wait End. Guid prevActivityId = new Guid(); bool bEtwLogEnabled = innerEtwLog.IsEnabled(); if (bEtwLogEnabled) { var currentTaskAtEnd = Task.InternalCurrent; innerEtwLog.TaskWaitEnd( (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler!.Id : TaskScheduler.Default.Id), (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), innerTask.Id); // Ensure the continuation runs under the activity ID of the task that completed for the // case the antecedent is a promise (in the other cases this is already the case). if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(TplEventSource.CreateGuidForTaskID(innerTask.Id), out prevActivityId); } // Invoke the original continuation provided to OnCompleted. innerContinuation(); if (bEtwLogEnabled) { innerEtwLog.TaskWaitContinuationComplete(innerTask.Id); if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(prevActivityId); } }, task); } } /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter<TResult> : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access TaskAwaiter<> as the non-generic TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param> internal TaskAwaiter(Task<TResult> task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// TaskAwaiter or a TaskAwaiter`1. It must not be implemented by any other /// awaiters. /// </summary> internal interface ITaskAwaiter { } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// CTA.ConfiguredTaskAwaiter or a CTA`1.ConfiguredTaskAwaiter. It must not /// be implemented by any other awaiters. /// </summary> internal interface IConfiguredTaskAwaiter { } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable { /// <summary>The task being awaited.</summary> private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaitable requires a task to await."); m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access the generic ConfiguredTaskAwaiter as this. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> internal readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured /// when BeginAwait is called; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable<TResult> { /// <summary>The underlying awaitable on whose logic this awaitable relies.</summary> private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access this as the non-generic ConfiguredTaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.Web.UI.Page.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI { public partial class Page : TemplateControl, System.Web.IHttpHandler { #region Methods and constructors protected internal void AddContentTemplate (string templateName, ITemplate template) { } public void AddOnPreRenderCompleteAsync (System.Web.BeginEventHandler beginHandler, System.Web.EndEventHandler endHandler, Object state) { } public void AddOnPreRenderCompleteAsync (System.Web.BeginEventHandler beginHandler, System.Web.EndEventHandler endHandler) { } protected internal void AddWrappedFileDependencies (Object virtualFileDependencies) { } protected IAsyncResult AspCompatBeginProcessRequest (System.Web.HttpContext context, AsyncCallback cb, Object extraData) { return default(IAsyncResult); } protected void AspCompatEndProcessRequest (IAsyncResult result) { } protected IAsyncResult AsyncPageBeginProcessRequest (System.Web.HttpContext context, AsyncCallback callback, Object extraData) { return default(IAsyncResult); } protected void AsyncPageEndProcessRequest (IAsyncResult result) { } protected internal virtual new HtmlTextWriter CreateHtmlTextWriter (TextWriter tw) { return default(HtmlTextWriter); } public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType) { return default(HtmlTextWriter); } public void DesignerInitialize () { } protected internal virtual new System.Collections.Specialized.NameValueCollection DeterminePostBackMode () { Contract.Requires (this.Context != null); return default(System.Collections.Specialized.NameValueCollection); } public void ExecuteRegisteredAsyncTasks () { } public override Control FindControl (string id) { return default(Control); } protected override void FrameworkInitialize () { } public Object GetDataItem () { return default(Object); } public string GetPostBackClientEvent (Control control, string argument) { return default(string); } public string GetPostBackClientHyperlink (Control control, string argument) { return default(string); } public string GetPostBackEventReference (Control control) { return default(string); } public string GetPostBackEventReference (Control control, string argument) { return default(string); } public virtual new int GetTypeHashCode () { return default(int); } public ValidatorCollection GetValidators (string validationGroup) { Contract.Ensures (Contract.Result<System.Web.UI.ValidatorCollection>() != null); return default(ValidatorCollection); } protected Object GetWrappedFileDependencies (string[] virtualFileDependencies) { Contract.Ensures (Contract.Result<System.Object>() == virtualFileDependencies); Contract.Ensures (virtualFileDependencies.Length >= 0); return default(Object); } protected virtual new void InitializeCulture () { } protected virtual new void InitOutputCache (int duration, string varyByHeader, string varyByCustom, OutputCacheLocation location, string varyByParam) { } protected virtual new void InitOutputCache (int duration, string varyByContentEncoding, string varyByHeader, string varyByCustom, OutputCacheLocation location, string varyByParam) { } protected internal virtual new void InitOutputCache (OutputCacheParameters cacheSettings) { Contract.Requires (cacheSettings != null); Contract.Requires (this.Response.Cache != null); } public bool IsClientScriptBlockRegistered (string key) { return default(bool); } public bool IsStartupScriptRegistered (string key) { return default(bool); } protected internal virtual new Object LoadPageStateFromPersistenceMedium () { return default(Object); } public string MapPath (string virtualPath) { return default(string); } protected internal override void OnInit (EventArgs e) { } protected virtual new void OnInitComplete (EventArgs e) { } protected virtual new void OnLoadComplete (EventArgs e) { } protected virtual new void OnPreInit (EventArgs e) { } protected virtual new void OnPreLoad (EventArgs e) { } protected virtual new void OnPreRenderComplete (EventArgs e) { } protected virtual new void OnSaveStateComplete (EventArgs e) { } public Page () { } public virtual new void ProcessRequest (System.Web.HttpContext context) { } protected virtual new void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument) { Contract.Requires (sourceControl != null); } public void RegisterArrayDeclaration (string arrayName, string arrayValue) { } public void RegisterAsyncTask (PageAsyncTask task) { } public virtual new void RegisterClientScriptBlock (string key, string script) { } public virtual new void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue) { } public void RegisterOnSubmitStatement (string key, string script) { } public void RegisterRequiresControlState (Control control) { } public void RegisterRequiresPostBack (Control control) { Contract.Requires (control != null); } public virtual new void RegisterRequiresRaiseEvent (IPostBackEventHandler control) { } public void RegisterRequiresViewStateEncryption () { } public virtual new void RegisterStartupScript (string key, string script) { } public void RegisterViewStateHandler () { } protected internal override void Render (HtmlTextWriter writer) { } public bool RequiresControlState (Control control) { return default(bool); } protected internal virtual new void SavePageStateToPersistenceMedium (Object state) { } public void SetFocus (Control control) { } public void SetFocus (string clientID) { Contract.Ensures (clientID.Trim().Length >= 1); } public void UnregisterRequiresControlState (Control control) { } public virtual new void Validate (string validationGroup) { } public virtual new void Validate () { } public virtual new void VerifyRenderingInServerForm (Control control) { } #endregion #region Properties and indexers public System.Web.HttpApplicationState Application { get { return default(System.Web.HttpApplicationState); } } protected bool AspCompatMode { get { return default(bool); } set { } } protected bool AsyncMode { get { return default(bool); } set { } } public TimeSpan AsyncTimeout { get { return default(TimeSpan); } set { } } public Control AutoPostBackControl { get { return default(Control); } set { } } public bool Buffer { get { Contract.Ensures (Contract.Result<bool>() == this.Response.BufferOutput); return default(bool); } set { Contract.Ensures (value == this.Response.BufferOutput); } } public System.Web.Caching.Cache Cache { get { Contract.Ensures (Contract.Result<System.Web.Caching.Cache>() != null); return default(System.Web.Caching.Cache); } } public string ClientQueryString { get { return default(string); } } public ClientScriptManager ClientScript { get { Contract.Ensures (Contract.Result<System.Web.UI.ClientScriptManager>() != null); return default(ClientScriptManager); } } public string ClientTarget { get { return default(string); } set { } } public int CodePage { get { Contract.Requires (this.Response.ContentEncoding != null); Contract.Ensures (this.Response.ContentEncoding != null); Contract.Ensures (Contract.Result<int>() == this.Response.ContentEncoding.CodePage); return default(int); } set { Contract.Ensures (this.Response.ContentEncoding != null); } } public string ContentType { get { Contract.Ensures (Contract.Result<string>() == this.Response.ContentType); return default(string); } set { Contract.Ensures (value == this.Response.ContentType); } } internal protected override System.Web.HttpContext Context { get { return default(System.Web.HttpContext); } } public string Culture { get { Contract.Ensures(Contract.Result<string>() != null); Contract.Ensures(Contract.Result<string>() == System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName); return default(string); } set { Contract.Requires (value != null); } } public virtual new bool EnableEventValidation { get { return default(bool); } set { } } public override bool EnableViewState { get { return default(bool); } set { } } public bool EnableViewStateMac { get { return default(bool); } set { } } public string ErrorPage { get { return default(string); } set { } } protected System.Collections.ArrayList FileDependencies { set { } } public System.Web.UI.HtmlControls.HtmlForm Form { get { return default(System.Web.UI.HtmlControls.HtmlForm); } } public System.Web.UI.HtmlControls.HtmlHead Header { get { return default(System.Web.UI.HtmlControls.HtmlHead); } } public override string ID { get { return default(string); } set { } } public virtual new char IdSeparator { get { Contract.Requires (this.PageAdapter != null); return default(char); } } public bool IsAsync { get { return default(bool); } } public bool IsCallback { get { return default(bool); } } public bool IsCrossPagePostBack { get { return default(bool); } } public bool IsPostBack { get { return default(bool); } } public bool IsPostBackEventControlRegistered { get { return default(bool); } } public bool IsReusable { get { return default(bool); } } public bool IsValid { get { return default(bool); } } public System.Collections.IDictionary Items { get { Contract.Ensures (Contract.Result<System.Collections.IDictionary>() != null); return default(System.Collections.IDictionary); } } public int LCID { get { Contract.Ensures (Contract.Result<int>() == System.Threading.Thread.CurrentThread.CurrentCulture.LCID); return default(int); } set { } } public bool MaintainScrollPositionOnPostBack { get { return default(bool); } set { } } public MasterPage Master { get { return default(MasterPage); } } public virtual new string MasterPageFile { get { return default(string); } set { } } public int MaxPageStateFieldLength { get { return default(int); } set { } } #if NETFRAMEWORK_4_0 public string MetaDescription { get { Contract.Requires (this.Page != null); Contract.Requires (this.Page.Header != null); return default(string); } set { Contract.Requires (this.Page != null); } } public string MetaKeywords { get { Contract.Requires (this.Page != null); Contract.Requires (this.Page.Header != null); return default(string); } set { Contract.Requires (this.Page != null); } } #endif public System.Web.UI.Adapters.PageAdapter PageAdapter { get { return default(System.Web.UI.Adapters.PageAdapter); } } protected virtual new PageStatePersister PageStatePersister { get { return default(PageStatePersister); } } public System.Web.UI.Page PreviousPage { get { return default(System.Web.UI.Page); } } public System.Web.HttpRequest Request { get { Contract.Ensures(Contract.Result<HttpRequest>() != null); return default(System.Web.HttpRequest); } } public System.Web.HttpResponse Response { get { Contract.Ensures (Contract.Result<System.Web.HttpResponse>() != null); return default(System.Web.HttpResponse); } } public string ResponseEncoding { get { Contract.Requires (this.Response.ContentEncoding != null); Contract.Ensures (this.Response.ContentEncoding != null); Contract.Ensures (this.Response.ContentEncoding.EncodingName != null); Contract.Ensures (Contract.Result<string>() == this.Response.ContentEncoding.EncodingName); return default(string); } set { Contract.Ensures (this.Response.ContentEncoding != null); } } #if NETFRAMEWORK_4_0 public System.Web.Routing.RouteData RouteData { get { return default(System.Web.Routing.RouteData); } } #endif public System.Web.HttpServerUtility Server { get { Contract.Ensures (Contract.Result<System.Web.HttpServerUtility>() == this.Context.Server); return default(System.Web.HttpServerUtility); } } public virtual new System.Web.SessionState.HttpSessionState Session { get { return default(System.Web.SessionState.HttpSessionState); } } public bool SmartNavigation { get { return default(bool); } set { } } public virtual new string StyleSheetTheme { get { return default(string); } set { } } public virtual new string Theme { get { return default(string); } set { } } public string Title { get { Contract.Requires (this.Page != null); Contract.Requires (this.Page.Header != null); return default(string); } set { Contract.Requires (this.Page != null); } } public System.Web.TraceContext Trace { get { Contract.Ensures (Contract.Result<System.Web.TraceContext>() == this.Context.Trace); return default(System.Web.TraceContext); } } public bool TraceEnabled { get { Contract.Requires (this.Trace != null); Contract.Ensures (Contract.Result<bool>() == this.Trace.IsEnabled); Contract.Ensures (this.Trace == this.Context.Trace); return default(bool); } set { Contract.Requires (this.Trace != null); Contract.Ensures (this.Trace == this.Context.Trace); Contract.Ensures (value == this.Trace.IsEnabled); } } public System.Web.TraceMode TraceModeValue { get { Contract.Requires (this.Trace != null); Contract.Ensures (Contract.Result<System.Web.TraceMode>() == this.Trace.TraceMode); Contract.Ensures (this.Trace == this.Context.Trace); return default(System.Web.TraceMode); } set { Contract.Requires (this.Trace != null); Contract.Ensures (this.Trace == this.Context.Trace); Contract.Ensures (value == this.Trace.TraceMode); } } protected int TransactionMode { get { return default(int); } set { } } public string UICulture { get { Contract.Ensures(Contract.Result<string>() != null); Contract.Ensures (Contract.Result<string>() == System.Threading.Thread.CurrentThread.CurrentUICulture.DisplayName); return default(string); } set { Contract.Requires (value != null); } } internal protected virtual new string UniqueFilePathSuffix { get { return default(string); } } public System.Security.Principal.IPrincipal User { get { Contract.Ensures (Contract.Result<System.Security.Principal.IPrincipal>() == this.Context.User); return default(System.Security.Principal.IPrincipal); } } public ValidatorCollection Validators { get { Contract.Ensures (Contract.Result<System.Web.UI.ValidatorCollection>() != null); return default(ValidatorCollection); } } public ViewStateEncryptionMode ViewStateEncryptionMode { get { return default(ViewStateEncryptionMode); } set { } } public string ViewStateUserKey { get { return default(string); } set { } } public override bool Visible { get { return default(bool); } set { } } #endregion #region Fields #endregion } }
using PlayFab.ClientModels; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; /// <summary> /// Promotional item types. /// </summary> public enum PromotionalItemTypes { None, News, Image, Sale, Event, Tip } public class UB_PromotionalItem { public string PromoTitle; public DateTime TimeStamp; public string PromoBody; public string PromoBanner; public string PromoSplash; public string PromoId; public Dictionary<string, string> CustomTags = new Dictionary<string, string>(); public PromotionalItemTypes PromoType; } public class UB_LevelData { public string Description; public string Icon; public string StatsPrefix; public int? MinEntryLevel; public UB_LevelWinConditions WinConditions; public Dictionary<string, UB_LevelAct> Acts; public string RestrictedToEventKey; } public class UB_LevelAct { public string Background; public string UsePregeneratedEncounter; public UB_LevelEncounters CreepEncounters; public UB_LevelEncounters MegaCreepEncounters; public UB_LevelEncounters RareCreepEncounters; public UB_LevelEncounters BossCreepEncounters; public UB_LevelEncounters HeroEncounters; public UB_LevelEncounters StoreEncounters; public string IntroMonolog; public string IntroBossMonolog; public string OutroMonolog; public string FailureMonolog; public bool IsActCompleted; } public class UB_LevelWinConditions { public int SurvivalTime; public long TimeLimit; public int KillCount; public string KillTarget; public bool CompleteAllActs; public int FindCount; public string FindTarget; } public class UB_LevelEncounters { public string EncounterPool; public int MinQuantity; public int MaxQuantity; public float ChanceForAddedEncounters; public List<string> SpawnSpecificEncountersByID; public bool LimitProbabilityToAct; } public class UB_GamePlayEncounter { public string DisplayName; public UB_EncounterData Data; public bool playerCompleted; // not sure about this var public bool isEndOfAct; //TODO add a bool for signals end of act } public enum EncounterTypes { Creep, MegaCreep, RareCreep, BossCreep, Hero, Store } public class UB_EncounterData { public float SpawnWeight; public EncounterTypes EncounterType; public string Description; public string Icon; public Dictionary<string, EnemySpellDetail> Spells; public EnemyVitals Vitals; public EncounterRewards Rewards; // some list of actions public Dictionary<string, string> EncounterActions; public void SetSpellDetails() { if (Spells == null) Spells = new Dictionary<string, EnemySpellDetail>(); foreach (var spell in Spells) { UB_SpellDetail sp; if (!PF_GameData.Spells.TryGetValue(spell.Value.SpellName, out sp) || sp == null) continue; sp = UpgradeSpell(sp, spell.Value.SpellLevel); spell.Value.Detail = sp; Vitals.Spells.Add(spell.Value); } } UB_SpellDetail UpgradeSpell(UB_SpellDetail sp, int level) { for (int z = 0; z < level; z++) { sp.BaseDmg *= Mathf.CeilToInt(1.0f + sp.UpgradePower); if (sp.ApplyStatus != null) { sp.ApplyStatus.ChanceToApply *= 1.0f + sp.UpgradePower; sp.ApplyStatus.ModifyAmount *= 1.0f + sp.UpgradePower; } } return sp; } //ctor public UB_EncounterData() { } //copy ctor public UB_EncounterData(UB_EncounterData prius) { if (prius == null) return; SpawnWeight = prius.SpawnWeight; EncounterType = prius.EncounterType; Description = prius.Description; Icon = prius.Icon; Vitals = new EnemyVitals(prius.Vitals); Rewards = new EncounterRewards(prius.Rewards); EncounterActions = new Dictionary<string, string>(); foreach (var kvp in prius.EncounterActions) EncounterActions.Add(kvp.Key, kvp.Value); Spells = new Dictionary<string, EnemySpellDetail>(); foreach (var spell in prius.Spells) Spells.Add(spell.Key, new EnemySpellDetail(spell.Value)); Vitals.ActiveStati = new List<UB_SpellStatus>(); foreach (var status in prius.Vitals.ActiveStati) Vitals.ActiveStati.Add(new UB_SpellStatus(status)); } } public class UB_Achievement { public string AchievementName; public string MatchingStatistic; public bool SingleStat; public int Threshold; public string Icon; } public class EnemySpellDetail { public string SpellName; public int SpellLevel; public int SpellPriority; public UB_SpellDetail Detail; public bool IsOnCooldown; public int CdTurns; //ctor public EnemySpellDetail() { } //copy ctor public EnemySpellDetail(EnemySpellDetail prius) { if (prius == null) return; SpellName = prius.SpellName; SpellPriority = prius.SpellPriority; SpellLevel = prius.SpellLevel; IsOnCooldown = prius.IsOnCooldown; CdTurns = prius.CdTurns; Detail = new UB_SpellDetail(prius.Detail); } } public class EnemyVitals { public int Health; public int Mana; public int Speed; public int Defense; public int CharacterLevel; public List<string> UsableItems; public List<UB_SpellStatus> ActiveStati; public List<EnemySpellDetail> Spells; public int MaxHealth; public int MaxMana; public int MaxSpeed; public int MaxDefense; //public UB_Spell public void SetMaxVitals() { MaxHealth = Health; MaxMana = Mana; MaxSpeed = Speed; MaxDefense = Defense; Spells = new List<EnemySpellDetail>(); } //ctor public EnemyVitals() { } //Copy ctor public EnemyVitals(EnemyVitals prius) { if (prius == null) return; Health = prius.Health; Mana = prius.Mana; Speed = prius.Speed; Defense = prius.Defense; CharacterLevel = prius.CharacterLevel; MaxHealth = prius.MaxHealth; MaxMana = prius.MaxMana; MaxSpeed = prius.MaxSpeed; MaxDefense = prius.MaxDefense; if (prius.UsableItems != null && prius.UsableItems.Count > 0) UsableItems = prius.UsableItems.ToList(); else UsableItems = new List<string>(); Spells = new List<EnemySpellDetail>(); if (prius.Spells != null && prius.Spells.Count > 0) foreach (var spell in prius.Spells) Spells.Add(new EnemySpellDetail(spell)); ActiveStati = new List<UB_SpellStatus>(); if (prius.ActiveStati != null && prius.ActiveStati.Count > 0) foreach (var status in ActiveStati) ActiveStati.Add(new UB_SpellStatus(status)); } } public class UB_AdData { public AdPlacementDetails Details; } public enum PromotionType { Inactive, Active, ActivePromoted, } public class UB_EventData { public string EventKey; public string EventName; public string EventDescription; public string StoreToUse; public string BundleId; public UB_UnpackedAssetBundle Assets; } public class EncounterRewards { public int XpMin; public int XpMax; public int GoldMin; public int GoldMax; public List<string> ItemsDropped; //ctor public EncounterRewards() { } //copy ctor public EncounterRewards(EncounterRewards prius) { if (prius == null) return; XpMin = prius.XpMin; XpMax = prius.XpMax; GoldMin = prius.GoldMin; GoldMax = prius.GoldMax; ItemsDropped = prius.ItemsDropped.ToList(); } } public class UB_LevelActRewards { public List<string> Easy; public List<string> Medium; public List<string> Hard; public string VictoryEncounter; } public class UB_CharacterData { public UB_ClassDetail ClassDetails; public int TotalExp; public int ExpThisLevel; public int Health; public int Mana; public int Speed; public int Defense; public int CharacterLevel; public int Spell1_Level; public int Spell2_Level; public int Spell3_Level; public string CustomAvatar; } [Serializable] public class UB_ClassDetail { public string Description; public string CatalogCode; public string Icon; public string Spell1; public string Spell2; public string Spell3; public int BaseHP; public int HPLevelBonus; public int BaseMP; public int MPLevelBonus; public int BaseDP; public int DPLevelBonus; public int BaseSP; public int SPLevelBonus; public string Prereq; public string DisplayStatus; } /// <summary> /// /// </summary> [Serializable] public class UB_SpellDetail { public string Description; public string Icon; public string Target; public int BaseDmg; public int ManaCost; public float UpgradePower; public int UpgradeLevels; public string FX; public int Cooldown; public int LevelReq; public UB_SpellStatus ApplyStatus; //ctor public UB_SpellDetail() { } //copy ctor public UB_SpellDetail(UB_SpellDetail prius) { if (prius == null) return; Description = prius.Description; Icon = prius.Icon; Target = prius.Target; BaseDmg = prius.BaseDmg; ManaCost = prius.ManaCost; BaseDmg = prius.BaseDmg; UpgradePower = prius.UpgradePower; UpgradeLevels = prius.UpgradeLevels; FX = prius.FX; Cooldown = prius.Cooldown; LevelReq = prius.LevelReq; ApplyStatus = new UB_SpellStatus(prius.ApplyStatus); } } /// <summary> /// details the attributes for effects to apply when spells hit their target. /// </summary> [Serializable] public class UB_SpellStatus { public string StatusName; public string Target; public string UpgradeReq; public string StatusDescription; public string StatModifierCode; // prbably need to map to an enum public float ModifyAmount; public float ChanceToApply; public int Turns; public string Icon; public string FX; // ctor public UB_SpellStatus() { } //copy ctor public UB_SpellStatus(UB_SpellStatus prius) { if (prius == null) return; StatusName = prius.StatusName; Target = prius.Target; UpgradeReq = prius.UpgradeReq; StatusDescription = prius.StatusDescription; StatModifierCode = prius.StatModifierCode; ModifyAmount = prius.ModifyAmount; ChanceToApply = prius.ChanceToApply; Turns = prius.Turns; Icon = prius.Icon; FX = prius.FX; } } /// <summary> /// details spell attributes /// </summary> public class UB_Spell { public string SpellName; public string Description; public string Icon; public int Dmg; public int Level; public int UpgradeLevels; public string FX; public int Cooldown; public int LevelReq; public UB_SpellStatus ApplyStatus; } /// <summary> /// A wrapper class that contains several important classes for tracking player character state. /// </summary> public class UB_SavedCharacter { public UB_ClassDetail baseClass; public CharacterResult characterDetails; public UB_CharacterData characterData; public PlayerVitals PlayerVitals; public void SetMaxVitals() { PlayerVitals.MaxHealth = characterData.Health; PlayerVitals.MaxMana = characterData.Mana; PlayerVitals.MaxSpeed = characterData.Speed; PlayerVitals.MaxDefense = characterData.Defense; PlayerVitals.Health = characterData.Health; PlayerVitals.Mana = characterData.Mana; PlayerVitals.Speed = characterData.Speed; PlayerVitals.Defense = characterData.Defense; PlayerVitals.ActiveStati.Clear(); PlayerVitals.didLevelUp = false; PlayerVitals.skillSelected = 0; } public void RefillVitals() { PlayerVitals.ActiveStati.Clear(); PlayerVitals.didLevelUp = false; PlayerVitals.skillSelected = 0; PlayerVitals.Health = PlayerVitals.MaxHealth; PlayerVitals.Mana = PlayerVitals.MaxMana; PlayerVitals.Speed = PlayerVitals.MaxSpeed; PlayerVitals.Defense = PlayerVitals.MaxDefense; } public void LevelUpCharacterStats() { //TODO add in this -- needs to have a level up table from title data } //ctor public UB_SavedCharacter() { PlayerVitals = new PlayerVitals { ActiveStati = new List<UB_SpellStatus>() }; } } /// <summary> /// A class for tracking players through combat /// </summary> public class PlayerVitals { public int Health; public int Mana; public int Speed; public int Defense; public List<UB_SpellStatus> ActiveStati; public int MaxHealth; public int MaxMana; public int MaxSpeed; public int MaxDefense; public bool didLevelUp; public int skillSelected; } /// <summary> /// Details the player progress /// </summary> public class QuestTracker { public KeyValuePair<string, UB_LevelAct> CurrentAct; public int ActIndex; public List<string> WinConditions; //TODO hook up these stats public int DamageDone; public int DamageTaken; public int Deaths; public int XpCollected; public int GoldCollected; public List<UB_GamePlayEncounter> CompletedEncounters; public List<string> ItemsFound; public List<ItemGrantResult> ItemsGranted; public int CreepEncounters; public int HeroRescues; public int ItemsUsed; //ctor public QuestTracker() { WinConditions = new List<string>(); CompletedEncounters = new List<UB_GamePlayEncounter>(); ItemsFound = new List<string>(); } public bool isQuestWon = false; public bool areItemsAwarded = false; } /// <summary> /// basic details that describe an item that was granted to the player /// </summary> public class ItemGrantResult { // These are used in Cloud Script public string PlayFabId; public string ItemId; public string ItemInstanceId; public bool Result; } /// <summary> /// A custom grouping optomized for use in UB. /// </summary> public class InventoryCategory { public string itemId = string.Empty; public CatalogItem catalogRef; public List<ItemInstance> inventory; public Sprite icon; public int count { get { return inventory.Count; } } //ctor public InventoryCategory(string id, CatalogItem cat, List<ItemInstance> inv, Sprite icn) { itemId = id; catalogRef = cat; inventory = inv; icon = icn; } }
/* Copyright (c) Citrix Systems 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. * * 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. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using XenAdmin.Dialogs; using XenAPI; using XenAdmin.Commands; namespace XenAdmin.Dialogs { /// <summary> /// A confirmation dialog for Commands. Primarily used for displaying the subset of items from the multiple-selection /// which are not going to be actioned by the Command. /// </summary> internal partial class CommandErrorDialog : XenDialogBase { public enum DialogMode { Close, OKCancel }; public DialogMode Mode { get; private set; } private ListSortDirection m_direction; private DataGridViewColumn m_oldSortedColumn; /// <summary> /// Gets a new <see cref="CommandErrorDialog"/> using the specified parameters. /// </summary> /// <typeparam name="TXenObject">The type of the xen object.</typeparam> /// <param name="title">The title for the confirmation dialog.</param> /// <param name="text">The text for the confirmation dialog.</param> /// <param name="cantExecuteReasons">A dictionary of names of the objects which will be ignored with assoicated reasons.</param> public static CommandErrorDialog Create<TXenObject>(string title, string text, IDictionary<TXenObject, string> cantExecuteReasons) where TXenObject : IXenObject { Dictionary<SelectedItem, string> d = new Dictionary<SelectedItem, string>(); foreach (TXenObject x in cantExecuteReasons.Keys) { d[new SelectedItem(x)] = cantExecuteReasons[x]; } return new CommandErrorDialog(title, text, d); } /// <summary> /// Initializes a new instance of the <see cref="CommandErrorDialog"/> class. /// </summary> /// <param name="title">The title for the confirmation dialog.</param> /// <param name="text">The text for the confirmation dialog.</param> /// <param name="cantExecuteReasons">A dictionary of names of the objects which will be ignored with assoicated reasons.</param> public CommandErrorDialog(string title, string text, IDictionary<SelectedItem, string> cantExecuteReasons) : this(title, text, cantExecuteReasons, DialogMode.Close) { } /// <summary> /// Initializes a new instance of the <see cref="CommandErrorDialog"/> class. /// </summary> /// <param name="title">The title for the confirmation dialog.</param> /// <param name="text">The text for the confirmation dialog.</param> /// <param name="cantExecuteReasons">A dictionary of names of the objects which will be ignored with assoicated reasons.</param> /// <param name="mode">Whether the dialog should show a Close button, or OK and Cancel buttons.</param> public CommandErrorDialog(string title, string text, IDictionary<SelectedItem, string> cantExecuteReasons, DialogMode mode) { Util.ThrowIfParameterNull(cantExecuteReasons, "cantExecuteReasons"); Util.ThrowIfParameterNull(title, "title"); Util.ThrowIfParameterNull(text, "text"); InitializeComponent(); pbQuestion.Image = SystemIcons.Error.ToBitmap(); Text = title; lblText.Text = text; Mode = mode; btnCancel.Visible = mode == DialogMode.OKCancel; btnOK.Visible = mode == DialogMode.OKCancel; btnClose.Visible = mode == DialogMode.Close; foreach (SelectedItem selectedItem in cantExecuteReasons.Keys) { DataGridViewRow row = new DataGridViewRow {Tag = selectedItem.XenObject}; row.Cells.AddRange(new DataGridViewCell[] { new DataGridViewImageCell {Value = Images.GetImage16For(selectedItem.XenObject)}, new DataGridViewTextBoxCell {Value = selectedItem.XenObject.ToString()}, new DataGridViewTextBoxCell {Value = cantExecuteReasons[selectedItem]} }); m_dataGridView.Rows.Add(row); } m_direction = ListSortDirection.Ascending; m_oldSortedColumn = colName; m_dataGridView.Sort(new RowComparer(colName.Index, m_direction)); } private void btnOK_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void m_dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.ColumnIndex < colName.Index || e.ColumnIndex > colReason.Index) return; var newColumn = m_dataGridView.Columns[e.ColumnIndex]; if (m_oldSortedColumn == null) { // the DataGridView is not currently sorted m_direction = ListSortDirection.Ascending; m_oldSortedColumn = newColumn; } else { if (m_oldSortedColumn == newColumn) { // Sort the same column again, reversing the SortOrder. m_direction = (m_direction == ListSortDirection.Ascending) ? ListSortDirection.Descending : ListSortDirection.Ascending; } else { // Sort a new column and remove the SortGlyph from the old column m_direction = ListSortDirection.Ascending; m_oldSortedColumn.HeaderCell.SortGlyphDirection = SortOrder.None; m_oldSortedColumn = newColumn; } } m_dataGridView.Sort(new RowComparer(newColumn.Index, m_direction)); newColumn.HeaderCell.SortGlyphDirection = m_direction == ListSortDirection.Ascending ? SortOrder.Ascending : SortOrder.Descending; } private class RowComparer : IComparer { private readonly int m_columnIndex; private readonly ListSortDirection m_direction; private const int COL_NAME = 1; private const int COL_REASON = 2; public RowComparer(int columnIndex, ListSortDirection direction) { m_columnIndex = columnIndex; m_direction = direction; } public int Compare(object x, object y) { var row1 = (DataGridViewRow)x; var row2 = (DataGridViewRow)y; int result = 0; if (m_columnIndex == COL_NAME) result = ((IXenObject)row1.Tag).CompareTo(row2.Tag); else if (m_columnIndex == COL_REASON) result = string.Compare(row1.Cells[COL_REASON].Value.ToString(), row2.Cells[COL_REASON].Value.ToString()); if (m_direction == ListSortDirection.Descending) return -1 * result; return result; } } } }
// 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.IO; using System.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SendPacketsAsync { private readonly ITestOutputHelper _log; private IPAddress _serverAddress = IPAddress.IPv6Loopback; // In the current directory private const string TestFileName = "NCLTest.Socket.SendPacketsAsync.testpayload"; private static int s_testFileSize = 1024; #region Additional test attributes public SendPacketsAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); byte[] buffer = new byte[s_testFileSize]; for (int i = 0; i < s_testFileSize; i++) { buffer[i] = (byte)(i % 255); } try { _log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize); using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew)) { fs.Write(buffer, 0, buffer.Length); } } catch (IOException) { // Test payload file already exists. _log.WriteLine("Payload file exists: {0}", TestFileName); } } #endregion Additional test attributes #region Basic Arguments [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Disposed_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); sock.Dispose(); Assert.Throws<ObjectDisposedException>(() => { sock.SendPacketsAsync(new SocketAsyncEventArgs()); }); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullArgs_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { sock.SendPacketsAsync(null); }); Assert.Equal("e", ex.ParamName); } } } [Fact] public void NotConnected_Throw() { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); // Needs to be connected before send ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { socket.SendPacketsAsync(new SocketAsyncEventArgs()); }); Assert.Equal("e.SendPacketsElements", ex.ParamName); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullList_Throws(SocketImplementationType type) { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0); }); Assert.Equal("e.SendPacketsElements", ex.ParamName); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullElement_Ignored(SocketImplementationType type) { SendPackets(type, (SendPacketsElement)null, 0); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void EmptyList_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SocketAsyncEventArgs_DefaultSendSize_0() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); Assert.Equal(0, args.SendPacketsSendSize); } #endregion Basic Arguments #region Buffers [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NormalBuffer_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10]), 10); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NormalBufferRange_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void EmptyBuffer_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[0]), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void BufferZeroCount_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(new byte[10], 4, 0), // Ignored new SendPacketsElement(new byte[10], 4, 4), new SendPacketsElement(new byte[10], 0, 4) }; SendPackets(type, elements, SocketError.Success, 8); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; // First do an empty send, ignored args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 3, 0) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(0, args.BytesTransferred); completed.Reset(); // Now do a real send args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 1, 4) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(4, args.BytesTransferred); } } } } #endregion Buffers #region TransmitFileOptions [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4); } #endregion #region Files [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { SendPackets(type, new SendPacketsElement(String.Empty), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(" \t "), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type) { Assert.Throws<DirectoryNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type) { Assert.Throws<FileNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("DoesntExit"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_File_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FilePart_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(TestFileName, 10, 20), new SendPacketsElement(TestFileName, 30, 10), new SendPacketsElement(TestFileName, 0, 10), }; SendPackets(type, elements, SocketError.Success, 40); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0); } #endregion Files #region Helpers private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = new[] { element }; args.SendPacketsFlags = flags; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } switch (flags) { case TransmitFileOptions.Disconnect: // Sending data again throws with socket shut down error. Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); }); break; case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect: // Able to send data again with reuse socket flag set. Assert.Equal(1, sock.Send(new byte[1] { 01 })); break; } } } } private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, SocketError.Success, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResut, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, expectedResut, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResut, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = elements; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(expectedResut, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } } } } private void OnCompleted(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; handle.Set(); } #endregion Helpers } }
// JsonReader.cs // DynamicRest provides REST service access using C# 4.0 dynamic programming. // The latest information and code for the project can be found at // https://github.com/NikhilK/dynamicrest // // This project is licensed under the BSD license. See the License.txt file for // more information. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace DynamicRest.Json { public sealed class JsonReader { internal static readonly long MinDateTimeTicks = (new DateTime(1970, 1, 1, 0, 0, 0)).Ticks; internal static readonly DateTime MinDate = new DateTime(100, 1, 1, 0, 0, 0); private TextReader _reader; public JsonReader(string jsonText) : this(new StringReader(jsonText)) { } public JsonReader(TextReader reader) { _reader = reader; } private char GetNextCharacter() { return (char)_reader.Read(); } private char GetNextSignificantCharacter() { char ch = (char)_reader.Read(); while ((ch != '\0') && Char.IsWhiteSpace(ch)) { ch = (char)_reader.Read(); } return ch; } private string GetCharacters(int count) { string s = String.Empty; for (int i = 0; i < count; i++) { char ch = (char)_reader.Read(); if (ch == '\0') { return null; } s += ch; } return s; } private char PeekNextSignificantCharacter() { char ch = (char)_reader.Peek(); while ((ch != '\0') && Char.IsWhiteSpace(ch)) { _reader.Read(); ch = (char)_reader.Peek(); } return ch; } private JsonArray ReadArray() { JsonArray array = new JsonArray(); ICollection<object> arrayItems = (ICollection<object>)array; // Consume the '[' _reader.Read(); while (true) { char ch = PeekNextSignificantCharacter(); if (ch == '\0') { throw new FormatException("Unterminated array literal."); } if (ch == ']') { _reader.Read(); return array; } if (arrayItems.Count != 0) { if (ch != ',') { throw new FormatException("Invalid array literal."); } else { _reader.Read(); } } object item = ReadValue(); arrayItems.Add(item); } } private bool ReadBoolean() { string s = ReadName(/* allowQuotes */ false); if (s != null) { if (s.Equals("true", StringComparison.Ordinal)) { return true; } else if (s.Equals("false", StringComparison.Ordinal)) { return false; } } throw new FormatException("Invalid boolean literal."); } private string ReadName(bool allowQuotes) { char ch = PeekNextSignificantCharacter(); if ((ch == '"') || (ch == '\'')) { if (allowQuotes) { return ReadString(); } } else { StringBuilder sb = new StringBuilder(); while (true) { ch = (char)_reader.Peek(); if ((ch == '_') || Char.IsLetterOrDigit(ch)) { _reader.Read(); sb.Append(ch); } else { return sb.ToString(); } } } return null; } private void ReadNull() { string s = ReadName(/* allowQuotes */ false); if ((s == null) || !s.Equals("null", StringComparison.Ordinal)) { throw new FormatException("Invalid null literal."); } } private object ReadNumber() { char ch = (char)_reader.Read(); StringBuilder sb = new StringBuilder(); bool hasDecimal = (ch == '.'); sb.Append(ch); while (true) { ch = PeekNextSignificantCharacter(); if (Char.IsDigit(ch) || (ch == '.')) { hasDecimal = hasDecimal || (ch == '.'); _reader.Read(); sb.Append(ch); } else { break; } } string s = sb.ToString(); if (hasDecimal) { float value; if (Single.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) { return value; } } else { int value; if (Int32.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) { return value; } else { long lvalue; if (Int64.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out lvalue)) { return lvalue; } } } throw new FormatException("Invalid numeric literal."); } private JsonObject ReadObject() { JsonObject record = new JsonObject(); IDictionary<string, object> recordItems = (IDictionary<string, object>)record; // Consume the '{' _reader.Read(); while (true) { char ch = PeekNextSignificantCharacter(); if (ch == '\0') { throw new FormatException("Unterminated object literal."); } if (ch == '}') { _reader.Read(); return record; } if (recordItems.Count != 0) { if (ch != ',') { throw new FormatException("Invalid object literal."); } else { _reader.Read(); } } string name = ReadName(/* allowQuotes */ true); ch = PeekNextSignificantCharacter(); if (ch != ':') { throw new FormatException("Unexpected name/value pair syntax in object literal."); } else { _reader.Read(); } object item = ReadValue(); recordItems[name] = item; } } private string ReadString() { bool dummy; return ReadString(out dummy); } private string ReadString(out bool hasLeadingSlash) { StringBuilder sb = new StringBuilder(); char endQuoteCharacter = (char)_reader.Read(); bool inEscape = false; bool firstCharacter = true; hasLeadingSlash = false; while (true) { char ch = GetNextCharacter(); if (ch == '\0') { throw new FormatException("Unterminated string literal."); } if (firstCharacter) { if (ch == '\\') { hasLeadingSlash = true; } firstCharacter = false; } if (inEscape) { if (ch == 'u') { string unicodeSequence = GetCharacters(4); if (unicodeSequence == null) { throw new FormatException("Unterminated string literal."); } ch = (char)Int32.Parse(unicodeSequence, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } else if (ch == 'n') { ch = '\n'; } else if (ch == 't') { ch = '\t'; } else if (ch == 'r') { ch = '\r'; } sb.Append(ch); inEscape = false; continue; } if (ch == '\\') { inEscape = true; continue; } if (ch == endQuoteCharacter) { return sb.ToString(); } sb.Append(ch); } } public object ReadValue() { object value = null; bool allowNull = false; char ch = PeekNextSignificantCharacter(); if (ch == '[') { value = ReadArray(); } else if (ch == '{') { value = ReadObject(); } else if ((ch == '\'') || (ch == '"')) { bool hasLeadingSlash; string s = ReadString(out hasLeadingSlash); if (hasLeadingSlash && s.StartsWith("@") && s.EndsWith("@")) { long ticks; if (Int64.TryParse(s.Substring(1, s.Length - 2), NumberStyles.Any, CultureInfo.InvariantCulture, out ticks)) { value = new DateTime(ticks * 10000 + JsonReader.MinDateTimeTicks, DateTimeKind.Utc); } } if (value == null) { value = s; } } else if (Char.IsDigit(ch) || (ch == '-') || (ch == '.')) { value = ReadNumber(); } else if ((ch == 't') || (ch == 'f')) { value = ReadBoolean(); } else if (ch == 'n') { ReadNull(); allowNull = true; } if ((value == null) && (allowNull == false)) { throw new FormatException("Invalid JSON text."); } return value; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 the OpenSimulator Project 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 DEVELOPERS ``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 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 log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System; using System.IO; using System.Reflection; using System.Xml; using System.Xml.Serialization; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// A new version of the old Channel class, simplified /// </summary> public class TerrainChannel : ITerrainChannel { protected TerrainData m_terrainData; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[TERRAIN CHANNEL]"; // Default, not-often-used builder public TerrainChannel() { m_terrainData = new HeightmapTerrainData((int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionHeight); FlatLand(); // PinHeadIsland(); } // Create terrain of given size public TerrainChannel(int pX, int pY) { m_terrainData = new HeightmapTerrainData(pX, pY, (int)Constants.RegionHeight); } // Create terrain of specified size and initialize with specified terrain. // TODO: join this with the terrain initializers. public TerrainChannel(String type, int pX, int pY, int pZ) { m_terrainData = new HeightmapTerrainData(pX, pY, pZ); if (type.Equals("flat")) FlatLand(); else PinHeadIsland(); } // Create channel passed a heightmap and expected dimensions of the region. // The heightmap might not fit the passed size so accomodations must be made. public TerrainChannel(double[,] pM, int pSizeX, int pSizeY, int pAltitude) { int hmSizeX = pM.GetLength(0); int hmSizeY = pM.GetLength(1); m_terrainData = new HeightmapTerrainData(pSizeX, pSizeY, pAltitude); for (int xx = 0; xx < pSizeX; xx++) for (int yy = 0; yy < pSizeY; yy++) if (xx > hmSizeX || yy > hmSizeY) m_terrainData[xx, yy] = TerrainData.DefaultTerrainHeight; else m_terrainData[xx, yy] = (float)pM[xx, yy]; } public TerrainChannel(TerrainData pTerrData) { m_terrainData = pTerrData; } public int Altitude { get { return m_terrainData.SizeZ; } } // Unfortunately, for historical reasons, in this module 'Width' is X and 'Height' is Y public int Height { get { return m_terrainData.SizeY; } } public int Width { get { return m_terrainData.SizeX; } } // X dimension // Y dimension // Y dimension #region ITerrainChannel Members // ITerrainChannel.this[x,y] public double this[int x, int y] { get { if (x < 0 || x >= Width || y < 0 || y >= Height) return 0; return (double)m_terrainData[x, y]; } set { if (Double.IsNaN(value) || Double.IsInfinity(value)) return; m_terrainData[x, y] = (float)value; } } // ITerrainChannel.GetDoubles() public double[,] GetDoubles() { double[,] heights = new double[Width, Height]; int idx = 0; // index into serialized array for (int ii = 0; ii < Width; ii++) { for (int jj = 0; jj < Height; jj++) { heights[ii, jj] = (double)m_terrainData[ii, jj]; idx++; } } return heights; } // ITerrainChannel.GetFloatsSerialized() // This one dimensional version is ordered so height = map[y*sizeX+x]; // DEPRECATED: don't use this function as it does not retain the dimensions of the terrain // and the caller will probably do the wrong thing if the terrain is not the legacy 256x256. public float[] GetFloatsSerialised() { return m_terrainData.GetFloatsSerialized(); } // ITerrainChannel.GetHieghtAtXYZ(x, y, z) public float GetHeightAtXYZ(float x, float y, float z) { if (x < 0 || x >= Width || y < 0 || y >= Height) return 0; return m_terrainData[(int)x, (int)y]; } // ITerrainChannel.GetTerrainData() public TerrainData GetTerrainData() { return m_terrainData; } // ITerrainChannel.LoadFromXmlString() public void LoadFromXmlString(string data) { StringReader sr = new StringReader(data); XmlTextReader reader = new XmlTextReader(sr); reader.Read(); ReadXml(reader); reader.Close(); sr.Close(); } // ITerrainChannel.MakeCopy() public ITerrainChannel MakeCopy() { return this.Copy(); } // ITerrainChannel.Merge public void Merge(ITerrainChannel newTerrain, Vector3 displacement, float radianRotation, Vector2 rotationDisplacement) { m_log.DebugFormat("{0} Merge. inSize=<{1},{2}>, disp={3}, rot={4}, rotDisp={5}, outSize=<{6},{7}>", LogHeader, newTerrain.Width, newTerrain.Height, displacement, radianRotation, rotationDisplacement, m_terrainData.SizeX, m_terrainData.SizeY); for (int xx = 0; xx < newTerrain.Width; xx++) { for (int yy = 0; yy < newTerrain.Height; yy++) { int dispX = (int)displacement.X; int dispY = (int)displacement.Y; float newHeight = (float)newTerrain[xx, yy] + displacement.Z; if (radianRotation == 0) { // If no rotation, place the new height in the specified location dispX += xx; dispY += yy; if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY) { m_terrainData[dispX, dispY] = newHeight; } } else { // If rotating, we have to smooth the result because the conversion // to ints will mean heightmap entries will not get changed // First compute the rotation location for the new height. dispX += (int)(rotationDisplacement.X + ((float)xx - rotationDisplacement.X) * Math.Cos(radianRotation) - ((float)yy - rotationDisplacement.Y) * Math.Sin(radianRotation)); dispY += (int)(rotationDisplacement.Y + ((float)xx - rotationDisplacement.X) * Math.Sin(radianRotation) + ((float)yy - rotationDisplacement.Y) * Math.Cos(radianRotation)); if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY) { float oldHeight = m_terrainData[dispX, dispY]; // Smooth the heights around this location if the old height is far from this one for (int sxx = dispX - 2; sxx < dispX + 2; sxx++) { for (int syy = dispY - 2; syy < dispY + 2; syy++) { if (sxx >= 0 && sxx < m_terrainData.SizeX && syy >= 0 && syy < m_terrainData.SizeY) { if (sxx == dispX && syy == dispY) { // Set height for the exact rotated point m_terrainData[dispX, dispY] = newHeight; } else { if (Math.Abs(m_terrainData[sxx, syy] - newHeight) > 1f) { // If the adjacent height is far off, force it to this height m_terrainData[sxx, syy] = newHeight; } } } } } } if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY) { m_terrainData[dispX, dispY] = (float)newTerrain[xx, yy]; } } } } } // ITerrainChannel.SaveToXmlString() public string SaveToXmlString() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Util.UTF8; using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw, settings)) { WriteXml(writer); } string output = sw.ToString(); return output; } } // ITerrainChannel.Tainted() public bool Tainted(int x, int y) { return m_terrainData.IsTaintedAt(x, y); } #endregion ITerrainChannel Members public TerrainChannel Copy() { TerrainChannel copy = new TerrainChannel(); copy.m_terrainData = m_terrainData.Clone(); return copy; } private void FlatLand() { m_terrainData.ClearLand(); } // Read legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array. private void FromXml(XmlReader xmlReader) { XmlSerializer serializer = new XmlSerializer(typeof(byte[])); byte[] dataArray = (byte[])serializer.Deserialize(xmlReader); int index = 0; m_terrainData = new HeightmapTerrainData(Height, Width, (int)Constants.RegionHeight); for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { float value; value = BitConverter.ToSingle(dataArray, index); index += 4; this[x, y] = (double)value; } } } // New terrain serialization format that includes the width and length. private void FromXml2(XmlReader xmlReader) { XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage)); TerrainChannelXMLPackage package = (TerrainChannelXMLPackage)serializer.Deserialize(xmlReader); m_terrainData = new HeightmapTerrainData(package.Map, package.CompressionFactor, package.SizeX, package.SizeY, package.SizeZ); } // Fill the heightmap with the center bump terrain private void PinHeadIsland() { for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { m_terrainData[x, y] = (float)TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10; float spherFacA = (float)(TerrainUtil.SphericalFactor(x, y, m_terrainData.SizeX / 2.0, m_terrainData.SizeY / 2.0, 50) * 0.01d); float spherFacB = (float)(TerrainUtil.SphericalFactor(x, y, m_terrainData.SizeX / 2.0, m_terrainData.SizeY / 2.0, 100) * 0.001d); if (m_terrainData[x, y] < spherFacA) m_terrainData[x, y] = spherFacA; if (m_terrainData[x, y] < spherFacB) m_terrainData[x, y] = spherFacB; } } } private void ReadXml(XmlReader reader) { // Check the first element. If legacy element, use the legacy reader. if (reader.IsStartElement("TerrainMap")) { reader.ReadStartElement("TerrainMap"); FromXml(reader); } else { reader.ReadStartElement("TerrainMap2"); FromXml2(reader); } } // Write legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array. private void ToXml(XmlWriter xmlWriter) { float[] mapData = GetFloatsSerialised(); byte[] buffer = new byte[mapData.Length * 4]; for (int i = 0; i < mapData.Length; i++) { byte[] value = BitConverter.GetBytes(mapData[i]); Array.Copy(value, 0, buffer, (i * 4), 4); } XmlSerializer serializer = new XmlSerializer(typeof(byte[])); serializer.Serialize(xmlWriter, buffer); } // New terrain serialization format that includes the width and length. private void ToXml2(XmlWriter xmlWriter) { TerrainChannelXMLPackage package = new TerrainChannelXMLPackage(Width, Height, Altitude, m_terrainData.CompressionFactor, m_terrainData.GetCompressedMap()); XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage)); serializer.Serialize(xmlWriter, package); } private void WriteXml(XmlWriter writer) { if (Width == Constants.RegionSize && Height == Constants.RegionSize) { // Downward compatibility for legacy region terrain maps. // If region is exactly legacy size, return the old format XML. writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty); ToXml(writer); writer.WriteEndElement(); } else { // New format XML that includes width and length. writer.WriteStartElement(String.Empty, "TerrainMap2", String.Empty); ToXml2(writer); writer.WriteEndElement(); } } private class TerrainChannelXMLPackage { public float CompressionFactor; public int[] Map; public int SizeX; public int SizeY; public int SizeZ; public int Version; public TerrainChannelXMLPackage(int pX, int pY, int pZ, float pCompressionFactor, int[] pMap) { Version = 1; SizeX = pX; SizeY = pY; SizeZ = pZ; CompressionFactor = pCompressionFactor; Map = pMap; } } } }
/* VRWebView * MiddleVR * (c) MiddleVR */ // Rendering plugin test // --------------------- // // VRWebView can be used without MiddleVR_UnityRendering.dll but it will // be much slower. // - Unity 4 can only use rendering plugins with a professionnal license. // However, the UNITY_PRO_LICENSE preprocessor condition only exists // starting from Unity 4.5 so for Unity 4.2 and 4.3 we always assume // it's a Professional edition. // - Starting with Unity 5 plugins are not limited anymore. #if (UNITY_4_5 || UNITY_4_6) && !UNITY_PRO_LICENSE #define VRWEBVIEW_UNITY_FREE #endif using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; [AddComponentMenu("MiddleVR/GUI/Web View")] public class VRWebView : MonoBehaviour { // Public attributes public int m_Width = 1024; public int m_Height = 768; public string m_URL = "http://www.middlevr.com/"; public float m_Zoom = 1.0f; // View management private vrWebView m_WebView = null; private vrImage m_Image = null; private Texture2D m_Texture = null; // Virtual mouse management private List<Camera> m_Cameras = null; private Vector2 m_VirtualMousePosition; private bool m_MouseButtonState = false; private bool m_IgnorePhysicalMouseInput = false; // Interaction private bool m_WandRayWasVisible = true; private static byte ALPHA_LIMIT = 50; #if VRWEBVIEW_UNITY_FREE // Unity Free texture management private Color32[] m_Pixels; private GCHandle m_PixelsHandle; #else IntPtr m_NativeTexturePtr = IntPtr.Zero; #endif public vrImage image { get { return m_Image; } } public vrWebView webView { get { return m_WebView; } } protected void SetVirtualMouseButtonPressed() { if (m_WebView != null) { m_WebView.SendMouseButtonPressed((int)m_VirtualMousePosition.x, (int)m_VirtualMousePosition.y); } } protected void SetVirtualMouseButtonReleased() { if (m_WebView != null) { m_WebView.SendMouseButtonReleased((int)m_VirtualMousePosition.x, (int)m_VirtualMousePosition.y); } } // pos: texture coordinate of raycast hit protected void SetVirtualMousePosition(Vector2 pos) { if (m_WebView != null) { m_VirtualMousePosition = new Vector2(pos.x * m_Texture.width, (float)m_WebView.GetHeight() - (pos.y * m_Texture.height)); m_WebView.SendMouseMove((int)m_VirtualMousePosition.x, (int)m_VirtualMousePosition.y); } } public void IgnorePhysicalMouseInput() { m_IgnorePhysicalMouseInput = true; } public bool IsPixelEmpty(Vector2 iTextureCoord) { byte alpha = image.GetAlphaAtPoint((int)(iTextureCoord.x * m_Width), (int)(iTextureCoord.y * m_Height)); return alpha < ALPHA_LIMIT; } protected void Start () { // Check if we are running MiddleVR if(MiddleVR.VRKernel == null) { Debug.Log("[X] VRManager is missing from the scene !"); enabled = false; return; } m_VirtualMousePosition = new Vector2(0, 0); if (Application.isEditor) { // Get the vrCameras corresponding Cameras m_Cameras = new List<Camera>(); uint camerasNb = MiddleVR.VRDisplayMgr.GetCamerasNb(); for (uint i = 0; i < camerasNb; ++i) { vrCamera vrcamera = MiddleVR.VRDisplayMgr.GetCameraByIndex(i); GameObject cameraObj = GameObject.Find(vrcamera.GetName()); Camera camera = cameraObj.GetComponent<Camera>(); if (camera != null) { m_Cameras.Add(camera); } } } m_Texture = new Texture2D(m_Width, m_Height, TextureFormat.ARGB32, false); m_Texture.wrapMode = TextureWrapMode.Clamp; // Create vrImage and Texture2D #if VRWEBVIEW_UNITY_FREE // Texture2D.SetPixels takes RGBA. m_Image = new vrImage("", (uint)m_Width, (uint)m_Height, VRImagePixelFormat.VRImagePixelFormat_RGBA); m_Pixels = m_Texture.GetPixels32 (0); m_PixelsHandle = GCHandle.Alloc(m_Pixels, GCHandleType.Pinned); #else // OpenGL and Direct3D 9: Memory order for texture upload is BGRA (little-endian representation of ARGB32) // Direct3D 11: Unity seems to ignore TextureFormat.ARGB32 and always creates an RGBA texture. // We let vrImage do the pixel format conversion because this operation is done in another thread. if (SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")) { m_Image = new vrImage("", (uint)m_Width, (uint)m_Height, VRImagePixelFormat.VRImagePixelFormat_RGBA); } else { m_Image = new vrImage("", (uint)m_Width, (uint)m_Height, VRImagePixelFormat.VRImagePixelFormat_BGRA); } #endif // Fill texture Color32[] colors = new Color32[(m_Width * m_Height)]; for (int i = 0; i < (m_Width * m_Height); i++) { colors[i].r = 0; colors[i].g = 0; colors[i].b = 0; colors[i].a = 0; } m_Texture.SetPixels32(colors); m_Texture.Apply(false, false); #if !VRWEBVIEW_UNITY_FREE m_NativeTexturePtr = m_Texture.GetNativeTexturePtr(); #endif // Attach texture if (gameObject != null && gameObject.GetComponent<GUITexture>() == null && gameObject.GetComponent<Renderer>() != null) { var renderer = gameObject.GetComponent<Renderer>(); // Assign the material/shader to the object attached renderer.material = Resources.Load("VRWebViewMaterial", typeof(Material)) as Material; renderer.material.mainTexture = this.m_Texture; } else if (gameObject != null && gameObject.GetComponent<GUITexture>() != null ) { gameObject.GetComponent<GUITexture>().texture = this.m_Texture; } else { MiddleVR.VRLog(2, "VRWebView must be attached to a GameObject with a renderer or a GUITexture !"); enabled = false; return; } // Handle Cluster if ( MiddleVR.VRClusterMgr.IsServer() && ! MiddleVR.VRKernel.GetEditorMode() ) { MiddleVR.VRClusterMgr.AddSynchronizedObject( m_Image ); } if( ! MiddleVR.VRClusterMgr.IsClient() ) { m_WebView = new vrWebView("", GetAbsoluteURL( m_URL ) , (uint)m_Width, (uint)m_Height, m_Image ); m_WebView.SetZoom( m_Zoom ); } } #if !VRWEBVIEW_UNITY_FREE // Hex code for "MVR1" const int MVR_RENDEREVENT_COPYBUFFERSTOTEXTURES = 0x4D565231; [DllImport("MiddleVR_UnityRendering")] private static extern void MiddleVR_AsyncCopyBufferToTexture(IntPtr iBuffer, IntPtr iNativeTexturePtr, uint iWidth, uint iHeight); [DllImport("MiddleVR_UnityRendering")] private static extern void MiddleVR_CancelCopyBufferToTexture(IntPtr iNativeTexturePtr); #endif protected void Update () { // Handle mouse input if (!MiddleVR.VRClusterMgr.IsClient()) { if (!m_IgnorePhysicalMouseInput) { Vector2 mouseHit = new Vector2(0, 0); bool hasMouseHit = false; if (gameObject.GetComponent<GUITexture>() != null) { // GUITexture mouse input Rect r = gameObject.GetComponent<GUITexture>().GetScreenRect(); if( Input.mousePosition.x >= r.x && Input.mousePosition.x < (r.x + r.width) && Input.mousePosition.y >= r.y && Input.mousePosition.y < (r.y + r.height) ) { float x = (Input.mousePosition.x - r.x) / r.width; float y = (Input.mousePosition.y - r.y) / r.height; mouseHit = new Vector2(x, y); hasMouseHit = true; } } else if( gameObject.GetComponent<Renderer>() != null && Application.isEditor ) { // 3D object mouse input mouseHit = GetClosestMouseHit(); if (mouseHit.x != -1 && mouseHit.y != -1) { hasMouseHit = true; } } if (hasMouseHit) { bool newMouseButtonState = Input.GetMouseButton(0); if (m_MouseButtonState == false && newMouseButtonState == true) { SetVirtualMousePosition(mouseHit); SetVirtualMouseButtonPressed(); } else if (m_MouseButtonState == true && newMouseButtonState == false) { SetVirtualMouseButtonReleased(); SetVirtualMousePosition(mouseHit); } else { SetVirtualMousePosition(mouseHit); } m_MouseButtonState = newMouseButtonState; } } m_IgnorePhysicalMouseInput = false; } // Handle texture update if ( m_Image.HasChanged() ) { using (vrImageFormat format = m_Image.GetImageFormat()) { if ((uint)m_Texture.width != format.GetWidth() || (uint)m_Texture.height != format.GetHeight()) { #if VRWEBVIEW_UNITY_FREE m_PixelsHandle.Free(); #endif m_Texture.Resize((int)format.GetWidth(), (int)format.GetHeight()); m_Texture.Apply(false, false); #if VRWEBVIEW_UNITY_FREE m_PixelsHandle.Free(); m_Pixels = m_Texture.GetPixels32 (0); m_PixelsHandle = GCHandle.Alloc(m_Pixels, GCHandleType.Pinned); #else MiddleVR_CancelCopyBufferToTexture(m_NativeTexturePtr); m_NativeTexturePtr = m_Texture.GetNativeTexturePtr(); #endif } if (format.GetWidth() > 0 && format.GetHeight() > 0) { #if VRWEBVIEW_UNITY_FREE m_Image.GetReadBufferData( m_PixelsHandle.AddrOfPinnedObject() ); m_Texture.SetPixels32(m_Pixels, 0); m_Texture.Apply(false, false); #else MiddleVR_AsyncCopyBufferToTexture(m_Image.GetReadBuffer(), m_NativeTexturePtr, format.GetWidth(), format.GetHeight()); GL.IssuePluginEvent(MVR_RENDEREVENT_COPYBUFFERSTOTEXTURES); #endif } } } } protected void OnDestroy () { #if VRWEBVIEW_UNITY_FREE m_PixelsHandle.Free(); #else MiddleVR_CancelCopyBufferToTexture( m_NativeTexturePtr ); #endif } private Vector2 GetClosestMouseHit() { foreach( Camera camera in m_Cameras ) { RaycastHit[] hits = Physics.RaycastAll( camera.ScreenPointToRay(Input.mousePosition)); foreach (RaycastHit hit in hits) { if (hit.collider.gameObject == gameObject) { return hit.textureCoord; } } } return new Vector2(-1,-1); } private string GetAbsoluteURL( string iUrl ) { string url = iUrl; // If url does not start with http/https we assume it's a file if( !url.StartsWith( "http://" ) && !url.StartsWith( "https://" ) ) { if( url.StartsWith( "file://" ) ) { url = url.Substring(7, url.Length-7 ); if( Application.platform == RuntimePlatform.WindowsPlayer && url.StartsWith( "/" ) ) { url = url.Substring(1, url.Length-1); } } if( ! System.IO.Path.IsPathRooted( url ) ) { url = Application.dataPath + System.IO.Path.DirectorySeparatorChar + url; } if( Application.platform == RuntimePlatform.WindowsPlayer ) { url = "/" + url; } url = "file://" + url; } return url; } protected void OnMVRWandEnter(VRSelection iSelection) { // Force show ray and save state m_WandRayWasVisible = iSelection.SourceWand.IsRayVisible(); iSelection.SourceWand.ShowRay(true); } protected void OnMVRWandHover(VRSelection iSelection) { SetVirtualMousePosition(iSelection.TextureCoordinate); } protected void OnMVRWandButtonPressed(VRSelection iSelection) { SetVirtualMousePosition(iSelection.TextureCoordinate); SetVirtualMouseButtonPressed(); } protected void OnMVRWandButtonReleased(VRSelection iSelection) { SetVirtualMouseButtonReleased(); SetVirtualMousePosition(iSelection.TextureCoordinate); } protected void OnMVRWandExit(VRSelection iSelection) { // Unforce show ray iSelection.SourceWand.ShowRay(m_WandRayWasVisible); } protected void OnMVRTouchEnd(VRTouch iTouch) { SetVirtualMouseButtonPressed(); SetVirtualMouseButtonReleased(); } protected void OnMVRTouchMoved(VRTouch iTouch) { Vector3 fwd = -transform.TransformDirection(Vector3.up); Ray ray = new Ray(iTouch.TouchObject.transform.position, fwd); var collider = GetComponent<Collider>(); RaycastHit hit; if (collider != null && collider.Raycast(ray, out hit, 1.0F)) { if (hit.collider.gameObject == gameObject) { Vector2 mouseCursor = hit.textureCoord; SetVirtualMousePosition(mouseCursor); } } } protected void OnMVRTouchBegin(VRTouch iTouch) { Vector3 fwd = -transform.TransformDirection(Vector3.up); Ray ray = new Ray(iTouch.TouchObject.transform.position, fwd); var collider = GetComponent<Collider>(); RaycastHit hit; if (collider != null && collider.Raycast(ray, out hit, 1.0F)) { if (hit.collider.gameObject == gameObject) { Vector2 mouseCursor = hit.textureCoord; SetVirtualMousePosition(mouseCursor); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; namespace CalcIP { public static class Program { public static readonly Regex IPv4WithSubnetRegex = new Regex("^(?<addr>[0-9]+(?:[.][0-9]+){3})/(?<wildcard>-)?(?<mask>[0-9]+(?:[.][0-9]+){3})$", RegexOptions.Compiled); public static readonly Regex IPv4WithCidrRegex = new Regex("^(?<addr>[0-9]+(?:[.][0-9]+){3})/(?<cidr>[0-9]+)$", RegexOptions.Compiled); public static readonly Regex IPv6WithSubnetRegex = new Regex("^(?<addr>[0-9a-f:]+)/(?<wildcard>-)?(?<mask>[0-9a-f:]+)$", RegexOptions.Compiled); public static readonly Regex IPv6WithCidrRegex = new Regex("^(?<addr>[0-9a-f:]+)/(?<cidr>[0-9]+)$", RegexOptions.Compiled); public static int Main(string[] args) { try { return RealMain(args); } finally { Console.ResetColor(); } } public static int RealMain(string[] args) { if (args.Length < 1) { UsageAndExit(); } if (args[0] == "--stdin") { return RunFromStdin(); } return RunSingleArgs(args); } public static int RunFromStdin() { int retCode = 0; string line; while ((line = Console.ReadLine()) != null) { // split on whitespace, removing empty entries string[] args = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); if (args.Length == 0) { Console.WriteLine(); continue; } int lineRetCode = RunSingleArgs(args); if (retCode < lineRetCode) { retCode = lineRetCode; } } return retCode; } public static int RunSingleArgs(string[] args) { if (args[0] == "-m" || args[0] == "--minimize") { return Minimize.PerformMinimize(args); } else if (args[0] == "-d" || args[0] == "--derange") { return Derange.PerformDerange(args); } else if (args[0] == "-s" || args[0] == "--split") { return Split.PerformSplit(args); } else if (args[0] == "-r" || args[0] == "--resize") { return Resize.PerformResize(args); } else if (args[0] == "-e" || args[0] == "--enumerate") { return Enumerate.PerformEnumerate(args); } else { return ShowNet.PerformShowNet(args); } } public static void UsageAndExit(int exitCode = 1) { Console.Error.WriteLine( "Usage: CalcIP IPADDRESS/SUBNET...\r\n" + " CalcIP -m|--minimize IPADDRESS/SUBNET...\r\n" + " CalcIP -d|--derange IPADDRESS IPADDRESS\r\n" + " CalcIP -s|--split IPADDRESS/CIDRPREFIX HOSTCOUNT...\r\n" + " CalcIP -r|--resize IPADDRESS/SUBNET SUBNET\r\n" + " CalcIP -e|--enumerate IPADDRESS/SUBNET\r\n" + " CalcIP --stdin\r\n" + "\r\n" + "SUBNET is one of: SUBNETMASK\r\n" + " CIDRPREFIX\r\n" + " -WILDCARD\r\n" + "\r\n" + "IPv4 and IPv6 are supported, but cannot be mixed within an invocation.\r\n" ); Environment.Exit(exitCode); } public static Tuple<IPv4Address, IPv4Network> ParseIPv4SubnetSpec(Match match) { string addressString = match.Groups["addr"].Value; string maskString = match.Groups["mask"].Value; bool isWildcard = match.Groups["wildcard"].Success; var address = IPv4Address.MaybeParse(addressString); if (!address.HasValue) { Console.Error.WriteLine("{0}: Invalid IPv4 address {1}", match.Value, addressString); return null; } var mask = IPv4Address.MaybeParse(maskString); if (!mask.HasValue) { Console.Error.WriteLine("{0}: Invalid IPv4 subnet mask {1}", match.Value, maskString); return null; } if (isWildcard) { mask = ~mask.Value; } return Tuple.Create(address.Value, new IPv4Network(address.Value, mask.Value)); } public static Tuple<IPv4Address, IPv4Network> ParseIPv4CidrSpec(Match match) { string addressString = match.Groups["addr"].Value; string cidrString = match.Groups["cidr"].Value; var address = IPv4Address.MaybeParse(addressString); if (!address.HasValue) { Console.Error.WriteLine("{0}: Invalid IPv4 address {1}", match.Value, addressString); return null; } int cidr; if (!int.TryParse(cidrString, NumberStyles.None, CultureInfo.InvariantCulture, out cidr)) { Console.Error.WriteLine("{0}: Invalid CIDR prefix {1}", match.Value, cidrString); return null; } if (cidr > 32) { Console.Error.WriteLine("{0}: CIDR prefix {1} is too large (32 is the maximum for IPv4)", match.Value, cidr); return null; } return Tuple.Create(address.Value, new IPv4Network(address.Value, cidr)); } public static Tuple<IPv6Address, IPv6Network> ParseIPv6CidrSpec(Match match) { string addressString = match.Groups["addr"].Value; string cidrString = match.Groups["cidr"].Value; var address = IPv6Address.MaybeParse(addressString); if (!address.HasValue) { Console.Error.WriteLine("{0}: Invalid IPv6 address {1}", match.Value, addressString); return null; } int cidr; if (!int.TryParse(cidrString, NumberStyles.None, CultureInfo.InvariantCulture, out cidr)) { Console.Error.WriteLine("{0}: Invalid CIDR prefix {1}", match.Value, cidrString); return null; } if (cidr > 128) { Console.Error.WriteLine("{0}: CIDR prefix {1} is too large (128 is the maximum for IPv6)", match.Value, cidr); return null; } return Tuple.Create(address.Value, new IPv6Network(address.Value, cidr)); } public static Tuple<IPv6Address, IPv6Network> ParseIPv6SubnetSpec(Match match) { string addressString = match.Groups["addr"].Value; string maskString = match.Groups["mask"].Value; bool isWildcard = match.Groups["wildcard"].Success; var address = IPv6Address.MaybeParse(addressString); if (!address.HasValue) { Console.Error.WriteLine("{0}: Invalid IPv6 address {1}", match.Value, addressString); return null; } var mask = IPv6Address.MaybeParse(maskString); if (!mask.HasValue) { Console.Error.WriteLine("{0}: Invalid IPv6 subnet mask {1}", match.Value, maskString); return null; } if (isWildcard) { mask = ~mask.Value; } return Tuple.Create(address.Value, new IPv6Network(address.Value, mask.Value)); } public static void PerformOnSubnets(IEnumerable<string> subnetSpecs, Action<IPv4Address, IPv4Network> ipv4Action, Action<IPv6Address, IPv6Network> ipv6Action) { foreach (string spec in subnetSpecs) { // attempt to identify the input format // scope { Match ipv4CidrMatch = Program.IPv4WithCidrRegex.Match(spec); if (ipv4CidrMatch.Success) { Tuple<IPv4Address, IPv4Network> ipv4Tuple = ParseIPv4CidrSpec(ipv4CidrMatch); if (ipv4Tuple != null) { ipv4Action.Invoke(ipv4Tuple.Item1, ipv4Tuple.Item2); } continue; } } // scope { Match ipv4SubnetMatch = Program.IPv4WithSubnetRegex.Match(spec); if (ipv4SubnetMatch.Success) { Tuple<IPv4Address, IPv4Network> ipv4Tuple = ParseIPv4SubnetSpec(ipv4SubnetMatch); if (ipv4Tuple != null) { ipv4Action.Invoke(ipv4Tuple.Item1, ipv4Tuple.Item2); } continue; } } // scope { Match ipv6CidrMatch = Program.IPv6WithCidrRegex.Match(spec); if (ipv6CidrMatch.Success) { Tuple<IPv6Address, IPv6Network> ipv6Tuple = ParseIPv6CidrSpec(ipv6CidrMatch); if (ipv6Tuple != null) { ipv6Action.Invoke(ipv6Tuple.Item1, ipv6Tuple.Item2); } continue; } } // scope { Match ipv6SubnetMatch = Program.IPv6WithSubnetRegex.Match(spec); if (ipv6SubnetMatch.Success) { Tuple<IPv6Address, IPv6Network> ipv6Tuple = ParseIPv6SubnetSpec(ipv6SubnetMatch); if (ipv6Tuple != null) { ipv6Action.Invoke(ipv6Tuple.Item1, ipv6Tuple.Item2); } continue; } } Console.Error.WriteLine("Failed to identify {0} input type.", spec); } } } }
using UnityEngine; using System.Collections.Generic; using System.Linq; using System.Collections; /// <summary> /// Main component of CamOn. /// A camera operator can be asigned to a camera using the "On" method or by adding the component to a camera /// A shot can be selected using the SelectShot method or manually in the unity editor /// </summary> [AddComponentMenu("CamOn/Camera Operator")] public class CameraOperator : MonoBehaviour { /// <summary> /// Types of transition: /// </summary> public enum Transition { /// <summary> /// The camre switches directly from one shot to the next one /// </summary> Cut, /// <summary> /// The camera smoothy animates from the current shot to the new one /// </summary> Smooth }; /// <summary> /// The movement responsiveness. /// </summary> public float MovementResponsiveness = 0.95f; /// <summary> /// The rotation responsiveness. /// </summary> public float RotationResponsiveness = 0.95f; [SerializeField] Shot shot; [SerializeField] Actor[] actors; readonly Solver solver = new ArtificialPotentialField(); Transform bestCamera; Vector3 velocity = Vector3.zero; bool started = false; Transition transition = Transition.Cut; /// <summary> /// Return the camera used internally for the solver computations /// </summary> /// <value>The evaluation camera.</value> public Transform EvaluationCamera { get { return bestCamera; } } /// <summary> /// Returns the current list of actors evaluated /// </summary> /// <value>The subjects.</value> public Actor[] Actors { get { return actors; } } /// <summary> /// Gets or sets the shot that will drive the camera. /// </summary> /// <value>The shot.</value> public Shot Shot { set { if (value != shot) { shot = value; shot.FixPropertiesType(); actors = new Actor[shot.NumberOfActors]; } } get { return shot; } } /// <summary> /// Gets a value indicating whether this <see cref="CameraOperator"/> ready for evaluation. /// </summary> /// <value><c>true</c> if ready for evaluation; otherwise, <c>false</c>.</value> public bool ReadyForEvaluation { get { if (Shot == null || Shot.Properties == null) return false; if (actors == null) return false; foreach (Actor s in actors) if (s == null) return false; return true; } } void Start () { if (!started){ bestCamera = (Transform)GameObject.Instantiate(transform,transform.position,transform.rotation); GameObject.DestroyImmediate (bestCamera.GetComponent<CameraOperator> ()); GameObject.DestroyImmediate (bestCamera.GetComponent<AudioListener> ()); bestCamera.gameObject.SetActive (false); started = true; } if (shot != null && actors != null){ shot.FixPropertiesType(); solver.Stop (); for (int i=0;i<actors.Length;i++) if (actors[i] != null) actors[i].SetAreaOfInterest(shot.VolumesOfInterestSize[i],shot.VolumesOfInterestPosition[i]); solver.Start (bestCamera, actors, shot); } } float timeLimit = 0.1f; void Update () { if (Time.deltaTime < 1.0f/60) timeLimit *= 1.1f; else timeLimit *= 0.9f; timeLimit = Mathf.Max(timeLimit, 0.016f); if (ReadyForEvaluation) solver.Update(bestCamera, actors, shot,timeLimit); Solver.setPosition(transform.position+solver.SubjectsVelocity*Time.deltaTime,transform,shot); float dampening = Mathf.Pow(solver.Satisfaction,4); if (transition == Transition.Cut) { transform.position = bestCamera.position; transform.rotation = bestCamera.rotation; transition = Transition.Smooth; } else { transform.position = Vector3.SmoothDamp(transform.position, bestCamera.position, ref velocity, 1.05f-MovementResponsiveness*dampening); transform.rotation = Quaternion.Slerp(transform.rotation, bestCamera.rotation, Time.deltaTime * (0.1f + RotationResponsiveness*dampening*0.9f)*2); } } void OnDrawGizmos () { solver.DrawGizmos (); } /// <summary> /// Selects a new shot and initiates a transition. /// </summary> /// <param name="shot">Shot.</param> /// <param name="transition">The type fo transition.</param> /// <param name="actors">An array of actors included in the shot.</param> public void SelectShot(Shot shot, Transition transition, Actor [] actors){ this.Shot = shot; for (int i=0;i<Mathf.Min (actors.Length,this.actors.Length);i++) this.actors[i] = actors[i]; this.transition = transition; Start(); } /// <summary> /// Selects a new shot with one actor and initiates a transition. /// </summary> /// <param name="shot">Shot.</param> /// <param name="transition">The type fo transition.</param> /// <param name="actor">The actor included in the shot.</param> public void SelectShot(Shot shot, Transition transition, Actor actor){ this.Shot = shot; this.actors[0] = actor; this.transition = transition; Start(); } /// <summary> /// Returns the camera operator assigned to a specific camera. /// If no operator exists, a new one is assigned. /// </summary> /// <param name="camera">Camera.</param> public static CameraOperator On(Camera camera){ CameraOperator co = camera.GetComponent<CameraOperator> (); if (co == null) co = camera.gameObject.AddComponent<CameraOperator> (); return co; } /// <summary> /// Returns the camera operator assigned to the main camera. /// If no operator exists, a new one is assigned. /// </summary> public static CameraOperator OnMainCamera { get { return On (Camera.main); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.AppEngine.V1 { /// <summary>Settings for <see cref="DomainMappingsClient"/> instances.</summary> public sealed partial class DomainMappingsSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="DomainMappingsSettings"/>.</summary> /// <returns>A new instance of the default <see cref="DomainMappingsSettings"/>.</returns> public static DomainMappingsSettings GetDefault() => new DomainMappingsSettings(); /// <summary>Constructs a new <see cref="DomainMappingsSettings"/> object with default settings.</summary> public DomainMappingsSettings() { } private DomainMappingsSettings(DomainMappingsSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListDomainMappingsSettings = existing.ListDomainMappingsSettings; GetDomainMappingSettings = existing.GetDomainMappingSettings; CreateDomainMappingSettings = existing.CreateDomainMappingSettings; CreateDomainMappingOperationsSettings = existing.CreateDomainMappingOperationsSettings.Clone(); UpdateDomainMappingSettings = existing.UpdateDomainMappingSettings; UpdateDomainMappingOperationsSettings = existing.UpdateDomainMappingOperationsSettings.Clone(); DeleteDomainMappingSettings = existing.DeleteDomainMappingSettings; DeleteDomainMappingOperationsSettings = existing.DeleteDomainMappingOperationsSettings.Clone(); OnCopy(existing); } partial void OnCopy(DomainMappingsSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>DomainMappingsClient.ListDomainMappings</c> and <c>DomainMappingsClient.ListDomainMappingsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListDomainMappingsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>DomainMappingsClient.GetDomainMapping</c> and <c>DomainMappingsClient.GetDomainMappingAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetDomainMappingSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>DomainMappingsClient.CreateDomainMapping</c> and <c>DomainMappingsClient.CreateDomainMappingAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateDomainMappingSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// Long Running Operation settings for calls to <c>DomainMappingsClient.CreateDomainMapping</c> and /// <c>DomainMappingsClient.CreateDomainMappingAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings CreateDomainMappingOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>DomainMappingsClient.UpdateDomainMapping</c> and <c>DomainMappingsClient.UpdateDomainMappingAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings UpdateDomainMappingSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// Long Running Operation settings for calls to <c>DomainMappingsClient.UpdateDomainMapping</c> and /// <c>DomainMappingsClient.UpdateDomainMappingAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings UpdateDomainMappingOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>DomainMappingsClient.DeleteDomainMapping</c> and <c>DomainMappingsClient.DeleteDomainMappingAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteDomainMappingSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// Long Running Operation settings for calls to <c>DomainMappingsClient.DeleteDomainMapping</c> and /// <c>DomainMappingsClient.DeleteDomainMappingAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings DeleteDomainMappingOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="DomainMappingsSettings"/> object.</returns> public DomainMappingsSettings Clone() => new DomainMappingsSettings(this); } /// <summary> /// Builder class for <see cref="DomainMappingsClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class DomainMappingsClientBuilder : gaxgrpc::ClientBuilderBase<DomainMappingsClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public DomainMappingsSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public DomainMappingsClientBuilder() { UseJwtAccessWithScopes = DomainMappingsClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref DomainMappingsClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<DomainMappingsClient> task); /// <summary>Builds the resulting client.</summary> public override DomainMappingsClient Build() { DomainMappingsClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<DomainMappingsClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<DomainMappingsClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private DomainMappingsClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return DomainMappingsClient.Create(callInvoker, Settings); } private async stt::Task<DomainMappingsClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return DomainMappingsClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => DomainMappingsClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => DomainMappingsClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => DomainMappingsClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>DomainMappings client wrapper, for convenient use.</summary> /// <remarks> /// Manages domains serving an application. /// </remarks> public abstract partial class DomainMappingsClient { /// <summary> /// The default endpoint for the DomainMappings service, which is a host of "appengine.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "appengine.googleapis.com:443"; /// <summary>The default DomainMappings scopes.</summary> /// <remarks> /// The default DomainMappings scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/appengine.admin</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform.read-only</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/appengine.admin", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="DomainMappingsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="DomainMappingsClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="DomainMappingsClient"/>.</returns> public static stt::Task<DomainMappingsClient> CreateAsync(st::CancellationToken cancellationToken = default) => new DomainMappingsClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="DomainMappingsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="DomainMappingsClientBuilder"/>. /// </summary> /// <returns>The created <see cref="DomainMappingsClient"/>.</returns> public static DomainMappingsClient Create() => new DomainMappingsClientBuilder().Build(); /// <summary> /// Creates a <see cref="DomainMappingsClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="DomainMappingsSettings"/>.</param> /// <returns>The created <see cref="DomainMappingsClient"/>.</returns> internal static DomainMappingsClient Create(grpccore::CallInvoker callInvoker, DomainMappingsSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } DomainMappings.DomainMappingsClient grpcClient = new DomainMappings.DomainMappingsClient(callInvoker); return new DomainMappingsClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC DomainMappings client</summary> public virtual DomainMappings.DomainMappingsClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Lists the domain mappings on an application. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="DomainMapping"/> resources.</returns> public virtual gax::PagedEnumerable<ListDomainMappingsResponse, DomainMapping> ListDomainMappings(ListDomainMappingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the domain mappings on an application. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="DomainMapping"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListDomainMappingsResponse, DomainMapping> ListDomainMappingsAsync(ListDomainMappingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the specified domain mapping. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual DomainMapping GetDomainMapping(GetDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the specified domain mapping. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DomainMapping> GetDomainMappingAsync(GetDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the specified domain mapping. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DomainMapping> GetDomainMappingAsync(GetDomainMappingRequest request, st::CancellationToken cancellationToken) => GetDomainMappingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Maps a domain to an application. A user must be authorized to administer a /// domain in order to map it to an application. For a list of available /// authorized domains, see [`AuthorizedDomains.ListAuthorizedDomains`](). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<DomainMapping, OperationMetadataV1> CreateDomainMapping(CreateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Maps a domain to an application. A user must be authorized to administer a /// domain in order to map it to an application. For a list of available /// authorized domains, see [`AuthorizedDomains.ListAuthorizedDomains`](). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> CreateDomainMappingAsync(CreateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Maps a domain to an application. A user must be authorized to administer a /// domain in order to map it to an application. For a list of available /// authorized domains, see [`AuthorizedDomains.ListAuthorizedDomains`](). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> CreateDomainMappingAsync(CreateDomainMappingRequest request, st::CancellationToken cancellationToken) => CreateDomainMappingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>CreateDomainMapping</c>.</summary> public virtual lro::OperationsClient CreateDomainMappingOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>CreateDomainMapping</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<DomainMapping, OperationMetadataV1> PollOnceCreateDomainMapping(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<DomainMapping, OperationMetadataV1>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateDomainMappingOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>CreateDomainMapping</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> PollOnceCreateDomainMappingAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<DomainMapping, OperationMetadataV1>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateDomainMappingOperationsClient, callSettings); /// <summary> /// Updates the specified domain mapping. To map an SSL certificate to a /// domain mapping, update `certificate_id` to point to an `AuthorizedCertificate` /// resource. A user must be authorized to administer the associated domain /// in order to update a `DomainMapping` resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<DomainMapping, OperationMetadataV1> UpdateDomainMapping(UpdateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates the specified domain mapping. To map an SSL certificate to a /// domain mapping, update `certificate_id` to point to an `AuthorizedCertificate` /// resource. A user must be authorized to administer the associated domain /// in order to update a `DomainMapping` resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> UpdateDomainMappingAsync(UpdateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates the specified domain mapping. To map an SSL certificate to a /// domain mapping, update `certificate_id` to point to an `AuthorizedCertificate` /// resource. A user must be authorized to administer the associated domain /// in order to update a `DomainMapping` resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> UpdateDomainMappingAsync(UpdateDomainMappingRequest request, st::CancellationToken cancellationToken) => UpdateDomainMappingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>UpdateDomainMapping</c>.</summary> public virtual lro::OperationsClient UpdateDomainMappingOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>UpdateDomainMapping</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<DomainMapping, OperationMetadataV1> PollOnceUpdateDomainMapping(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<DomainMapping, OperationMetadataV1>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateDomainMappingOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>UpdateDomainMapping</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> PollOnceUpdateDomainMappingAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<DomainMapping, OperationMetadataV1>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateDomainMappingOperationsClient, callSettings); /// <summary> /// Deletes the specified domain mapping. A user must be authorized to /// administer the associated domain in order to delete a `DomainMapping` /// resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<wkt::Empty, OperationMetadataV1> DeleteDomainMapping(DeleteDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified domain mapping. A user must be authorized to /// administer the associated domain in order to delete a `DomainMapping` /// resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadataV1>> DeleteDomainMappingAsync(DeleteDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified domain mapping. A user must be authorized to /// administer the associated domain in order to delete a `DomainMapping` /// resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadataV1>> DeleteDomainMappingAsync(DeleteDomainMappingRequest request, st::CancellationToken cancellationToken) => DeleteDomainMappingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>DeleteDomainMapping</c>.</summary> public virtual lro::OperationsClient DeleteDomainMappingOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>DeleteDomainMapping</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<wkt::Empty, OperationMetadataV1> PollOnceDeleteDomainMapping(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<wkt::Empty, OperationMetadataV1>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteDomainMappingOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>DeleteDomainMapping</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadataV1>> PollOnceDeleteDomainMappingAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<wkt::Empty, OperationMetadataV1>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteDomainMappingOperationsClient, callSettings); } /// <summary>DomainMappings client wrapper implementation, for convenient use.</summary> /// <remarks> /// Manages domains serving an application. /// </remarks> public sealed partial class DomainMappingsClientImpl : DomainMappingsClient { private readonly gaxgrpc::ApiCall<ListDomainMappingsRequest, ListDomainMappingsResponse> _callListDomainMappings; private readonly gaxgrpc::ApiCall<GetDomainMappingRequest, DomainMapping> _callGetDomainMapping; private readonly gaxgrpc::ApiCall<CreateDomainMappingRequest, lro::Operation> _callCreateDomainMapping; private readonly gaxgrpc::ApiCall<UpdateDomainMappingRequest, lro::Operation> _callUpdateDomainMapping; private readonly gaxgrpc::ApiCall<DeleteDomainMappingRequest, lro::Operation> _callDeleteDomainMapping; /// <summary> /// Constructs a client wrapper for the DomainMappings service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="DomainMappingsSettings"/> used within this client.</param> public DomainMappingsClientImpl(DomainMappings.DomainMappingsClient grpcClient, DomainMappingsSettings settings) { GrpcClient = grpcClient; DomainMappingsSettings effectiveSettings = settings ?? DomainMappingsSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); CreateDomainMappingOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.CreateDomainMappingOperationsSettings); UpdateDomainMappingOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.UpdateDomainMappingOperationsSettings); DeleteDomainMappingOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.DeleteDomainMappingOperationsSettings); _callListDomainMappings = clientHelper.BuildApiCall<ListDomainMappingsRequest, ListDomainMappingsResponse>(grpcClient.ListDomainMappingsAsync, grpcClient.ListDomainMappings, effectiveSettings.ListDomainMappingsSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListDomainMappings); Modify_ListDomainMappingsApiCall(ref _callListDomainMappings); _callGetDomainMapping = clientHelper.BuildApiCall<GetDomainMappingRequest, DomainMapping>(grpcClient.GetDomainMappingAsync, grpcClient.GetDomainMapping, effectiveSettings.GetDomainMappingSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetDomainMapping); Modify_GetDomainMappingApiCall(ref _callGetDomainMapping); _callCreateDomainMapping = clientHelper.BuildApiCall<CreateDomainMappingRequest, lro::Operation>(grpcClient.CreateDomainMappingAsync, grpcClient.CreateDomainMapping, effectiveSettings.CreateDomainMappingSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreateDomainMapping); Modify_CreateDomainMappingApiCall(ref _callCreateDomainMapping); _callUpdateDomainMapping = clientHelper.BuildApiCall<UpdateDomainMappingRequest, lro::Operation>(grpcClient.UpdateDomainMappingAsync, grpcClient.UpdateDomainMapping, effectiveSettings.UpdateDomainMappingSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callUpdateDomainMapping); Modify_UpdateDomainMappingApiCall(ref _callUpdateDomainMapping); _callDeleteDomainMapping = clientHelper.BuildApiCall<DeleteDomainMappingRequest, lro::Operation>(grpcClient.DeleteDomainMappingAsync, grpcClient.DeleteDomainMapping, effectiveSettings.DeleteDomainMappingSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteDomainMapping); Modify_DeleteDomainMappingApiCall(ref _callDeleteDomainMapping); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ListDomainMappingsApiCall(ref gaxgrpc::ApiCall<ListDomainMappingsRequest, ListDomainMappingsResponse> call); partial void Modify_GetDomainMappingApiCall(ref gaxgrpc::ApiCall<GetDomainMappingRequest, DomainMapping> call); partial void Modify_CreateDomainMappingApiCall(ref gaxgrpc::ApiCall<CreateDomainMappingRequest, lro::Operation> call); partial void Modify_UpdateDomainMappingApiCall(ref gaxgrpc::ApiCall<UpdateDomainMappingRequest, lro::Operation> call); partial void Modify_DeleteDomainMappingApiCall(ref gaxgrpc::ApiCall<DeleteDomainMappingRequest, lro::Operation> call); partial void OnConstruction(DomainMappings.DomainMappingsClient grpcClient, DomainMappingsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC DomainMappings client</summary> public override DomainMappings.DomainMappingsClient GrpcClient { get; } partial void Modify_ListDomainMappingsRequest(ref ListDomainMappingsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetDomainMappingRequest(ref GetDomainMappingRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CreateDomainMappingRequest(ref CreateDomainMappingRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_UpdateDomainMappingRequest(ref UpdateDomainMappingRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteDomainMappingRequest(ref DeleteDomainMappingRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Lists the domain mappings on an application. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="DomainMapping"/> resources.</returns> public override gax::PagedEnumerable<ListDomainMappingsResponse, DomainMapping> ListDomainMappings(ListDomainMappingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListDomainMappingsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListDomainMappingsRequest, ListDomainMappingsResponse, DomainMapping>(_callListDomainMappings, request, callSettings); } /// <summary> /// Lists the domain mappings on an application. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="DomainMapping"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListDomainMappingsResponse, DomainMapping> ListDomainMappingsAsync(ListDomainMappingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListDomainMappingsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListDomainMappingsRequest, ListDomainMappingsResponse, DomainMapping>(_callListDomainMappings, request, callSettings); } /// <summary> /// Gets the specified domain mapping. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override DomainMapping GetDomainMapping(GetDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetDomainMappingRequest(ref request, ref callSettings); return _callGetDomainMapping.Sync(request, callSettings); } /// <summary> /// Gets the specified domain mapping. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<DomainMapping> GetDomainMappingAsync(GetDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetDomainMappingRequest(ref request, ref callSettings); return _callGetDomainMapping.Async(request, callSettings); } /// <summary>The long-running operations client for <c>CreateDomainMapping</c>.</summary> public override lro::OperationsClient CreateDomainMappingOperationsClient { get; } /// <summary> /// Maps a domain to an application. A user must be authorized to administer a /// domain in order to map it to an application. For a list of available /// authorized domains, see [`AuthorizedDomains.ListAuthorizedDomains`](). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<DomainMapping, OperationMetadataV1> CreateDomainMapping(CreateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateDomainMappingRequest(ref request, ref callSettings); return new lro::Operation<DomainMapping, OperationMetadataV1>(_callCreateDomainMapping.Sync(request, callSettings), CreateDomainMappingOperationsClient); } /// <summary> /// Maps a domain to an application. A user must be authorized to administer a /// domain in order to map it to an application. For a list of available /// authorized domains, see [`AuthorizedDomains.ListAuthorizedDomains`](). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> CreateDomainMappingAsync(CreateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateDomainMappingRequest(ref request, ref callSettings); return new lro::Operation<DomainMapping, OperationMetadataV1>(await _callCreateDomainMapping.Async(request, callSettings).ConfigureAwait(false), CreateDomainMappingOperationsClient); } /// <summary>The long-running operations client for <c>UpdateDomainMapping</c>.</summary> public override lro::OperationsClient UpdateDomainMappingOperationsClient { get; } /// <summary> /// Updates the specified domain mapping. To map an SSL certificate to a /// domain mapping, update `certificate_id` to point to an `AuthorizedCertificate` /// resource. A user must be authorized to administer the associated domain /// in order to update a `DomainMapping` resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<DomainMapping, OperationMetadataV1> UpdateDomainMapping(UpdateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateDomainMappingRequest(ref request, ref callSettings); return new lro::Operation<DomainMapping, OperationMetadataV1>(_callUpdateDomainMapping.Sync(request, callSettings), UpdateDomainMappingOperationsClient); } /// <summary> /// Updates the specified domain mapping. To map an SSL certificate to a /// domain mapping, update `certificate_id` to point to an `AuthorizedCertificate` /// resource. A user must be authorized to administer the associated domain /// in order to update a `DomainMapping` resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<DomainMapping, OperationMetadataV1>> UpdateDomainMappingAsync(UpdateDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateDomainMappingRequest(ref request, ref callSettings); return new lro::Operation<DomainMapping, OperationMetadataV1>(await _callUpdateDomainMapping.Async(request, callSettings).ConfigureAwait(false), UpdateDomainMappingOperationsClient); } /// <summary>The long-running operations client for <c>DeleteDomainMapping</c>.</summary> public override lro::OperationsClient DeleteDomainMappingOperationsClient { get; } /// <summary> /// Deletes the specified domain mapping. A user must be authorized to /// administer the associated domain in order to delete a `DomainMapping` /// resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<wkt::Empty, OperationMetadataV1> DeleteDomainMapping(DeleteDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteDomainMappingRequest(ref request, ref callSettings); return new lro::Operation<wkt::Empty, OperationMetadataV1>(_callDeleteDomainMapping.Sync(request, callSettings), DeleteDomainMappingOperationsClient); } /// <summary> /// Deletes the specified domain mapping. A user must be authorized to /// administer the associated domain in order to delete a `DomainMapping` /// resource. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<wkt::Empty, OperationMetadataV1>> DeleteDomainMappingAsync(DeleteDomainMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteDomainMappingRequest(ref request, ref callSettings); return new lro::Operation<wkt::Empty, OperationMetadataV1>(await _callDeleteDomainMapping.Async(request, callSettings).ConfigureAwait(false), DeleteDomainMappingOperationsClient); } } public partial class ListDomainMappingsRequest : gaxgrpc::IPageRequest { } public partial class ListDomainMappingsResponse : gaxgrpc::IPageResponse<DomainMapping> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<DomainMapping> GetEnumerator() => DomainMappings.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class DomainMappings { public partial class DomainMappingsClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
using NSubstitute; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Logging; using NuKeeper.Abstractions.Output; using NuKeeper.Commands; using NuKeeper.Inspection.Logging; using NuKeeper.Local; using NUnit.Framework; using System; using System.Threading.Tasks; namespace NuKeeper.Tests.Commands { [TestFixture] public class InspectCommandTests { [Test] public async Task ShouldCallEngineAndSucceed() { var engine = Substitute.For<ILocalEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var command = new InspectCommand(engine, logger, fileSettings); var status = await command.OnExecute(); Assert.That(status, Is.EqualTo(0)); await engine .Received(1) .Run(Arg.Any<SettingsContainer>(), false); } [Test] public async Task EmptyFileResultsInDefaultSettings() { var fileSettings = FileSettings.Empty(); var settings = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.UserSettings, Is.Not.Null); Assert.That(settings.BranchSettings, Is.Not.Null); Assert.That(settings.PackageFilters.MinimumAge, Is.EqualTo(TimeSpan.FromDays(7))); Assert.That(settings.PackageFilters.Excludes, Is.Null); Assert.That(settings.PackageFilters.Includes, Is.Null); Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(0)); Assert.That(settings.UserSettings.AllowedChange, Is.EqualTo(VersionChange.Major)); Assert.That(settings.UserSettings.NuGetSources, Is.Null); Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.Console)); Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Text)); Assert.That(settings.BranchSettings.BranchNameTemplate, Is.Null); } [Test] public async Task WillReadMaxAgeFromFile() { var fileSettings = new FileSettings { Age = "8d" }; var settings = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.PackageFilters.MinimumAge, Is.EqualTo(TimeSpan.FromDays(8))); } [Test] public async Task InvalidMaxAgeWillFail() { var fileSettings = new FileSettings { Age = "fish" }; var settings = await CaptureSettings(fileSettings); Assert.That(settings, Is.Null); } [Test] public async Task WillReadIncludeExcludeFromFile() { var fileSettings = new FileSettings { Include = "foo", Exclude = "bar" }; var settings = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.PackageFilters.Includes.ToString(), Is.EqualTo("foo")); Assert.That(settings.PackageFilters.Excludes.ToString(), Is.EqualTo("bar")); } [Test] public async Task WillReadBranchNamePrefixFromFile() { var testTemplate = "nukeeper/MyBranch"; var fileSettings = new FileSettings { BranchNameTemplate = testTemplate }; var settings = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.BranchSettings, Is.Not.Null); Assert.That(settings.BranchSettings.BranchNameTemplate, Is.EqualTo(testTemplate)); } [Test] public async Task LogLevelIsNormalByDefault() { var engine = Substitute.For<ILocalEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var command = new InspectCommand(engine, logger, fileSettings); await command.OnExecute(); logger .Received(1) .Initialise(LogLevel.Normal, LogDestination.Console, Arg.Any<string>()); } [Test] public async Task ShouldSetLogLevelFromCommand() { var engine = Substitute.For<ILocalEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var command = new InspectCommand(engine, logger, fileSettings); command.Verbosity = LogLevel.Minimal; await command.OnExecute(); logger .Received(1) .Initialise(LogLevel.Minimal, LogDestination.Console, Arg.Any<string>()); } [Test] public async Task ShouldSetLogLevelFromFile() { var engine = Substitute.For<ILocalEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); var settings = new FileSettings { Verbosity = LogLevel.Detailed }; fileSettings.GetSettings().Returns(settings); var command = new InspectCommand(engine, logger, fileSettings); await command.OnExecute(); logger .Received(1) .Initialise(LogLevel.Detailed, LogDestination.Console, Arg.Any<string>()); } [Test] public async Task CommandLineLogLevelOverridesFile() { var engine = Substitute.For<ILocalEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); var settings = new FileSettings { Verbosity = LogLevel.Detailed }; fileSettings.GetSettings().Returns(settings); var command = new InspectCommand(engine, logger, fileSettings); command.Verbosity = LogLevel.Minimal; await command.OnExecute(); logger .Received(1) .Initialise(LogLevel.Minimal, LogDestination.Console, Arg.Any<string>()); } [Test] public async Task LogToFileBySettingFileName() { var engine = Substitute.For<ILocalEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); var settings = FileSettings.Empty(); fileSettings.GetSettings().Returns(settings); var command = new InspectCommand(engine, logger, fileSettings); command.LogFile = "somefile.log"; await command.OnExecute(); logger .Received(1) .Initialise(LogLevel.Normal, LogDestination.File, "somefile.log"); } [Test] public async Task LogToFileBySettingLogDestination() { var engine = Substitute.For<ILocalEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); var settings = FileSettings.Empty(); fileSettings.GetSettings().Returns(settings); var command = new InspectCommand(engine, logger, fileSettings); command.LogDestination = LogDestination.File; await command.OnExecute(); logger .Received(1) .Initialise(LogLevel.Normal, LogDestination.File, "nukeeper.log"); } [Test] public async Task ShouldSetOutputOptionsFromFile() { var fileSettings = new FileSettings { OutputDestination = OutputDestination.File, OutputFormat = OutputFormat.Csv, OutputFileName = "foo.csv" }; var settings = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.File)); Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Csv)); Assert.That(settings.UserSettings.OutputFileName, Is.EqualTo("foo.csv")); } [Test] public async Task WhenFileNameIsExplicit_ShouldDefaultOutputDestToFile() { var fileSettings = new FileSettings { OutputDestination = null, OutputFormat = OutputFormat.Csv }; var settings = await CaptureSettings(fileSettings, null, null, "foo.csv"); Assert.That(settings, Is.Not.Null); Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.File)); Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Csv)); Assert.That(settings.UserSettings.OutputFileName, Is.EqualTo("foo.csv")); } [Test] public async Task WhenFileNameIsExplicit_ShouldKeepOutputDest() { var fileSettings = new FileSettings { OutputDestination = OutputDestination.Off, OutputFormat = OutputFormat.Csv }; var settings = await CaptureSettings(fileSettings, null, null, "foo.csv"); Assert.That(settings, Is.Not.Null); Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.Off)); Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Csv)); Assert.That(settings.UserSettings.OutputFileName, Is.EqualTo("foo.csv")); } [Test] public async Task ShouldSetOutputOptionsFromCommand() { var settingsOut = await CaptureSettings(FileSettings.Empty(), OutputDestination.File, OutputFormat.Csv); Assert.That(settingsOut.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.File)); Assert.That(settingsOut.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Csv)); } public static async Task<SettingsContainer> CaptureSettings(FileSettings settingsIn, OutputDestination? outputDestination = null, OutputFormat? outputFormat = null, string outputFileName = null) { var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); SettingsContainer settingsOut = null; var engine = Substitute.For<ILocalEngine>(); await engine.Run(Arg.Do<SettingsContainer>(x => settingsOut = x), false); fileSettings.GetSettings().Returns(settingsIn); var command = new InspectCommand(engine, logger, fileSettings); if (outputDestination.HasValue) { command.OutputDestination = outputDestination.Value; } if (outputFormat.HasValue) { command.OutputFormat = outputFormat.Value; } if (!string.IsNullOrWhiteSpace(outputFileName)) { command.OutputFileName = outputFileName; } await command.OnExecute(); return settingsOut; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Handlers.Tls { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Net.Security; using System.Runtime.ExceptionServices; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Codecs; using DotNetty.Common.Concurrency; using DotNetty.Common.Utilities; using DotNetty.Transport.Channels; public sealed class TlsHandler : ByteToMessageDecoder { readonly TlsSettings settings; const int FallbackReadBufferSize = 256; const int UnencryptedWriteBatchSize = 14 * 1024; static readonly Exception ChannelClosedException = new IOException("Channel is closed"); static readonly Action<Task, object> HandshakeCompletionCallback = new Action<Task, object>(HandleHandshakeCompleted); readonly SslStream sslStream; readonly MediationStream mediationStream; readonly TaskCompletionSource closeFuture; TlsHandlerState state; int packetLength; volatile IChannelHandlerContext capturedContext; BatchingPendingWriteQueue pendingUnencryptedWrites; Task lastContextWriteTask; bool firedChannelRead; IByteBuffer pendingSslStreamReadBuffer; Task<int> pendingSslStreamReadFuture; public TlsHandler(TlsSettings settings) : this(stream => new SslStream(stream, true), settings) { } public TlsHandler(Func<Stream, SslStream> sslStreamFactory, TlsSettings settings) { Contract.Requires(sslStreamFactory != null); Contract.Requires(settings != null); this.settings = settings; this.closeFuture = new TaskCompletionSource(); this.mediationStream = new MediationStream(this); this.sslStream = sslStreamFactory(this.mediationStream); } public static TlsHandler Client(string targetHost) => new TlsHandler(new ClientTlsSettings(targetHost)); public static TlsHandler Client(string targetHost, X509Certificate clientCertificate) => new TlsHandler(new ClientTlsSettings(targetHost, new List<X509Certificate>{ clientCertificate })); public static TlsHandler Server(X509Certificate certificate) => new TlsHandler(new ServerTlsSettings(certificate)); // using workaround mentioned here: https://github.com/dotnet/corefx/issues/4510 public X509Certificate2 LocalCertificate => this.sslStream.LocalCertificate as X509Certificate2 ?? new X509Certificate2(this.sslStream.LocalCertificate?.Export(X509ContentType.Cert)); public X509Certificate2 RemoteCertificate => this.sslStream.RemoteCertificate as X509Certificate2 ?? new X509Certificate2(this.sslStream.RemoteCertificate?.Export(X509ContentType.Cert)); bool IsServer => this.settings is ServerTlsSettings; public void Dispose() => this.sslStream?.Dispose(); public override void ChannelActive(IChannelHandlerContext context) { base.ChannelActive(context); if (!this.IsServer) { this.EnsureAuthenticated(); } } public override void ChannelInactive(IChannelHandlerContext context) { // Make sure to release SslStream, // and notify the handshake future if the connection has been closed during handshake. this.HandleFailure(ChannelClosedException); base.ChannelInactive(context); } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { if (this.IgnoreException(exception)) { // Close the connection explicitly just in case the transport // did not close the connection automatically. if (context.Channel.Active) { context.CloseAsync(); } } else { base.ExceptionCaught(context, exception); } } bool IgnoreException(Exception t) { if (t is ObjectDisposedException && this.closeFuture.Task.IsCompleted) { return true; } return false; } static void HandleHandshakeCompleted(Task task, object state) { var self = (TlsHandler)state; switch (task.Status) { case TaskStatus.RanToCompletion: { TlsHandlerState oldState = self.state; Contract.Assert(!oldState.HasAny(TlsHandlerState.AuthenticationCompleted)); self.state = (oldState | TlsHandlerState.Authenticated) & ~(TlsHandlerState.Authenticating | TlsHandlerState.FlushedBeforeHandshake); self.capturedContext.FireUserEventTriggered(TlsHandshakeCompletionEvent.Success); if (oldState.Has(TlsHandlerState.ReadRequestedBeforeAuthenticated) && !self.capturedContext.Channel.Configuration.AutoRead) { self.capturedContext.Read(); } if (oldState.Has(TlsHandlerState.FlushedBeforeHandshake)) { self.Wrap(self.capturedContext); self.capturedContext.Flush(); } break; } case TaskStatus.Canceled: case TaskStatus.Faulted: { // ReSharper disable once AssignNullToNotNullAttribute -- task.Exception will be present as task is faulted TlsHandlerState oldState = self.state; Contract.Assert(!oldState.HasAny(TlsHandlerState.AuthenticationCompleted)); self.state = (oldState | TlsHandlerState.FailedAuthentication) & ~TlsHandlerState.Authenticating; self.HandleFailure(task.Exception); break; } default: throw new ArgumentOutOfRangeException(nameof(task), "Unexpected task status: " + task.Status); } } public override void HandlerAdded(IChannelHandlerContext context) { base.HandlerAdded(context); this.capturedContext = context; this.pendingUnencryptedWrites = new BatchingPendingWriteQueue(context, UnencryptedWriteBatchSize); if (context.Channel.Active && !this.IsServer) { // todo: support delayed initialization on an existing/active channel if in client mode this.EnsureAuthenticated(); } } protected override void HandlerRemovedInternal(IChannelHandlerContext context) { if (!this.pendingUnencryptedWrites.IsEmpty) { // Check if queue is not empty first because create a new ChannelException is expensive this.pendingUnencryptedWrites.RemoveAndFailAll(new ChannelException("Write has failed due to TlsHandler being removed from channel pipeline.")); } } protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output) { int startOffset = input.ReaderIndex; int endOffset = input.WriterIndex; int offset = startOffset; int totalLength = 0; List<int> packetLengths; // if we calculated the length of the current SSL record before, use that information. if (this.packetLength > 0) { if (endOffset - startOffset < this.packetLength) { // input does not contain a single complete SSL record return; } else { packetLengths = new List<int>(4); packetLengths.Add(this.packetLength); offset += this.packetLength; totalLength = this.packetLength; this.packetLength = 0; } } else { packetLengths = new List<int>(4); } bool nonSslRecord = false; while (totalLength < TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { int readableBytes = endOffset - offset; if (readableBytes < TlsUtils.SSL_RECORD_HEADER_LENGTH) { break; } int encryptedPacketLength = TlsUtils.GetEncryptedPacketLength(input, offset); if (encryptedPacketLength == -1) { nonSslRecord = true; break; } Contract.Assert(encryptedPacketLength > 0); if (encryptedPacketLength > readableBytes) { // wait until the whole packet can be read this.packetLength = encryptedPacketLength; break; } int newTotalLength = totalLength + encryptedPacketLength; if (newTotalLength > TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { // Don't read too much. break; } // 1. call unwrap with packet boundaries - call SslStream.ReadAsync only once. // 2. once we're through all the whole packets, switch to reading out using fallback sized buffer // We have a whole packet. // Increment the offset to handle the next packet. packetLengths.Add(encryptedPacketLength); offset += encryptedPacketLength; totalLength = newTotalLength; } if (totalLength > 0) { // The buffer contains one or more full SSL records. // Slice out the whole packet so unwrap will only be called with complete packets. // Also directly reset the packetLength. This is needed as unwrap(..) may trigger // decode(...) again via: // 1) unwrap(..) is called // 2) wrap(...) is called from within unwrap(...) // 3) wrap(...) calls unwrapLater(...) // 4) unwrapLater(...) calls decode(...) // // See https://github.com/netty/netty/issues/1534 input.SkipBytes(totalLength); this.Unwrap(context, input, startOffset, totalLength, packetLengths, output); if (!this.firedChannelRead) { // Check first if firedChannelRead is not set yet as it may have been set in a // previous decode(...) call. this.firedChannelRead = output.Count > 0; } } if (nonSslRecord) { // Not an SSL/TLS packet var ex = new NotSslRecordException( "not an SSL/TLS record: " + ByteBufferUtil.HexDump(input)); input.SkipBytes(input.ReadableBytes); context.FireExceptionCaught(ex); this.HandleFailure(ex); } } public override void ChannelReadComplete(IChannelHandlerContext ctx) { // Discard bytes of the cumulation buffer if needed. this.DiscardSomeReadBytes(); this.ReadIfNeeded(ctx); this.firedChannelRead = false; ctx.FireChannelReadComplete(); } void ReadIfNeeded(IChannelHandlerContext ctx) { // if handshake is not finished yet, we need more data if (!ctx.Channel.Configuration.AutoRead && (!this.firedChannelRead || !this.state.HasAny(TlsHandlerState.AuthenticationCompleted))) { // No auto-read used and no message was passed through the ChannelPipeline or the handshake was not completed // yet, which means we need to trigger the read to ensure we will not stall ctx.Read(); } } /// <summary>Unwraps inbound SSL records.</summary> void Unwrap(IChannelHandlerContext ctx, IByteBuffer packet, int offset, int length, List<int> packetLengths, List<object> output) { Contract.Requires(packetLengths.Count > 0); //bool notifyClosure = false; // todo: netty/issues/137 bool pending = false; IByteBuffer outputBuffer = null; try { ArraySegment<byte> inputIoBuffer = packet.GetIoBuffer(offset, length); this.mediationStream.SetSource(inputIoBuffer.Array, inputIoBuffer.Offset); int packetIndex = 0; while (!this.EnsureAuthenticated()) { this.mediationStream.ExpandSource(packetLengths[packetIndex]); if (++packetIndex == packetLengths.Count) { return; } } Task<int> currentReadFuture = this.pendingSslStreamReadFuture; int outputBufferLength; if (currentReadFuture != null) { // restoring context from previous read Contract.Assert(this.pendingSslStreamReadBuffer != null); outputBuffer = this.pendingSslStreamReadBuffer; outputBufferLength = outputBuffer.WritableBytes; } else { outputBufferLength = 0; } // go through packets one by one (because SslStream does not consume more than 1 packet at a time) for (; packetIndex < packetLengths.Count; packetIndex++) { int currentPacketLength = packetLengths[packetIndex]; this.mediationStream.ExpandSource(currentPacketLength); if (currentReadFuture != null) { // there was a read pending already, so we make sure we completed that first if (!currentReadFuture.IsCompleted) { // we did feed the whole current packet to SslStream yet it did not produce any result -> move to the next packet in input Contract.Assert(this.mediationStream.SourceReadableBytes == 0); continue; } int read = currentReadFuture.Result; // Now output the result of previous read and decide whether to do an extra read on the same source or move forward AddBufferToOutput(outputBuffer, read, output); currentReadFuture = null; if (this.mediationStream.SourceReadableBytes == 0) { // we just made a frame available for reading but there was already pending read so SslStream read it out to make further progress there if (read < outputBufferLength) { // SslStream returned non-full buffer and there's no more input to go through -> // typically it means SslStream is done reading current frame so we skip continue; } // we've read out `read` bytes out of current packet to fulfil previously outstanding read outputBufferLength = currentPacketLength - read; if (outputBufferLength <= 0) { // after feeding to SslStream current frame it read out more bytes than current packet size outputBufferLength = FallbackReadBufferSize; } } else { // SslStream did not get to reading current frame so it completed previous read sync // and the next read will likely read out the new frame outputBufferLength = currentPacketLength; } } else { // there was no pending read before so we estimate buffer of `currentPacketLength` bytes to be sufficient outputBufferLength = currentPacketLength; } outputBuffer = ctx.Allocator.Buffer(outputBufferLength); currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, outputBufferLength); } // read out the rest of SslStream's output (if any) at risk of going async // using FallbackReadBufferSize - buffer size we're ok to have pinned with the SslStream until it's done reading while (true) { if (currentReadFuture != null) { if (!currentReadFuture.IsCompleted) { break; } int read = currentReadFuture.Result; AddBufferToOutput(outputBuffer, read, output); } outputBuffer = ctx.Allocator.Buffer(FallbackReadBufferSize); currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, FallbackReadBufferSize); } pending = true; this.pendingSslStreamReadBuffer = outputBuffer; this.pendingSslStreamReadFuture = currentReadFuture; } catch (Exception ex) { this.HandleFailure(ex); throw; } finally { this.mediationStream.ResetSource(); if (!pending && outputBuffer != null) { if (outputBuffer.IsReadable()) { output.Add(outputBuffer); } else { outputBuffer.SafeRelease(); } } } } static void AddBufferToOutput(IByteBuffer outputBuffer, int length, List<object> output) { Contract.Assert(length > 0); output.Add(outputBuffer.SetWriterIndex(outputBuffer.WriterIndex + length)); } Task<int> ReadFromSslStreamAsync(IByteBuffer outputBuffer, int outputBufferLength) { ArraySegment<byte> outlet = outputBuffer.GetIoBuffer(outputBuffer.WriterIndex, outputBufferLength); return this.sslStream.ReadAsync(outlet.Array, outlet.Offset, outlet.Count); } public override void Read(IChannelHandlerContext context) { TlsHandlerState oldState = this.state; if (!oldState.HasAny(TlsHandlerState.AuthenticationCompleted)) { this.state = oldState | TlsHandlerState.ReadRequestedBeforeAuthenticated; } context.Read(); } bool EnsureAuthenticated() { TlsHandlerState oldState = this.state; if (!oldState.HasAny(TlsHandlerState.AuthenticationStarted)) { this.state = oldState | TlsHandlerState.Authenticating; if (this.IsServer) { var serverSettings = (ServerTlsSettings)this.settings; this.sslStream.AuthenticateAsServerAsync(serverSettings.Certificate, serverSettings.NegotiateClientCertificate, serverSettings.EnabledProtocols, serverSettings.CheckCertificateRevocation) .ContinueWith(HandshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously); } else { var clientSettings = (ClientTlsSettings)this.settings; this.sslStream.AuthenticateAsClientAsync(clientSettings.TargetHost, clientSettings.X509CertificateCollection, clientSettings.EnabledProtocols, clientSettings.CheckCertificateRevocation) .ContinueWith(HandshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously); } return false; } return oldState.Has(TlsHandlerState.Authenticated); } public override Task WriteAsync(IChannelHandlerContext context, object message) { if (!(message is IByteBuffer)) { return TaskEx.FromException(new UnsupportedMessageTypeException(message, typeof(IByteBuffer))); } return this.pendingUnencryptedWrites.Add(message); } public override void Flush(IChannelHandlerContext context) { if (this.pendingUnencryptedWrites.IsEmpty) { this.pendingUnencryptedWrites.Add(Unpooled.Empty); } if (!this.EnsureAuthenticated()) { this.state |= TlsHandlerState.FlushedBeforeHandshake; return; } try { this.Wrap(context); } finally { // We may have written some parts of data before an exception was thrown so ensure we always flush. context.Flush(); } } void Wrap(IChannelHandlerContext context) { Contract.Assert(context == this.capturedContext); IByteBuffer buf = null; try { while (true) { List<object> messages = this.pendingUnencryptedWrites.Current; if (messages == null || messages.Count == 0) { break; } if (messages.Count == 1) { buf = (IByteBuffer)messages[0]; } else { buf = context.Allocator.Buffer((int)this.pendingUnencryptedWrites.CurrentSize); foreach (IByteBuffer buffer in messages) { buffer.ReadBytes(buf, buffer.ReadableBytes); buffer.Release(); } } buf.ReadBytes(this.sslStream, buf.ReadableBytes); // this leads to FinishWrap being called 0+ times buf.Release(); TaskCompletionSource promise = this.pendingUnencryptedWrites.Remove(); Task task = this.lastContextWriteTask; if (task != null) { task.LinkOutcome(promise); this.lastContextWriteTask = null; } else { promise.TryComplete(); } } } catch (Exception ex) { buf.SafeRelease(); this.HandleFailure(ex); throw; } } void FinishWrap(byte[] buffer, int offset, int count) { IByteBuffer output; if (count == 0) { output = Unpooled.Empty; } else { output = this.capturedContext.Allocator.Buffer(count); output.WriteBytes(buffer, offset, count); } this.lastContextWriteTask = this.capturedContext.WriteAsync(output); } public override Task CloseAsync(IChannelHandlerContext context) { this.closeFuture.TryComplete(); this.sslStream.Dispose(); return base.CloseAsync(context); } void HandleFailure(Exception cause) { // Release all resources such as internal buffers that SSLEngine // is managing. try { this.sslStream.Dispose(); } catch (Exception) { // todo: evaluate following: // only log in Debug mode as it most likely harmless and latest chrome still trigger // this all the time. // // See https://github.com/netty/netty/issues/1340 //string msg = ex.Message; //if (msg == null || !msg.contains("possible truncation attack")) //{ // //Logger.Debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e); //} } this.NotifyHandshakeFailure(cause); this.pendingUnencryptedWrites.RemoveAndFailAll(cause); } void NotifyHandshakeFailure(Exception cause) { if (!this.state.HasAny(TlsHandlerState.AuthenticationCompleted)) { // handshake was not completed yet => TlsHandler react to failure by closing the channel this.state = (this.state | TlsHandlerState.FailedAuthentication) & ~TlsHandlerState.Authenticating; this.capturedContext.FireUserEventTriggered(new TlsHandshakeCompletionEvent(cause)); this.CloseAsync(this.capturedContext); } } sealed class MediationStream : Stream { readonly TlsHandler owner; byte[] input; int inputStartOffset; int inputOffset; int inputLength; TaskCompletionSource<int> readCompletionSource; ArraySegment<byte> sslOwnedBuffer; #if NETSTANDARD1_3 int readByteCount; #else SynchronousAsyncResult<int> syncReadResult; AsyncCallback readCallback; TaskCompletionSource writeCompletion; AsyncCallback writeCallback; #endif public MediationStream(TlsHandler owner) { this.owner = owner; } public int SourceReadableBytes => this.inputLength - this.inputOffset; public void SetSource(byte[] source, int offset) { this.input = source; this.inputStartOffset = offset; this.inputOffset = 0; this.inputLength = 0; } public void ResetSource() { this.input = null; this.inputLength = 0; } public void ExpandSource(int count) { Contract.Assert(this.input != null); this.inputLength += count; TaskCompletionSource<int> promise = this.readCompletionSource; if (promise == null) { // there is no pending read operation - keep for future return; } ArraySegment<byte> sslBuffer = this.sslOwnedBuffer; #if NETSTANDARD1_3 this.readByteCount = this.ReadFromInput(sslBuffer.Array, sslBuffer.Offset, sslBuffer.Count); // hack: this tricks SslStream's continuation to run synchronously instead of dispatching to TP. Remove once Begin/EndRead are available. new Task( ms => { var self = (MediationStream)ms; TaskCompletionSource<int> p = self.readCompletionSource; this.readCompletionSource = null; p.TrySetResult(self.readByteCount); }, this) .RunSynchronously(TaskScheduler.Default); #else int read = this.ReadFromInput(sslBuffer.Array, sslBuffer.Offset, sslBuffer.Count); this.readCompletionSource = null; promise.TrySetResult(read); this.readCallback?.Invoke(promise.Task); #endif } #if NETSTANDARD1_3 public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (this.inputLength - this.inputOffset > 0) { // we have the bytes available upfront - write out synchronously int read = this.ReadFromInput(buffer, offset, count); return Task.FromResult(read); } // take note of buffer - we will pass bytes there once available this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count); this.readCompletionSource = new TaskCompletionSource<int>(); return this.readCompletionSource.Task; } #else public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (this.inputLength - this.inputOffset > 0) { // we have the bytes available upfront - write out synchronously int read = this.ReadFromInput(buffer, offset, count); return this.PrepareSyncReadResult(read, state); } // take note of buffer - we will pass bytes there once available this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count); this.readCompletionSource = new TaskCompletionSource<int>(state); this.readCallback = callback; return this.readCompletionSource.Task; } public override int EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult<int> syncResult = this.syncReadResult; if (ReferenceEquals(asyncResult, syncResult)) { return syncResult.Result; } Contract.Assert(!((Task<int>)asyncResult).IsCanceled); try { return ((Task<int>)asyncResult).Result; } catch (AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; // unreachable } finally { this.readCompletionSource = null; this.readCallback = null; this.sslOwnedBuffer = default(ArraySegment<byte>); } } IAsyncResult PrepareSyncReadResult(int readBytes, object state) { // it is safe to reuse sync result object as it can't lead to leak (no way to attach to it via handle) SynchronousAsyncResult<int> result = this.syncReadResult ?? (this.syncReadResult = new SynchronousAsyncResult<int>()); result.Result = readBytes; result.AsyncState = state; return result; } #endif public override void Write(byte[] buffer, int offset, int count) => this.owner.FinishWrap(buffer, offset, count); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => this.owner.capturedContext.WriteAndFlushAsync(Unpooled.WrappedBuffer(buffer, offset, count)); #if !NETSTANDARD1_3 static readonly Action<Task, object> WriteCompleteCallback = HandleChannelWriteComplete; public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { Task task = this.owner.capturedContext.WriteAndFlushAsync(Unpooled.WrappedBuffer(buffer, offset, count)); switch (task.Status) { case TaskStatus.RanToCompletion: // write+flush completed synchronously (and successfully) var result = new SynchronousAsyncResult<int>(); result.AsyncState = state; callback(result); return result; default: this.writeCallback = callback; var tcs = new TaskCompletionSource(state); this.writeCompletion = tcs; task.ContinueWith(WriteCompleteCallback, this, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } } static void HandleChannelWriteComplete(Task writeTask, object state) { var self = (MediationStream)state; switch (writeTask.Status) { case TaskStatus.RanToCompletion: self.writeCompletion.TryComplete(); break; case TaskStatus.Canceled: self.writeCompletion.TrySetCanceled(); break; case TaskStatus.Faulted: self.writeCompletion.TrySetException(writeTask.Exception); break; default: throw new ArgumentOutOfRangeException("Unexpected task status: " + writeTask.Status); } self.writeCallback?.Invoke(self.writeCompletion.Task); } public override void EndWrite(IAsyncResult asyncResult) { this.writeCallback = null; this.writeCompletion = null; if (asyncResult is SynchronousAsyncResult<int>) { return; } try { ((Task<int>)asyncResult).Wait(); } catch (AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } #endif int ReadFromInput(byte[] destination, int destinationOffset, int destinationCapacity) { Contract.Assert(destination != null); byte[] source = this.input; int readableBytes = this.inputLength - this.inputOffset; int length = Math.Min(readableBytes, destinationCapacity); Buffer.BlockCopy(source, this.inputStartOffset + this.inputOffset, destination, destinationOffset, length); this.inputOffset += length; return length; } public override void Flush() { // NOOP: called on SslStream.Close } #region plumbing public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endregion #region sync result sealed class SynchronousAsyncResult<T> : IAsyncResult { public T Result { get; set; } public bool IsCompleted => true; public WaitHandle AsyncWaitHandle { get { throw new InvalidOperationException("Cannot wait on a synchronous result."); } } public object AsyncState { get; set; } public bool CompletedSynchronously => true; } #endregion } } [Flags] enum TlsHandlerState { Authenticating = 1, Authenticated = 1 << 1, FailedAuthentication = 1 << 2, ReadRequestedBeforeAuthenticated = 1 << 3, FlushedBeforeHandshake = 1 << 4, AuthenticationStarted = Authenticating | Authenticated | FailedAuthentication, AuthenticationCompleted = Authenticated | FailedAuthentication } static class TlsHandlerStateExtensions { public static bool Has(this TlsHandlerState value, TlsHandlerState testValue) => (value & testValue) == testValue; public static bool HasAny(this TlsHandlerState value, TlsHandlerState testValue) => (value & testValue) != 0; } }
// 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using ObjectFormatterFixtures; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests { public class ObjectFormatterTests : ObjectFormatterTestBase { private static readonly ObjectFormatter s_formatter = new TestCSharpObjectFormatter(); [Fact] public void Objects() { string str; object nested = new Outer.Nested<int>(); str = s_formatter.FormatObject(nested, SingleLineOptions); Assert.Equal(@"Outer.Nested<int> { A=1, B=2 }", str); str = s_formatter.FormatObject(nested, HiddenOptions); Assert.Equal(@"Outer.Nested<int>", str); str = s_formatter.FormatObject(A<int>.X, HiddenOptions); Assert.Equal(@"A<int>.B<int>", str); object obj = new A<int>.B<bool>.C.D<string, double>.E(); str = s_formatter.FormatObject(obj, HiddenOptions); Assert.Equal(@"A<int>.B<bool>.C.D<string, double>.E", str); var sort = new Sort(); str = new TestCSharpObjectFormatter(maximumLineLength: 51).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1...", str); Assert.Equal(51 + 3, str.Length); str = new TestCSharpObjectFormatter(maximumLineLength: 5).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort ...", str); Assert.Equal(5 + 3, str.Length); str = new TestCSharpObjectFormatter(maximumLineLength: 4).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 3).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sor...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 2).FormatObject(sort, SingleLineOptions); Assert.Equal(@"So...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 1).FormatObject(sort, SingleLineOptions); Assert.Equal(@"S...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 80).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1, AG=1 }", str); } [Fact] public void ArrayOfInt32_NoMembers() { object o = new int[4] { 3, 4, 5, 6 }; var str = s_formatter.FormatObject(o, HiddenOptions); Assert.Equal("int[4] { 3, 4, 5, 6 }", str); } #region DANGER: Debugging this method under VS2010 might freeze your machine. [Fact] public void RecursiveRootHidden() { var DO_NOT_ADD_TO_WATCH_WINDOW = new RecursiveRootHidden(); DO_NOT_ADD_TO_WATCH_WINDOW.C = DO_NOT_ADD_TO_WATCH_WINDOW; string str = s_formatter.FormatObject(DO_NOT_ADD_TO_WATCH_WINDOW, SingleLineOptions); Assert.Equal(@"RecursiveRootHidden { A=0, B=0 }", str); } #endregion [Fact] public void DebuggerDisplay_ParseSimpleMemberName() { Test_ParseSimpleMemberName("foo", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName("foo ", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName(" foo", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName(" foo ", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName("foo()", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName("\nfoo (\r\n)", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName(" foo ( \t) ", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName("foo,nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo ,nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo(),nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName(" foo \t( ) ,nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName(" foo \t( ) , nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName("foo, nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo(,nq", name: "foo(", callable: false, nq: true); Test_ParseSimpleMemberName("foo),nq", name: "foo)", callable: false, nq: true); Test_ParseSimpleMemberName("foo ( ,nq", name: "foo (", callable: false, nq: true); Test_ParseSimpleMemberName("foo ) ,nq", name: "foo )", callable: false, nq: true); Test_ParseSimpleMemberName(",nq", name: "", callable: false, nq: true); Test_ParseSimpleMemberName(" ,nq", name: "", callable: false, nq: true); } private void Test_ParseSimpleMemberName(string value, string name, bool callable, bool nq) { bool actualNoQuotes, actualIsCallable; string actualName = ObjectFormatterHelpers.ParseSimpleMemberName(value, 0, value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); actualName = ObjectFormatterHelpers.ParseSimpleMemberName("---" + value + "-", 3, 3 + value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); } [Fact] public void DebuggerDisplay() { string str; var a = new ComplexProxy(); str = s_formatter.FormatObject(a, SeparateLinesOptions); AssertMembers(str, @"[AStr]", @"_02_public_property_dd: *1", @"_03_private_property_dd: *2", @"_04_protected_property_dd: *3", @"_05_internal_property_dd: *4", @"_07_private_field_dd: +2", @"_08_protected_field_dd: +3", @"_09_internal_field_dd: +4", @"_10_private_collapsed: 0", @"_12_public: 0", @"_13_private: 0", @"_14_protected: 0", @"_15_internal: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_33: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1", @"_40_private_get_private_set: 1" ); var b = new TypeWithComplexProxy(); str = s_formatter.FormatObject(b, SeparateLinesOptions); AssertMembers(str, @"[BStr]", @"_02_public_property_dd: *1", @"_04_protected_property_dd: *3", @"_08_protected_field_dd: +3", @"_10_private_collapsed: 0", @"_12_public: 0", @"_14_protected: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1" ); } [Fact] public void DebuggerDisplay_Inherited() { var obj = new InheritedDebuggerDisplay(); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("InheritedDebuggerDisplay(DebuggerDisplayValue)", str); } [Fact] public void DebuggerProxy_DebuggerDisplayAndProxy() { var obj = new TypeWithDebuggerDisplayAndProxy(); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("TypeWithDebuggerDisplayAndProxy(DD) { A=0, B=0 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "TypeWithDebuggerDisplayAndProxy(DD)", "A: 0", "B: 0" ); } [Fact] public void DebuggerProxy_Recursive() { string str; object obj = new RecursiveProxy.Node(0); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "RecursiveProxy.Node", "x: 0", "y: RecursiveProxy.Node { x=1, y=RecursiveProxy.Node { x=2, y=RecursiveProxy.Node { x=3, y=RecursiveProxy.Node { x=4, y=RecursiveProxy.Node { x=5, y=null } } } } }" ); obj = new InvalidRecursiveProxy.Node(); str = s_formatter.FormatObject(obj, SeparateLinesOptions); // TODO: better overflow handling Assert.Equal("!<Stack overflow while evaluating object>", str); } [Fact] public void Array_Recursive() { string str; ListNode n2; ListNode n1 = new ListNode(); object[] obj = new object[5]; obj[0] = 1; obj[1] = obj; obj[2] = n2 = new ListNode() { data = obj, next = n1 }; obj[3] = new object[] { 4, 5, obj, 6, new ListNode() }; obj[4] = 3; n1.next = n2; n1.data = new object[] { 7, n2, 8, obj }; str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "object[5]", "1", "{ ... }", "ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }", "object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }", "3" ); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal(str, "object[5] { 1, { ... }, ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }, object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }, 3 }"); } [Fact] public void LargeGraph() { var list = new LinkedList<object>(); object obj = list; for (int i = 0; i < 10000; i++) { var node = list.AddFirst(i); var newList = new LinkedList<object>(); list.AddAfter(node, newList); list = newList; } string output = "LinkedList<object>(2) { 0, LinkedList<object>(2) { 1, LinkedList<object>(2) { 2, LinkedList<object>(2) {"; for (int i = 100; i > 4; i--) { var printOptions = new PrintOptions { MaximumOutputLength = i, MemberDisplayFormat = MemberDisplayFormat.SingleLine, }; var actual = s_formatter.FormatObject(obj, printOptions); var expected = output.Substring(0, i) + "..."; Assert.Equal(expected, actual); } } [Fact] public void LongMembers() { object obj = new LongMembers(); var str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SingleLineOptions); Assert.Equal("LongMembers { LongNa...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SeparateLinesOptions); Assert.Equal("LongMembers {\r\n LongName0123456789...\r\n LongValue: \"012345...\r\n}\r\n", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Array() { var obj = new Object[] { new C(), 1, "str", 'c', true, null, new bool[] { true, false, true, false } }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "object[7]", "[CStr]", "1", "\"str\"", "'c'", "true", "null", "bool[4] { true, false, true, false }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_MdArray() { string str; int[,,] a = new int[2, 3, 4] { { { 000, 001, 002, 003 }, { 010, 011, 012, 013 }, { 020, 021, 022, 023 }, }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 }, } }; str = s_formatter.FormatObject(a, SingleLineOptions); Assert.Equal("int[2, 3, 4] { { { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } } }", str); str = s_formatter.FormatObject(a, SeparateLinesOptions); AssertMembers(str, "int[2, 3, 4]", "{ { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }", "{ { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } }" ); int[][,][,,,] obj = new int[2][,][,,,]; obj[0] = new int[1, 2][,,,]; obj[0][0, 0] = new int[1, 2, 3, 4]; str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("int[2][,][,,,] { int[1, 2][,,,] { { int[1, 2, 3, 4] { { { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } } } }, null } }, null }", str); Array x = Array.CreateInstance(typeof(Object), lengths: new int[] { 2, 3 }, lowerBounds: new int[] { 2, 9 }); str = s_formatter.FormatObject(x, SingleLineOptions); Assert.Equal("object[2..4, 9..12] { { null, null, null }, { null, null, null } }", str); Array y = Array.CreateInstance(typeof(Object), lengths: new int[] { 1, 1 }, lowerBounds: new int[] { 0, 0 }); str = s_formatter.FormatObject(y, SingleLineOptions); Assert.Equal("object[1, 1] { { null } }", str); Array z = Array.CreateInstance(typeof(Object), lengths: new int[] { 0, 0 }, lowerBounds: new int[] { 0, 0 }); str = s_formatter.FormatObject(z, SingleLineOptions); Assert.Equal("object[0, 0] { }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable() { string str; object obj; obj = Enumerable.Range(0, 10); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("RangeIterator { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Exception() { string str; object obj; obj = Enumerable.Range(0, 10).Where(i => { if (i == 5) throw new Exception("xxx"); return i < 7; }); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Enumerable.WhereEnumerableIterator<int> { 0, 1, 2, 3, 4, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary() { string str; object obj; obj = new ThrowingDictionary(throwAt: -1); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "ThrowingDictionary(10)", "{ 1, 1 }", "{ 2, 2 }", "{ 3, 3 }", "{ 4, 4 }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary_Exception() { string str; object obj; obj = new ThrowingDictionary(throwAt: 3); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BitArray() { // BitArray doesn't have debugger proxy/display var obj = new System.Collections.BitArray(new int[] { 1 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("BitArray(32) { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Queue() { var obj = new Queue<int>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Queue<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Stack() { var obj = new Stack<int>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Stack<int>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Dictionary() { var obj = new Dictionary<string, int> { { "x", 1 }, }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Dictionary<string, int>(1)", "{ \"x\", 1 }" ); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Dictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_KeyValuePair() { var obj = new KeyValuePair<int, string>(1, "x"); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("KeyValuePair<int, string> { 1, \"x\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_List() { var obj = new List<object> { 1, 2, 'c' }; var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("List<object>(3) { 1, 2, 'c' }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_LinkedList() { var obj = new LinkedList<int>(); obj.AddLast(1); obj.AddLast(2); obj.AddLast(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("LinkedList<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedList() { var obj = new SortedList<int, int>(); obj.Add(3, 4); obj.Add(1, 5); obj.Add(2, 6); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedList<int, int>(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str); var obj2 = new SortedList<int[], int[]>(); obj2.Add(new[] { 3 }, new int[] { 4 }); str = s_formatter.FormatObject(obj2, SingleLineOptions); Assert.Equal("SortedList<int[], int[]>(1) { { int[1] { 3 }, int[1] { 4 } } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedDictionary() { var obj = new SortedDictionary<int, int>(); obj.Add(1, 0x1a); obj.Add(3, 0x3c); obj.Add(2, 0x2b); var str = s_formatter. FormatObject(obj, new PrintOptions { NumberRadix = ObjectFormatterHelpers.NumberRadixHexadecimal }); Assert.Equal("SortedDictionary<int, int>(3) { { 0x00000001, 0x0000001a }, { 0x00000002, 0x0000002b }, { 0x00000003, 0x0000003c } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_HashSet() { var obj = new HashSet<int>(); obj.Add(1); obj.Add(2); // HashSet doesn't implement ICollection (it only implements ICollection<T>) so we don't call Count, // instead a DebuggerDisplay.Value is used. var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("HashSet<int>(Count = 2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedSet() { var obj = new SortedSet<int>(); obj.Add(1); obj.Add(2); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedSet<int>(2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentDictionary() { var obj = new ConcurrentDictionary<string, int>(); obj.AddOrUpdate("x", 1, (k, v) => v); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentDictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentQueue() { var obj = new ConcurrentQueue<object>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentQueue<object>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentStack() { var obj = new ConcurrentStack<object>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentStack<object>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BlockingCollection() { var obj = new BlockingCollection<int>(); obj.Add(1); obj.Add(2, new CancellationToken()); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("BlockingCollection<int>(2) { 1, 2 }", str); } // TODO(tomat): this only works with System.dll file version 30319.16644 (Win8 build) //[Fact] //public void DebuggerProxy_FrameworkTypes_ConcurrentBag() //{ // var obj = new ConcurrentBag<int>(); // obj.Add(1); // var str = ObjectFormatter.Instance.FormatObject(obj, quoteStrings: true, memberFormat: MemberDisplayFormat.Inline); // Assert.Equal("ConcurrentBag<int>(1) { 1 }", str); //} [Fact] public void DebuggerProxy_FrameworkTypes_ReadOnlyCollection() { var obj = new System.Collections.ObjectModel.ReadOnlyCollection<int>(new[] { 1, 2, 3 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ReadOnlyCollection<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Lazy() { var obj = new Lazy<int[]>(() => new int[] { 1, 2 }, LazyThreadSafetyMode.None); // Lazy<T> has both DebuggerDisplay and DebuggerProxy attributes and both display the same information. var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null) { IsValueCreated=false, IsValueFaulted=false, Mode=None, Value=null }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null)", "IsValueCreated: false", "IsValueFaulted: false", "Mode: None", "Value: null" ); Assert.NotNull(obj.Value); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 }) { IsValueCreated=true, IsValueFaulted=false, Mode=None, Value=int[2] { 1, 2 } }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 })", "IsValueCreated: true", "IsValueFaulted: false", "Mode: None", "Value: int[2] { 1, 2 }" ); } public void TaskMethod() { } [Fact] public void DebuggerProxy_FrameworkTypes_Task() { var obj = new System.Threading.Tasks.Task(TaskMethod); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal( @"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"") { AsyncState=null, CancellationPending=false, CreationOptions=None, Exception=null, Id=*, Status=Created }", FilterDisplayString(str)); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(FilterDisplayString(str), @"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"")", "AsyncState: null", "CancellationPending: false", "CreationOptions: None", "Exception: null", "Id: *", "Status: Created" ); } [Fact] public void DebuggerProxy_FrameworkTypes_SpinLock() { var obj = new SpinLock(); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=false, OwnerThreadID=0 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "SpinLock(IsHeld = false)", "IsHeld: false", "IsHeldByCurrentThread: false", "OwnerThreadID: 0" ); } [Fact] public void DebuggerProxy_DiagnosticBag() { var obj = new DiagnosticBag(); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_AbstractAndExtern, "bar"), NoLocation.Singleton); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_BadExternIdentifier, "foo"), NoLocation.Singleton); using (new EnsureEnglishUICulture()) { var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("DiagnosticBag(Count = 2) { =error CS0180: 'bar' cannot be both extern and abstract, =error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "DiagnosticBag(Count = 2)", ": error CS0180: 'bar' cannot be both extern and abstract", ": error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier" ); } } [Fact] public void DebuggerProxy_ArrayBuilder() { var obj = new ArrayBuilder<int>(); obj.AddRange(new[] { 1, 2, 3, 4, 5 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ArrayBuilder<int>(Count = 5) { 1, 2, 3, 4, 5 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "ArrayBuilder<int>(Count = 5)", "1", "2", "3", "4", "5" ); } [WorkItem(8542, "https://github.com/dotnet/roslyn/issues/8452")] [Fact] public void FormatConstructorSignature() { var constructor = typeof(object).GetTypeInfo().DeclaredConstructors.Single(); var signature = ((CommonObjectFormatter)s_formatter).FormatMethodSignature(constructor); Assert.Equal("object..ctor()", signature); // Checking for exceptions, more than particular output. } // The stack trace contains line numbers. We use a #line directive // so that the baseline doesn't need to be updated every time this // file changes. // // When adding a new test to this region, ADD IT ADD THE END, so you // don't have to update all the other baselines. #line 10000 "z:\Fixture.cs" private static class Fixture { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method() { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>() { throw new Exception(); } } private static class Fixture<T> { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method() { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>() { throw new Exception(); } } [Fact] public void StackTrace_NonGeneric() { try { Fixture.Method(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; var expected = $@"Exception of type 'System.Exception' was thrown. + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10006)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_NonGeneric(){string.Format(ScriptingResources.AtFileLine, filePath, 10036)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact] public void StackTrace_GenericMethod() { try { Fixture.Method<char>(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture.Method<char> var expected = $@"Exception of type 'System.Exception' was thrown. + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10012)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethod(){string.Format(ScriptingResources.AtFileLine, filePath, 10057)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact] public void StackTrace_GenericType() { try { Fixture<int>.Method(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture<int>.Method var expected = $@"Exception of type 'System.Exception' was thrown. + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10021)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10079)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact] public void StackTrace_GenericMethodInGenericType() { try { Fixture<int>.Method<char>(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture<int>.Method<char> var expected = $@"Exception of type 'System.Exception' was thrown. + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10027)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethodInGenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10101)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } } }
//------------------------------------------------------------------------------ // <copyright file="XmlSchemaSerializer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System; using System.Text; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Collections; using System.Collections.Specialized; internal class XmlAttributeComparer : IComparer { public int Compare(object o1, object o2) { XmlAttribute a1 = (XmlAttribute)o1; XmlAttribute a2 = (XmlAttribute)o2; int ns = String.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal); if (ns == 0) { return String.Compare(a1.Name, a2.Name, StringComparison.Ordinal); } return ns; } } internal class XmlFacetComparer : IComparer { public int Compare(object o1, object o2) { XmlSchemaFacet f1 = (XmlSchemaFacet)o1; XmlSchemaFacet f2 = (XmlSchemaFacet)o2; return String.Compare(f1.GetType().Name + ":" + f1.Value, f2.GetType().Name + ":" + f2.Value, StringComparison.Ordinal); } } internal class QNameComparer : IComparer { public int Compare(object o1, object o2) { XmlQualifiedName qn1 = (XmlQualifiedName)o1; XmlQualifiedName qn2 = (XmlQualifiedName)o2; int ns = String.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal); if (ns == 0) { return String.Compare(qn1.Name, qn2.Name, StringComparison.Ordinal); } return ns; } } internal class XmlSchemaObjectComparer : IComparer { QNameComparer comparer = new QNameComparer(); public int Compare(object o1, object o2) { return comparer.Compare(NameOf((XmlSchemaObject)o1), NameOf((XmlSchemaObject)o2)); } internal static XmlQualifiedName NameOf(XmlSchemaObject o) { if (o is XmlSchemaAttribute) { return ((XmlSchemaAttribute)o).QualifiedName; } else if (o is XmlSchemaAttributeGroup) { return ((XmlSchemaAttributeGroup)o).QualifiedName; } else if (o is XmlSchemaComplexType) { return ((XmlSchemaComplexType)o).QualifiedName; } else if (o is XmlSchemaSimpleType) { return ((XmlSchemaSimpleType)o).QualifiedName; } else if (o is XmlSchemaElement) { return ((XmlSchemaElement)o).QualifiedName; } else if (o is XmlSchemaGroup) { return ((XmlSchemaGroup)o).QualifiedName; } else if (o is XmlSchemaGroupRef) { return ((XmlSchemaGroupRef)o).RefName; } else if (o is XmlSchemaNotation) { return ((XmlSchemaNotation)o).QualifiedName; } else if (o is XmlSchemaSequence) { XmlSchemaSequence s = (XmlSchemaSequence)o; if (s.Items.Count == 0) return new XmlQualifiedName(".sequence", Namespace(o)); return NameOf(s.Items[0]); } else if (o is XmlSchemaAll) { XmlSchemaAll a = (XmlSchemaAll)o; if (a.Items.Count == 0) return new XmlQualifiedName(".all", Namespace(o)); return NameOf(a.Items); } else if (o is XmlSchemaChoice) { XmlSchemaChoice c = (XmlSchemaChoice)o; if (c.Items.Count == 0) return new XmlQualifiedName(".choice", Namespace(o)); return NameOf(c.Items); } else if (o is XmlSchemaAny) { return new XmlQualifiedName("*", SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList)); } else if (o is XmlSchemaIdentityConstraint) { return ((XmlSchemaIdentityConstraint)o).QualifiedName; } return new XmlQualifiedName("?", Namespace(o)); } internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items) { ArrayList list = new ArrayList(); for (int i = 0; i < items.Count; i++) { list.Add(NameOf(items[i])); } list.Sort(new QNameComparer()); return (XmlQualifiedName)list[0]; } internal static string Namespace(XmlSchemaObject o) { while (o != null && !(o is XmlSchema)) { o = o.Parent; } return o == null ? "" : ((XmlSchema)o).TargetNamespace; } } internal class SchemaObjectWriter { StringBuilder w = new StringBuilder(); int indentLevel = -1; void WriteIndent() { for (int i = 0; i < indentLevel; i++) { w.Append(" "); } } protected void WriteAttribute(string localName, string ns, string value) { if (value == null || value.Length == 0) return; w.Append(","); w.Append(ns); if (ns != null && ns.Length != 0) w.Append(":"); w.Append(localName); w.Append("="); w.Append(value); } protected void WriteAttribute(string localName, string ns, XmlQualifiedName value) { if (value.IsEmpty) return; WriteAttribute(localName, ns, value.ToString()); } protected void WriteStartElement(string name) { NewLine(); indentLevel++; w.Append("["); w.Append(name); } protected void WriteEndElement() { w.Append("]"); indentLevel--; } protected void NewLine() { w.Append(Environment.NewLine); WriteIndent(); } protected string GetString() { return w.ToString(); } void WriteAttribute(XmlAttribute a) { if (a.Value != null) { WriteAttribute(a.Name, a.NamespaceURI, a.Value); } } void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o) { if (a == null) return; ArrayList attrs = new ArrayList(); for (int i = 0; i < a.Length; i++) { attrs.Add(a[i]); } attrs.Sort(new XmlAttributeComparer()); for (int i = 0; i < attrs.Count; i++) { XmlAttribute attribute = (XmlAttribute)attrs[i]; WriteAttribute(attribute); } } internal static string ToString(NamespaceList list) { if (list == null) return null; switch (list.Type) { case NamespaceList.ListType.Any: return "##any"; case NamespaceList.ListType.Other: return "##other"; case NamespaceList.ListType.Set: ArrayList ns = new ArrayList(); foreach (string s in list.Enumerate) { ns.Add(s); } ns.Sort(); StringBuilder sb = new StringBuilder(); bool first = true; foreach (string s in ns) { if (first) { first = false; } else { sb.Append(" "); } if (s.Length == 0) { sb.Append("##local"); } else { sb.Append(s); } } return sb.ToString(); default: return list.ToString(); } } internal string WriteXmlSchemaObject(XmlSchemaObject o) { if (o == null) return String.Empty; Write3_XmlSchemaObject((XmlSchemaObject)o); return GetString(); } void WriteSortedItems(XmlSchemaObjectCollection items) { if (items == null) return; ArrayList list = new ArrayList(); for (int i = 0; i < items.Count; i++) { list.Add(items[i]); } list.Sort(new XmlSchemaObjectComparer()); for (int i = 0; i < list.Count; i++) { Write3_XmlSchemaObject((XmlSchemaObject)list[i]); } } void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) { if ((object)o == null) return; WriteStartElement("attribute"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); WriteAttribute(@"default", @"", ((System.String)o.@DefaultValue)); WriteAttribute(@"fixed", @"", ((System.String)o.@FixedValue)); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) { WriteAttribute(@"form", @"", "qualified"); } else { WriteAttribute(@"form", @"", "unqualified"); } } WriteAttribute(@"name", @"", ((System.String)o.@Name)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } else if (!o.SchemaTypeName.IsEmpty) { WriteAttribute("type", "", o.SchemaTypeName); } XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use; WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@SchemaType); WriteEndElement(); } void Write3_XmlSchemaObject(XmlSchemaObject o) { if ((object)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaComplexType)) { Write35_XmlSchemaComplexType((XmlSchemaComplexType)o); return; } else if (t == typeof(XmlSchemaSimpleType)) { Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o); return; } else if (t == typeof(XmlSchemaElement)) { Write46_XmlSchemaElement((XmlSchemaElement)o); return; } else if (t == typeof(XmlSchemaAppInfo)) { Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)o); return; } else if (t == typeof(XmlSchemaDocumentation)) { Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)o); return; } else if (t == typeof(XmlSchemaAnnotation)) { Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o); return; } else if (t == typeof(XmlSchemaGroup)) { Write57_XmlSchemaGroup((XmlSchemaGroup)o); return; } else if (t == typeof(XmlSchemaXPath)) { Write49_XmlSchemaXPath("xpath", "", (XmlSchemaXPath)o); return; } else if (t == typeof(XmlSchemaIdentityConstraint)) { Write48_XmlSchemaIdentityConstraint((XmlSchemaIdentityConstraint)o); return; } else if (t == typeof(XmlSchemaUnique)) { Write51_XmlSchemaUnique((XmlSchemaUnique)o); return; } else if (t == typeof(XmlSchemaKeyref)) { Write50_XmlSchemaKeyref((XmlSchemaKeyref)o); return; } else if (t == typeof(XmlSchemaKey)) { Write47_XmlSchemaKey((XmlSchemaKey)o); return; } else if (t == typeof(XmlSchemaGroupRef)) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o); return; } else if (t == typeof(XmlSchemaAny)) { Write53_XmlSchemaAny((XmlSchemaAny)o); return; } else if (t == typeof(XmlSchemaSequence)) { Write54_XmlSchemaSequence((XmlSchemaSequence)o); return; } else if (t == typeof(XmlSchemaChoice)) { Write52_XmlSchemaChoice((XmlSchemaChoice)o); return; } else if (t == typeof(XmlSchemaAll)) { Write43_XmlSchemaAll((XmlSchemaAll)o); return; } else if (t == typeof(XmlSchemaComplexContentRestriction)) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o); return; } else if (t == typeof(XmlSchemaComplexContentExtension)) { Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o); return; } else if (t == typeof(XmlSchemaSimpleContentRestriction)) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o); return; } else if (t == typeof(XmlSchemaSimpleContentExtension)) { Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o); return; } else if (t == typeof(XmlSchemaComplexContent)) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o); return; } else if (t == typeof(XmlSchemaSimpleContent)) { Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o); return; } else if (t == typeof(XmlSchemaAnyAttribute)) { Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o); return; } else if (t == typeof(XmlSchemaAttributeGroupRef)) { Write32_XmlSchemaAttributeGroupRef((XmlSchemaAttributeGroupRef)o); return; } else if (t == typeof(XmlSchemaAttributeGroup)) { Write31_XmlSchemaAttributeGroup((XmlSchemaAttributeGroup)o); return; } else if (t == typeof(XmlSchemaSimpleTypeRestriction)) { Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o); return; } else if (t == typeof(XmlSchemaSimpleTypeList)) { Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o); return; } else if (t == typeof(XmlSchemaSimpleTypeUnion)) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o); return; } else if (t == typeof(XmlSchemaAttribute)) { Write1_XmlSchemaAttribute((XmlSchemaAttribute)o); return; } } void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation o) { if ((object)o == null) return; WriteStartElement("annotation"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); System.Xml.Schema.XmlSchemaObjectCollection a = (System.Xml.Schema.XmlSchemaObjectCollection)o.@Items; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaAppInfo) { Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)ai); } else if (ai is XmlSchemaDocumentation) { Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)ai); } } } WriteEndElement(); } void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) { if ((object)o == null) return; WriteStartElement("documentation"); WriteAttribute(@"source", @"", ((System.String)o.@Source)); WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((System.String)o.@Language)); XmlNode[] a = (XmlNode[])o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) { XmlNode ai = (XmlNode)a[ia]; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } } WriteEndElement(); } void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o) { if ((object)o == null) return; WriteStartElement("appinfo"); WriteAttribute("source", "", o.Source); XmlNode[] a = (XmlNode[])o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) { XmlNode ai = (XmlNode)a[ia]; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } } WriteEndElement(); } void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType o) { if ((object)o == null) return; WriteStartElement("simpleType"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); WriteAttribute(@"name", @"", ((System.String)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Content is XmlSchemaSimpleTypeUnion) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content); } else if (o.@Content is XmlSchemaSimpleTypeRestriction) { Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content); } else if (o.@Content is XmlSchemaSimpleTypeList) { Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content); } WriteEndElement(); } string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v) { return v.ToString(); } void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o) { if ((object)o == null) return; WriteStartElement("union"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (o.MemberTypes != null) { ArrayList list = new ArrayList(); for (int i = 0; i < o.MemberTypes.Length; i++) { list.Add(o.MemberTypes[i]); } list.Sort(new QNameComparer()); w.Append(","); w.Append("memberTypes="); for (int i = 0; i < list.Count; i++) { XmlQualifiedName q = (XmlQualifiedName)list[i]; w.Append(q.ToString()); w.Append(","); } } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.@BaseTypes); WriteEndElement(); } void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o) { if ((object)o == null) return; WriteStartElement("list"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (!o.@ItemTypeName.IsEmpty){ WriteAttribute(@"itemType", @"", o.@ItemTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@ItemType); WriteEndElement(); } void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction o) { if ((object)o == null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty){ WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); WriteFacets(o.Facets); WriteEndElement(); } void WriteFacets(XmlSchemaObjectCollection facets) { if (facets == null) return; ArrayList a = new ArrayList(); for (int i = 0; i < facets.Count; i++) { a.Add(facets[i]); } a.Sort(new XmlFacetComparer()); for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaMinExclusiveFacet) { Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxInclusiveFacet) { Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxExclusiveFacet) { Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMinInclusiveFacet) { Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaLengthFacet) { Write_XmlSchemaFacet("length", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaEnumerationFacet) { Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMinLengthFacet) { Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaPatternFacet) { Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaTotalDigitsFacet) { Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxLengthFacet) { Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaWhiteSpaceFacet) { Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaFractionDigitsFacet) { Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)ai); } } } void Write_XmlSchemaFacet(string name, XmlSchemaFacet o) { if ((object)o == null) return; WriteStartElement(name); WriteAttribute("id", "", o.Id); WriteAttribute("value", "", o.Value); if (o.IsFixed) { WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed)); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } string Write30_XmlSchemaUse(XmlSchemaUse v) { string s = null; switch (v) { case XmlSchemaUse.@Optional:s = @"optional"; break; case XmlSchemaUse.@Prohibited:s = @"prohibited"; break; case XmlSchemaUse.@Required:s = @"required"; break; default: break; } return s; } void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup o) { if ((object)o == null) return; WriteStartElement("attributeGroup"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute(@"name", @"", ((System.String)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef o) { if ((object)o == null) return; WriteStartElement("attributeGroup"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute o) { if ((object)o == null) return; WriteStartElement("anyAttribute"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute("namespace", "", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } string Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) { string s = null; switch (v) { case XmlSchemaContentProcessing.@Skip:s = @"skip"; break; case XmlSchemaContentProcessing.@Lax:s = @"lax"; break; case XmlSchemaContentProcessing.@Strict:s = @"strict"; break; default: break; } return s; } void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) { if ((object)o == null) return; WriteStartElement("complexType"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute(@"name", @"", ((System.String)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); if (((System.Boolean)o.@IsAbstract) != false) { WriteAttribute(@"abstract", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsAbstract))); } WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved)); if (((System.Boolean)o.@IsMixed) != false) { WriteAttribute(@"mixed", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsMixed))); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@ContentModel is XmlSchemaComplexContent) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel); } else if (o.@ContentModel is XmlSchemaSimpleContent) { Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o.@ContentModel); } if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent o) { if ((object)o == null) return; WriteStartElement("simpleContent"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Content is XmlSchemaSimpleContentRestriction) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content); } else if (o.@Content is XmlSchemaSimpleContentExtension) { Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o.@Content); } WriteEndElement(); } void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExtension o) { if ((object)o == null) return; WriteStartElement("extension"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty){ WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction o) { if ((object)o == null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty){ WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); WriteFacets(o.Facets); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o) { if ((object)o == null) return; WriteStartElement("complexContent"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute(@"mixed", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsMixed))); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Content is XmlSchemaComplexContentRestriction) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content); } else if (o.@Content is XmlSchemaComplexContentExtension) { Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o.@Content); } WriteEndElement(); } void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension o) { if ((object)o == null) return; WriteStartElement("extension"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty){ WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } void Write43_XmlSchemaAll(XmlSchemaAll o) { if ((object)o == null) return; WriteStartElement("all"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } void Write46_XmlSchemaElement(XmlSchemaElement o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("element"); WriteAttribute(@"id", @"", o.Id); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); if (((System.Boolean)o.@IsAbstract) != false) { WriteAttribute(@"abstract", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsAbstract))); } WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved)); WriteAttribute(@"default", @"", o.DefaultValue); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); WriteAttribute(@"fixed", @"", o.FixedValue); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) { WriteAttribute(@"form", @"", "qualified"); } else { WriteAttribute(@"form", @"", "unqualified"); } } if (o.Name != null && o.Name.Length != 0) { WriteAttribute(@"name", @"", o.Name); } if (o.IsNillable) { WriteAttribute(@"nillable", @"", XmlConvert.ToString(o.IsNillable)); } if (!o.SubstitutionGroup.IsEmpty) { WriteAttribute("substitutionGroup", "", o.SubstitutionGroup); } if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } else if (!o.SchemaTypeName.IsEmpty) { WriteAttribute("type", "", o.SchemaTypeName); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation(o.Annotation); if (o.SchemaType is XmlSchemaComplexType) { Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType); } else if (o.SchemaType is XmlSchemaSimpleType) { Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType); } WriteSortedItems(o.Constraints); WriteEndElement(); } void Write47_XmlSchemaKey(XmlSchemaKey o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("key"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute(@"name", @"", ((System.String)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); } } } WriteEndElement(); } void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o) { if ((object)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaUnique)) { Write51_XmlSchemaUnique((XmlSchemaUnique)o); return; } else if (t == typeof(XmlSchemaKeyref)) { Write50_XmlSchemaKeyref((XmlSchemaKeyref)o); return; } else if (t == typeof(XmlSchemaKey)) { Write47_XmlSchemaKey((XmlSchemaKey)o); return; } } void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath o) { if ((object)o == null) return; WriteStartElement(name); WriteAttribute(@"id", @"", o.@Id); WriteAttribute(@"xpath", @"", o.@XPath); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } void Write50_XmlSchemaKeyref(XmlSchemaKeyref o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("keyref"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute(@"name", @"", ((System.String)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); // WriteAttribute(@"refer", @"", o.@Refer); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); } } } WriteEndElement(); } void Write51_XmlSchemaUnique(XmlSchemaUnique o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("unique"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute(@"name", @"", ((System.String)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath)o.@Selector); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath("field", "", (XmlSchemaXPath)a[ia]); } } WriteEndElement(); } void Write52_XmlSchemaChoice(XmlSchemaChoice o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("choice"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } void Write53_XmlSchemaAny(XmlSchemaAny o) { if ((object)o == null) return; WriteStartElement("any"); WriteAttribute(@"id", @"", o.@Id); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttribute(@"namespace", @"", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } void Write54_XmlSchemaSequence(XmlSchemaSequence o) { if ((object)o == null) return; WriteStartElement("sequence"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaAny) { Write53_XmlSchemaAny((XmlSchemaAny)ai); } else if (ai is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)ai); } else if (ai is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)ai); } else if (ai is XmlSchemaElement) { Write46_XmlSchemaElement((XmlSchemaElement)ai); } else if (ai is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)ai); } } } WriteEndElement(); } void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o) { if ((object)o == null) return; WriteStartElement("group"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction o) { if ((object)o == null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty){ WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } void Write57_XmlSchemaGroup(XmlSchemaGroup o) { if ((object)o == null) return; WriteStartElement("group"); WriteAttribute(@"id", @"", ((System.String)o.@Id)); WriteAttribute(@"name", @"", ((System.String)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteEndElement(); } } }
// // CFDHelpers.cs // // Author: // Eddy Zavaleta <eddy@mictlanix.com> // // Copyright (C) 2012-2018 Mictlanix SAS de CV and contributors. // // 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.Linq; using Mictlanix.BE.Model; using Mictlanix.CFDv33; using Mictlanix.ProFact.Client; using Mictlanix.DFacture.Client; using System.Text; using System.Security.Cryptography.X509Certificates; namespace Mictlanix.BE.Web.Helpers { internal static class CFDHelpers { public static Comprobante IssueCFD (FiscalDocument item) { return DFactureStamp (item); } public static bool CancelCFD (FiscalDocument item) { if (item.IsCancelled) { return false; } return DFactureCancel (item); } public static Comprobante SignCFD (FiscalDocument item) { var cfd = FiscalDocumentToCFDv33 (item); var cer = item.Issuer.Certificates.Single (x => x.Id == item.IssuerCertificateNumber); cfd.Sign (cer.KeyData, cer.KeyPassword); //System.IO.File.WriteAllText (System.Web.HttpContext.Current.Server.MapPath ("~/cfd.xml"), cfd.ToXmlString ()); return cfd; } //static Comprobante ProFactStamp (FiscalDocument item) //{ // var cfd = SignCFD (item); // var cli = new ProFactClient (WebConfig.ProFactUser, WebConfig.ProFactUrl); // var id = string.Format ("{0}-{1:D6}", WebConfig.ProFactCode, item.Id); // //System.IO.File.WriteAllText ("cfd.xml", cfd.ToXmlString ()); // var tfd = cli.Stamp (id, cfd); // if (cfd.Complemento == null) { // cfd.Complemento = new List<object> (); // } // cfd.Complemento.Add (tfd); // return cfd; //} //static bool ProFactCancel (FiscalDocument item) //{ // try { // if (item.Version > 3.2m) { // var cli = new ProFactClient (WebConfig.ProFactUser, WebConfig.ProFactUrl); // return cli.Cancel (item.Issuer.Id, item.StampId); // } else { // var cli = new ProFactClient (WebConfig.ProFactUser, WebConfig.ProFactUrlV32); // return cli.CancelV32 (item.Issuer.Id, item.StampId); // } // } catch (ProFactClientException ex) { // if (ex.Code == "202") { // UUID Previamente cancelado // return true; // } // throw ex; // } //} static Comprobante DFactureStamp (FiscalDocument item) { var cfd = SignCFD (item); var cli = new DFactureClient (WebConfig.DFactureUser, WebConfig.DFacturePassword, WebConfig.DFactureUrl); //System.IO.File.WriteAllText ("cfd.xml", cfd.ToXmlString ()); var tfd = cli.Stamp (cfd); if (cfd.Complemento == null) { cfd.Complemento = new List<object> (); } cfd.Complemento.Add (tfd); return cfd; } static bool DFactureCancel (FiscalDocument item) { var cer = item.Issuer.Certificates.First (x => x.IsActive); var cli = new DFactureClient (WebConfig.DFactureUser, WebConfig.DFacturePassword, WebConfig.DFactureUrl); try { return cli.Cancel (item.Issuer.Id, item.Recipient, item.StampId, item.Total.ToString (), Convert.ToBase64String (cer.CertificateData), Convert.ToBase64String (cer.KeyData), Encoding.UTF8.GetString (cer.KeyPassword)); } catch (DFactureClientException ex) { if (ex.Code == "202") { // UUID Previamente cancelado return true; } throw ex; } } public static bool PrivateKeyTest (byte [] data, byte [] password) { return CFDLib.Utils.PrivateKeyTest (data, password); } static Comprobante FiscalDocumentToCFDv33 (FiscalDocument item) { if (item.Type == FiscalDocumentType.PaymentReceipt) { return PaymentReceiptToCFDv33 (item); } return InvoiceToCFDv33 (item); } static Comprobante PaymentReceiptToCFDv33 (FiscalDocument item) { var cer = item.Issuer.Certificates.SingleOrDefault (x => x.Id == item.IssuerCertificateNumber); var cfd = new Comprobante { Serie = item.Batch, Folio = item.Serial.ToString (), Fecha = item.Issued.GetValueOrDefault (), NoCertificado = item.IssuerCertificateNumber.PadLeft (20, '0'), Certificado = (cer == null ? null : SecurityHelpers.EncodeBase64 (cer.CertificateData)), SubTotal = 0, Moneda = "XXX", Total = 0, TipoDeComprobante = c_TipoDeComprobante.Pago, LugarExpedicion = item.IssuedLocation, Emisor = new ComprobanteEmisor { Rfc = item.Issuer.Id, Nombre = item.IssuerName, RegimenFiscal = (c_RegimenFiscal) int.Parse (item.IssuerRegime.Id), }, Receptor = new ComprobanteReceptor { Rfc = item.Recipient, Nombre = item.RecipientName, UsoCFDI = c_UsoCFDI.PorDefinir }, Conceptos = new ComprobanteConcepto [] { new ComprobanteConcepto { ClaveProdServ = "84111506", Cantidad = 1, ClaveUnidad = "ACT", Descripcion = "Pago", ValorUnitario = 0, Importe = 0 } }, Complemento = new List<object> () }; var pagos = new Pagos { Pago = new PagosPago [] { new PagosPago { FechaPago = item.PaymentDate.GetValueOrDefault (), FormaDePagoP = (c_FormaPago)(int)item.PaymentMethod, MonedaP = item.Currency.GetDisplayName (), TipoCambioP = item.ExchangeRate, TipoCambioPSpecified = item.Currency != CurrencyCode.MXN, Monto = item.PaymentAmount, NumOperacion = string.IsNullOrWhiteSpace (item.PaymentReference) ? null : item.PaymentReference, NomBancoOrdExt = string.IsNullOrWhiteSpace (item.Reference) ? null : item.Reference, DoctoRelacionado = new PagosPagoDoctoRelacionado [item.Relations.Count] } } }; int i = 0; foreach (var relation in item.Relations) { pagos.Pago [0].DoctoRelacionado [i++] = new PagosPagoDoctoRelacionado { IdDocumento = relation.Relation.StampId, Serie = relation.Relation.Batch, Folio = relation.Relation.Serial.ToString (), MonedaDR = relation.Relation.Currency.GetDisplayName (), TipoCambioDR = relation.ExchangeRate, TipoCambioDRSpecified = relation.Relation.Currency != item.Currency, MetodoDePagoDR = c_MetodoPago.PagoEnParcialidadesODiferido, NumParcialidad = relation.Installment.ToString (), ImpSaldoAnt = relation.PreviousBalance, ImpSaldoAntSpecified = true, ImpPagado = relation.Amount, ImpPagadoSpecified = true, ImpSaldoInsoluto = relation.OutstandingBalance, ImpSaldoInsolutoSpecified = true }; } cfd.Complemento.Add (pagos); return cfd; } static Comprobante InvoiceToCFDv33 (FiscalDocument item) { var cer = item.Issuer.Certificates.SingleOrDefault (x => x.Id == item.IssuerCertificateNumber); var cfd = new Comprobante { TipoDeComprobante = (c_TipoDeComprobante) FDT2TDC (item.Type), NoCertificado = item.IssuerCertificateNumber.PadLeft (20, '0'), Serie = item.Batch, Folio = item.Serial.ToString (), Fecha = item.Issued.GetValueOrDefault (), MetodoPago = item.Terms == PaymentTerms.Immediate ? c_MetodoPago.PagoEnUnaSolaExhibicion : c_MetodoPago.PagoEnParcialidadesODiferido, MetodoPagoSpecified = true, FormaPago = (c_FormaPago) (int) item.PaymentMethod, FormaPagoSpecified = true, LugarExpedicion = item.IssuedLocation, SubTotal = item.Subtotal, Total = item.Total, Moneda = item.Currency.GetDisplayName (), TipoCambio = item.ExchangeRate, TipoCambioSpecified = item.Currency != CurrencyCode.MXN, Sello = item.IssuerDigitalSeal, Certificado = (cer == null ? null : SecurityHelpers.EncodeBase64 (cer.CertificateData)), Emisor = new ComprobanteEmisor { Rfc = item.Issuer.Id, Nombre = item.IssuerName, RegimenFiscal = (c_RegimenFiscal) int.Parse (item.IssuerRegime.Id), }, Receptor = new ComprobanteReceptor { Rfc = item.Recipient, Nombre = item.RecipientName, UsoCFDI = CfdiUsage2UsoCFDI (item.Usage.Id) }, Conceptos = new ComprobanteConcepto [item.Details.Count] }; int i = 0; foreach (var detail in item.Details) { cfd.Conceptos [i] = new ComprobanteConcepto { Cantidad = detail.Quantity, ClaveUnidad = detail.UnitOfMeasurement.Id, Unidad = detail.UnitOfMeasurementName, NoIdentificacion = detail.ProductCode, ClaveProdServ = detail.ProductService.Id, Descripcion = detail.ProductName, ValorUnitario = detail.NetPrice, Importe = detail.Subtotal, Descuento = detail.Discount, DescuentoSpecified = detail.Discount > 0m }; //cfd.Conceptos [i].InformacionAduanera = new ComprobanteConceptoInformacionAduanera [] { // new ComprobanteConceptoInformacionAduanera { // NumeroPedimento = "" // } //}; if (detail.Subtotal == detail.Discount) { i++; continue; } if (detail.TaxRate >= 0m) { cfd.Conceptos [i].Impuestos = new ComprobanteConceptoImpuestos { Traslados = new ComprobanteConceptoImpuestosTraslado [] { new ComprobanteConceptoImpuestosTraslado { Impuesto = c_Impuesto.IVA, TipoFactor = c_TipoFactor.Tasa, Base = detail.TaxBase, Importe = detail.Taxes, ImporteSpecified = true, TasaOCuota = detail.TaxRate, TasaOCuotaSpecified = true } }, Retenciones = item.RetentionRate <= 0m ? null : new ComprobanteConceptoImpuestosRetencion [] { new ComprobanteConceptoImpuestosRetencion { Impuesto = c_Impuesto.IVA, TipoFactor = c_TipoFactor.Tasa, Base = detail.TaxBase, Importe = detail.RetentionTaxes, TasaOCuota = item.RetentionRate } } }; } else { cfd.Conceptos [i].Impuestos = new ComprobanteConceptoImpuestos { Traslados = new ComprobanteConceptoImpuestosTraslado [] { new ComprobanteConceptoImpuestosTraslado { Impuesto = c_Impuesto.IVA, TipoFactor = c_TipoFactor.Exento, Base = detail.TaxBase } } }; } i++; } if (item.Discount > 0) { cfd.Descuento = item.Discount; cfd.DescuentoSpecified = true; } cfd.Impuestos = new ComprobanteImpuestos (); var taxes = new List<ComprobanteImpuestosTraslado> (); if (cfd.Conceptos.Any (c => c.Impuestos != null && c.Impuestos.Traslados.Any (x => x.TasaOCuota == decimal.Zero))) { taxes.Add (new ComprobanteImpuestosTraslado { Impuesto = c_Impuesto.IVA, TipoFactor = c_TipoFactor.Tasa, TasaOCuota = 0.000000m, Importe = 0.00m }); } if (cfd.Conceptos.Any (c => c.Impuestos != null && c.Impuestos.Traslados.Any (x => x.TasaOCuota == WebConfig.DefaultVAT))) { taxes.Add (new ComprobanteImpuestosTraslado { Impuesto = c_Impuesto.IVA, TipoFactor = c_TipoFactor.Tasa, TasaOCuota = WebConfig.DefaultVAT, Importe = cfd.Conceptos.Where (x => x.Impuestos != null).Sum (c => c.Impuestos.Traslados.Where (x => x.TasaOCuota == WebConfig.DefaultVAT).Sum (x => x.Importe)) }); } cfd.Impuestos.Traslados = taxes.ToArray (); cfd.Impuestos.TotalImpuestosTrasladados = cfd.Impuestos.Traslados.Sum (x => x.Importe); cfd.Impuestos.TotalImpuestosTrasladadosSpecified = true; if (item.RetentionRate > 0m) { cfd.Impuestos.Retenciones = new ComprobanteImpuestosRetencion [] { new ComprobanteImpuestosRetencion { Impuesto = c_Impuesto.IVA, Importe = item.RetentionTaxes, } }; cfd.Impuestos.TotalImpuestosRetenidos = cfd.Impuestos.Retenciones.Sum (x => x.Importe); cfd.Impuestos.TotalImpuestosRetenidosSpecified = true; } if (item.LocalRetentionRate > 0m) { var implocal = new ImpuestosLocalesRetencionesLocales { ImpLocRetenido = item.LocalRetentionName, Importe = item.LocalRetentionTaxes, TasadeRetencion = Math.Round (item.LocalRetentionRate * 100m, 2) }; if (cfd.Complemento == null) { cfd.Complemento = new List<object> (); } cfd.Complemento.Add (new ImpuestosLocales { TotaldeRetenciones = 76.50m, RetencionesLocales = new ImpuestosLocalesRetencionesLocales [] { implocal } }); } if (item.Relations.Any ()) { var rels = new ComprobanteCfdiRelacionados { CfdiRelacionado = new ComprobanteCfdiRelacionadosCfdiRelacionado [item.Relations.Count] }; if (item.Type == FiscalDocumentType.AdvancePaymentsApplied) { rels.TipoRelacion = c_TipoRelacion.AplicacionDeAnticipo; } else if (item.Type == FiscalDocumentType.CreditNote) { rels.TipoRelacion = c_TipoRelacion.NotaDeCredito; } else { rels.TipoRelacion = c_TipoRelacion.Sustitucion; } i = 0; foreach (var relation in item.Relations) { rels.CfdiRelacionado [i++] = new ComprobanteCfdiRelacionadosCfdiRelacionado { UUID = relation.Relation.StampId }; } cfd.CfdiRelacionados = rels; } return cfd; } // FiscalDocumentType -> TipoDeComprobante static int FDT2TDC (FiscalDocumentType type) { switch (type) { case FiscalDocumentType.Invoice: case FiscalDocumentType.FeeReceipt: case FiscalDocumentType.RentReceipt: case FiscalDocumentType.DebitNote: return (int) c_TipoDeComprobante.Ingreso; case FiscalDocumentType.CreditNote: case FiscalDocumentType.AdvancePaymentsApplied: return (int) c_TipoDeComprobante.Egreso; case FiscalDocumentType.PaymentReceipt: return (int) c_TipoDeComprobante.Pago; } throw new ArgumentOutOfRangeException (nameof (type)); } // FiscalDocumentType -> TipoDeComprobante static c_UsoCFDI CfdiUsage2UsoCFDI (string code) { switch (code) { case "G01": return c_UsoCFDI.AdquisicionDeMercancias; case "G02": return c_UsoCFDI.DevolucionesDescuentosOBonificaciones; case "G03": return c_UsoCFDI.GastosEnGeneral; case "I01": return c_UsoCFDI.Construcciones; case "I02": return c_UsoCFDI.MobilarioYEquipoDeOficinaPorInversiones; case "I03": return c_UsoCFDI.EquipoDeTransporte; case "I04": return c_UsoCFDI.EquipoDeComputoYAccesorios; case "I05": return c_UsoCFDI.DadosTroquelesMoldesMatricesYHerramental; case "I06": return c_UsoCFDI.ComunicacionesTelefonicas; case "I07": return c_UsoCFDI.ComunicacionesSatelitales; case "I08": return c_UsoCFDI.OtraMaquinariaYEquipo; case "D01": return c_UsoCFDI.HonorariosMedicosDentalesYGastosHospitalarios; case "D02": return c_UsoCFDI.GastosMedicosPorIncapacidadODiscapacidad; case "D03": return c_UsoCFDI.GastosFunerales; case "D04": return c_UsoCFDI.Donativos; case "D05": return c_UsoCFDI.InteresesRealesEfectivamentePagadosPorCreditosHipotecarios; case "D06": return c_UsoCFDI.AportacionesVoluntariasAlSAR; case "D07": return c_UsoCFDI.PrimasPorSegurosDeGastosMedicos; case "D08": return c_UsoCFDI.GastosDeTransportacionEscolarObligatoria; case "D09": return c_UsoCFDI.DepositosEnCuentasParaElAhorroPrimasQueTenganComoBasePlanesDePensiones; case "D10": return c_UsoCFDI.PagosPorServiciosEducativos; case "P01": return c_UsoCFDI.PorDefinir; } throw new ArgumentOutOfRangeException (nameof (code)); } } }
/* Copyright (c) 2019 Denis Zykov, GameDevWare.com This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. This source code is distributed via Unity Asset Store, to use it in your project you should accept Terms of Service and EULA https://unity3d.com/ru/legal/as_terms */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; // ReSharper disable once CheckNamespace namespace GameDevWare.Serialization { public static class JsonReaderExtentions { public static void ReadArrayBegin(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.Token != JsonToken.BeginArray) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.BeginArray); if (reader.IsEndOfStream()) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.EndOfArray); if (nextToken) reader.NextToken(); } public static void ReadArrayEnd(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.Token != JsonToken.EndOfArray) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.EndOfArray); if (nextToken) reader.NextToken(); } public static void ReadObjectBegin(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.Token != JsonToken.BeginObject) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.BeginObject); if (reader.IsEndOfStream()) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.EndOfObject); if (nextToken) reader.NextToken(); } public static void ReadObjectEnd(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.Token != JsonToken.EndOfObject) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.EndOfObject); if (nextToken) reader.NextToken(); } public static string ReadMember(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.Token != JsonToken.Member) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Member); var memberName = (string)reader.RawValue; if (nextToken) reader.NextToken(); return memberName; } public static byte ReadByte(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(byte); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsByte; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static byte? ReadByteOrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(byte?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsByte; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static sbyte ReadSByte(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(sbyte); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsSByte; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static sbyte? ReadSByteOrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(sbyte?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsSByte; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static short ReadInt16(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(short); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsInt16; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static short? ReadInt16OrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(short?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsInt16; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static int ReadInt32(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(int); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsInt32; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static int? ReadInt32OrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(int?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsInt32; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static long ReadInt64(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(long); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsInt64; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static long? ReadInt64OrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(long?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsInt64; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static ushort ReadUInt16(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(ushort); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsUInt16; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static ushort? ReadUInt16OrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(ushort?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsUInt16; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static uint ReadUInt32(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(uint); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsUInt32; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static uint? ReadUInt32OrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(uint?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsUInt32; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static ulong ReadUInt64(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(ulong); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsUInt64; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static ulong? ReadUInt64OrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(ulong?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsUInt64; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static float ReadSingle(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(float); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsSingle; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static float? ReadSingleOrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(float?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsSingle; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static double ReadDouble(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(double); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsDouble; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static double? ReadDoubleOrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(double?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsDouble; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static decimal ReadDecimal(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(decimal); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number) value = reader.Value.AsDecimal; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); if (nextToken) reader.NextToken(); return value; } public static decimal? ReadDecimalOrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(decimal?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: value = reader.Value.AsDecimal; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number); } if (nextToken) reader.NextToken(); return value; } public static bool ReadBoolean(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(bool); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Boolean) value = reader.Value.AsBoolean; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Boolean); if (nextToken) reader.NextToken(); return value; } public static bool? ReadBooleanOrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(bool?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Boolean: value = reader.Value.AsBoolean; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Boolean); } if (nextToken) reader.NextToken(); return value; } public static DateTime ReadDateTime(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(DateTime); if (reader.Token == JsonToken.Member || reader.Token == JsonToken.StringLiteral || reader.Token == JsonToken.Number || reader.Token == JsonToken.DateTime) value = reader.Value.AsDateTime; else throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number, JsonToken.DateTime); if (nextToken) reader.NextToken(); return value; } public static DateTime? ReadDateTimeOrNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var value = default(DateTime?); switch (reader.Token) { case JsonToken.Null: value = null; break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: case JsonToken.DateTime: value = reader.Value.AsDateTime; break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number, JsonToken.DateTime); } if (nextToken) reader.NextToken(); return value; } public static string ReadString(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); var stringValue = default(string); switch (reader.Token) { case JsonToken.Null: break; case JsonToken.Member: case JsonToken.StringLiteral: case JsonToken.Number: case JsonToken.DateTime: case JsonToken.Boolean: stringValue = Convert.ToString(reader.RawValue, reader.Context.Format); break; default: throw JsonSerializationException.UnexpectedToken(reader, JsonToken.StringLiteral, JsonToken.Number, JsonToken.DateTime, JsonToken.Boolean); } if (nextToken) reader.NextToken(); return stringValue; } public static void ReadNull(this IJsonReader reader, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.Token != JsonToken.Null) throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Null); if (nextToken) reader.NextToken(); } public static object ReadValue(this IJsonReader reader, Type valueType, bool nextToken = true) { if (reader == null) throw new ArgumentNullException("reader"); // try guess type if (valueType == typeof(object)) valueType = reader.Value.Type; var value = default(object); var isNullable = valueType.IsValueType == false || valueType.IsInstantiationOf(typeof(Nullable<>)); if (reader.Token == JsonToken.Null && isNullable) { value = null; } else { if (isNullable && valueType.IsValueType) valueType = valueType.GetGenericArguments()[0]; // get subtype of Nullable<T> var serializer = reader.Context.GetSerializerForType(valueType); value = serializer.Deserialize(reader); } if (nextToken) reader.NextToken(); return value; } public static string DebugPrintTokens(this IJsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); var output = new StringBuilder(); var stack = new Stack<JsonToken>(); stack.Push(JsonToken.None); while (reader.NextToken()) { var strValue = reader.Token + (reader.Value.HasValue && reader.Value != null ? "[<" + reader.Value.Type.Name + "> " + JsonUtils.EscapeAndQuote(reader.Value.AsString).Trim('"') + "]" : ""); if (stack.Peek() != JsonToken.Member) { var endingTokenIndent = (reader.Token == JsonToken.EndOfObject || reader.Token == JsonToken.EndOfArray ? -1 : 0); output.Append(Environment.NewLine); for (var i = 0; i < System.Linq.Enumerable.Count(stack, t => t != JsonToken.Member && t != JsonToken.None) + endingTokenIndent; i++) output.Append("\t"); } else { output.Append(" "); } output.Append(strValue); if (reader.Token == JsonToken.EndOfObject || reader.Token == JsonToken.EndOfArray || stack.Peek() == JsonToken.Member) stack.Pop(); if (reader.Token == JsonToken.BeginObject || reader.Token == JsonToken.BeginArray || reader.Token == JsonToken.Member) stack.Push(reader.Token); } return output.ToString(); } } }
/* * Copyright (c) 2006-2014, 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.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; namespace OpenMetaverse { /// <summary> /// Exception class to identify inventory exceptions /// </summary> public class InventoryException : Exception { public InventoryException(string message) : base(message) { } } /// <summary> /// Responsible for maintaining inventory structure. Inventory constructs nodes /// and manages node children as is necessary to maintain a coherant hirarchy. /// Other classes should not manipulate or create InventoryNodes explicitly. When /// A node's parent changes (when a folder is moved, for example) simply pass /// Inventory the updated InventoryFolder and it will make the appropriate changes /// to its internal representation. /// </summary> public class Inventory { /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<InventoryObjectUpdatedEventArgs> m_InventoryObjectUpdated; ///<summary>Raises the InventoryObjectUpdated Event</summary> /// <param name="e">A InventoryObjectUpdatedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnInventoryObjectUpdated(InventoryObjectUpdatedEventArgs e) { EventHandler<InventoryObjectUpdatedEventArgs> handler = m_InventoryObjectUpdated; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_InventoryObjectUpdatedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<InventoryObjectUpdatedEventArgs> InventoryObjectUpdated { add { lock (m_InventoryObjectUpdatedLock) { m_InventoryObjectUpdated += value; } } remove { lock (m_InventoryObjectUpdatedLock) { m_InventoryObjectUpdated -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<InventoryObjectRemovedEventArgs> m_InventoryObjectRemoved; ///<summary>Raises the InventoryObjectRemoved Event</summary> /// <param name="e">A InventoryObjectRemovedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnInventoryObjectRemoved(InventoryObjectRemovedEventArgs e) { EventHandler<InventoryObjectRemovedEventArgs> handler = m_InventoryObjectRemoved; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_InventoryObjectRemovedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<InventoryObjectRemovedEventArgs> InventoryObjectRemoved { add { lock (m_InventoryObjectRemovedLock) { m_InventoryObjectRemoved += value; } } remove { lock (m_InventoryObjectRemovedLock) { m_InventoryObjectRemoved -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<InventoryObjectAddedEventArgs> m_InventoryObjectAdded; ///<summary>Raises the InventoryObjectAdded Event</summary> /// <param name="e">A InventoryObjectAddedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnInventoryObjectAdded(InventoryObjectAddedEventArgs e) { EventHandler<InventoryObjectAddedEventArgs> handler = m_InventoryObjectAdded; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_InventoryObjectAddedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<InventoryObjectAddedEventArgs> InventoryObjectAdded { add { lock (m_InventoryObjectAddedLock) { m_InventoryObjectAdded += value; } } remove { lock (m_InventoryObjectAddedLock) { m_InventoryObjectAdded -= value; } } } /// <summary> /// The root folder of this avatars inventory /// </summary> public InventoryFolder RootFolder { get { return RootNode.Data as InventoryFolder; } set { UpdateNodeFor(value); _RootNode = Items[value.UUID]; } } /// <summary> /// The default shared library folder /// </summary> public InventoryFolder LibraryFolder { get { return LibraryRootNode.Data as InventoryFolder; } set { UpdateNodeFor(value); _LibraryRootNode = Items[value.UUID]; } } private InventoryNode _LibraryRootNode; private InventoryNode _RootNode; /// <summary> /// The root node of the avatars inventory /// </summary> public InventoryNode RootNode { get { return _RootNode; } } /// <summary> /// The root node of the default shared library /// </summary> public InventoryNode LibraryRootNode { get { return _LibraryRootNode; } } public UUID Owner { get { return _Owner; } } private UUID _Owner; private GridClient Client; //private InventoryManager Manager; public Dictionary<UUID, InventoryNode> Items = new Dictionary<UUID, InventoryNode>(); public Inventory(GridClient client, InventoryManager manager) : this(client, manager, client.Self.AgentID) { } public Inventory(GridClient client, InventoryManager manager, UUID owner) { Client = client; //Manager = manager; _Owner = owner; if (owner == UUID.Zero) Logger.Log("Inventory owned by nobody!", Helpers.LogLevel.Warning, Client); Items = new Dictionary<UUID, InventoryNode>(); } public List<InventoryBase> GetContents(InventoryFolder folder) { return GetContents(folder.UUID); } /// <summary> /// Returns the contents of the specified folder /// </summary> /// <param name="folder">A folder's UUID</param> /// <returns>The contents of the folder corresponding to <code>folder</code></returns> /// <exception cref="InventoryException">When <code>folder</code> does not exist in the inventory</exception> public List<InventoryBase> GetContents(UUID folder) { InventoryNode folderNode; if (!Items.TryGetValue(folder, out folderNode)) throw new InventoryException("Unknown folder: " + folder); lock (folderNode.Nodes.SyncRoot) { List<InventoryBase> contents = new List<InventoryBase>(folderNode.Nodes.Count); foreach (InventoryNode node in folderNode.Nodes.Values) { contents.Add(node.Data); } return contents; } } /// <summary> /// Updates the state of the InventoryNode and inventory data structure that /// is responsible for the InventoryObject. If the item was previously not added to inventory, /// it adds the item, and updates structure accordingly. If it was, it updates the /// InventoryNode, changing the parent node if <code>item.parentUUID</code> does /// not match <code>node.Parent.Data.UUID</code>. /// /// You can not set the inventory root folder using this method /// </summary> /// <param name="item">The InventoryObject to store</param> public void UpdateNodeFor(InventoryBase item) { lock (Items) { InventoryNode itemParent = null; if (item.ParentUUID != UUID.Zero && !Items.TryGetValue(item.ParentUUID, out itemParent)) { // OK, we have no data on the parent, let's create a fake one. InventoryFolder fakeParent = new InventoryFolder(item.ParentUUID); fakeParent.DescendentCount = 1; // Dear god, please forgive me. itemParent = new InventoryNode(fakeParent); Items[item.ParentUUID] = itemParent; // Unfortunately, this breaks the nice unified tree // while we're waiting for the parent's data to come in. // As soon as we get the parent, the tree repairs itself. //Logger.DebugLog("Attempting to update inventory child of " + // item.ParentUUID.ToString() + " when we have no local reference to that folder", Client); if (Client.Settings.FETCH_MISSING_INVENTORY) { // Fetch the parent List<UUID> fetchreq = new List<UUID>(1); fetchreq.Add(item.ParentUUID); } } InventoryNode itemNode; if (Items.TryGetValue(item.UUID, out itemNode)) // We're updating. { InventoryNode oldParent = itemNode.Parent; // Handle parent change if (oldParent == null || itemParent == null || itemParent.Data.UUID != oldParent.Data.UUID) { if (oldParent != null) { lock (oldParent.Nodes.SyncRoot) oldParent.Nodes.Remove(item.UUID); } if (itemParent != null) { lock (itemParent.Nodes.SyncRoot) itemParent.Nodes[item.UUID] = itemNode; } } itemNode.Parent = itemParent; if (m_InventoryObjectUpdated != null) { OnInventoryObjectUpdated(new InventoryObjectUpdatedEventArgs(itemNode.Data, item)); } itemNode.Data = item; } else // We're adding. { itemNode = new InventoryNode(item, itemParent); Items.Add(item.UUID, itemNode); if (m_InventoryObjectAdded != null) { OnInventoryObjectAdded(new InventoryObjectAddedEventArgs(item)); } } } } public InventoryNode GetNodeFor(UUID uuid) { return Items[uuid]; } /// <summary> /// Removes the InventoryObject and all related node data from Inventory. /// </summary> /// <param name="item">The InventoryObject to remove.</param> public void RemoveNodeFor(InventoryBase item) { lock (Items) { InventoryNode node; if (Items.TryGetValue(item.UUID, out node)) { if (node.Parent != null) lock (node.Parent.Nodes.SyncRoot) node.Parent.Nodes.Remove(item.UUID); Items.Remove(item.UUID); if (m_InventoryObjectRemoved != null) { OnInventoryObjectRemoved(new InventoryObjectRemovedEventArgs(item)); } } // In case there's a new parent: InventoryNode newParent; if (Items.TryGetValue(item.ParentUUID, out newParent)) { lock (newParent.Nodes.SyncRoot) newParent.Nodes.Remove(item.UUID); } } } /// <summary> /// Used to find out if Inventory contains the InventoryObject /// specified by <code>uuid</code>. /// </summary> /// <param name="uuid">The UUID to check.</param> /// <returns>true if inventory contains uuid, false otherwise</returns> public bool Contains(UUID uuid) { return Items.ContainsKey(uuid); } public bool Contains(InventoryBase obj) { return Contains(obj.UUID); } /// <summary> /// Saves the current inventory structure to a cache file /// </summary> /// <param name="filename">Name of the cache file to save to</param> public void SaveToDisk(string filename) { try { using (Stream stream = File.Open(filename, FileMode.Create)) { BinaryFormatter bformatter = new BinaryFormatter(); lock (Items) { Logger.Log("Caching " + Items.Count.ToString() + " inventory items to " + filename, Helpers.LogLevel.Info); foreach (KeyValuePair<UUID, InventoryNode> kvp in Items) { bformatter.Serialize(stream, kvp.Value); } } } } catch (Exception e) { Logger.Log("Error saving inventory cache to disk :"+e.Message,Helpers.LogLevel.Error); } } /// <summary> /// Loads in inventory cache file into the inventory structure. Note only valid to call after login has been successful. /// </summary> /// <param name="filename">Name of the cache file to load</param> /// <returns>The number of inventory items sucessfully reconstructed into the inventory node tree</returns> public int RestoreFromDisk(string filename) { List<InventoryNode> nodes = new List<InventoryNode>(); int item_count = 0; try { if (!File.Exists(filename)) return -1; using (Stream stream = File.Open(filename, FileMode.Open)) { BinaryFormatter bformatter = new BinaryFormatter(); while (stream.Position < stream.Length) { OpenMetaverse.InventoryNode node = (InventoryNode)bformatter.Deserialize(stream); nodes.Add(node); item_count++; } } } catch (Exception e) { Logger.Log("Error accessing inventory cache file :" + e.Message, Helpers.LogLevel.Error); return -1; } Logger.Log("Read " + item_count.ToString() + " items from inventory cache file", Helpers.LogLevel.Info); item_count = 0; List<InventoryNode> del_nodes = new List<InventoryNode>(); //nodes that we have processed and will delete List<UUID> dirty_folders = new List<UUID>(); // Tainted folders that we will not restore items into // Because we could get child nodes before parents we must itterate around and only add nodes who have // a parent already in the list because we must update both child and parent to link together // But sometimes we have seen orphin nodes due to bad/incomplete data when caching so we have an emergency abort route int stuck = 0; while (nodes.Count != 0 && stuck<5) { foreach (InventoryNode node in nodes) { InventoryNode pnode; if (node.ParentID == UUID.Zero) { //We don't need the root nodes "My Inventory" etc as they will already exist for the correct // user of this cache. del_nodes.Add(node); item_count--; } else if(Items.TryGetValue(node.Data.UUID,out pnode)) { //We already have this it must be a folder if (node.Data is InventoryFolder) { InventoryFolder cache_folder = (InventoryFolder)node.Data; InventoryFolder server_folder = (InventoryFolder)pnode.Data; if (cache_folder.Version != server_folder.Version) { Logger.DebugLog("Inventory Cache/Server version mismatch on " + node.Data.Name + " " + cache_folder.Version.ToString() + " vs " + server_folder.Version.ToString()); pnode.NeedsUpdate = true; dirty_folders.Add(node.Data.UUID); } else { pnode.NeedsUpdate = false; } del_nodes.Add(node); } } else if (Items.TryGetValue(node.ParentID, out pnode)) { if (node.Data != null) { // If node is folder, and it does not exist in skeleton, mark it as // dirty and don't process nodes that belong to it if (node.Data is InventoryFolder && !(Items.ContainsKey(node.Data.UUID))) { dirty_folders.Add(node.Data.UUID); } //Only add new items, this is most likely to be run at login time before any inventory //nodes other than the root are populated. Don't add non existing folders. if (!Items.ContainsKey(node.Data.UUID) && !dirty_folders.Contains(pnode.Data.UUID) && !(node.Data is InventoryFolder)) { Items.Add(node.Data.UUID, node); node.Parent = pnode; //Update this node with its parent pnode.Nodes.Add(node.Data.UUID, node); // Add to the parents child list item_count++; } } del_nodes.Add(node); } } if (del_nodes.Count == 0) stuck++; else stuck = 0; //Clean up processed nodes this loop around. foreach (InventoryNode node in del_nodes) nodes.Remove(node); del_nodes.Clear(); } Logger.Log("Reassembled " + item_count.ToString() + " items from inventory cache file", Helpers.LogLevel.Info); return item_count; } #region Operators /// <summary> /// By using the bracket operator on this class, the program can get the /// InventoryObject designated by the specified uuid. If the value for the corresponding /// UUID is null, the call is equivelant to a call to <code>RemoveNodeFor(this[uuid])</code>. /// If the value is non-null, it is equivelant to a call to <code>UpdateNodeFor(value)</code>, /// the uuid parameter is ignored. /// </summary> /// <param name="uuid">The UUID of the InventoryObject to get or set, ignored if set to non-null value.</param> /// <returns>The InventoryObject corresponding to <code>uuid</code>.</returns> public InventoryBase this[UUID uuid] { get { InventoryNode node = Items[uuid]; return node.Data; } set { if (value != null) { // Log a warning if there is a UUID mismatch, this will cause problems if (value.UUID != uuid) Logger.Log("Inventory[uuid]: uuid " + uuid.ToString() + " is not equal to value.UUID " + value.UUID.ToString(), Helpers.LogLevel.Warning, Client); UpdateNodeFor(value); } else { InventoryNode node; if (Items.TryGetValue(uuid, out node)) { RemoveNodeFor(node.Data); } } } } #endregion Operators } #region EventArgs classes public class InventoryObjectUpdatedEventArgs : EventArgs { private readonly InventoryBase m_OldObject; private readonly InventoryBase m_NewObject; public InventoryBase OldObject { get { return m_OldObject; } } public InventoryBase NewObject { get { return m_NewObject; } } public InventoryObjectUpdatedEventArgs(InventoryBase oldObject, InventoryBase newObject) { this.m_OldObject = oldObject; this.m_NewObject = newObject; } } public class InventoryObjectRemovedEventArgs : EventArgs { private readonly InventoryBase m_Obj; public InventoryBase Obj { get { return m_Obj; } } public InventoryObjectRemovedEventArgs(InventoryBase obj) { this.m_Obj = obj; } } public class InventoryObjectAddedEventArgs : EventArgs { private readonly InventoryBase m_Obj; public InventoryBase Obj { get { return m_Obj; } } public InventoryObjectAddedEventArgs(InventoryBase obj) { this.m_Obj = obj; } } #endregion EventArgs }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using JsonApiDotNetCore.AtomicOperations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Errors; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Resources; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Logging; namespace JsonApiDotNetCore.Controllers { /// <summary> /// Implements the foundational ASP.NET Core controller layer in the JsonApiDotNetCore architecture for handling atomic:operations requests. See /// https://jsonapi.org/ext/atomic/ for details. Delegates work to <see cref="IOperationsProcessor" />. /// </summary> [PublicAPI] public abstract class BaseJsonApiOperationsController : CoreJsonApiController { private readonly IJsonApiOptions _options; private readonly IOperationsProcessor _processor; private readonly IJsonApiRequest _request; private readonly ITargetedFields _targetedFields; private readonly TraceLogWriter<BaseJsonApiOperationsController> _traceWriter; protected BaseJsonApiOperationsController(IJsonApiOptions options, ILoggerFactory loggerFactory, IOperationsProcessor processor, IJsonApiRequest request, ITargetedFields targetedFields) { ArgumentGuard.NotNull(options, nameof(options)); ArgumentGuard.NotNull(loggerFactory, nameof(loggerFactory)); ArgumentGuard.NotNull(processor, nameof(processor)); ArgumentGuard.NotNull(request, nameof(request)); ArgumentGuard.NotNull(targetedFields, nameof(targetedFields)); _options = options; _processor = processor; _request = request; _targetedFields = targetedFields; _traceWriter = new TraceLogWriter<BaseJsonApiOperationsController>(loggerFactory); } /// <summary> /// Atomically processes a list of operations and returns a list of results. All changes are reverted if processing fails. If processing succeeds but /// none of the operations returns any data, then HTTP 201 is returned instead of 200. /// </summary> /// <example> /// The next example creates a new resource. /// <code><![CDATA[ /// POST /operations HTTP/1.1 /// Content-Type: application/vnd.api+json;ext="https://jsonapi.org/ext/atomic" /// /// { /// "atomic:operations": [{ /// "op": "add", /// "data": { /// "type": "authors", /// "attributes": { /// "name": "John Doe" /// } /// } /// }] /// } /// ]]></code> /// </example> /// <example> /// The next example updates an existing resource. /// <code><![CDATA[ /// POST /operations HTTP/1.1 /// Content-Type: application/vnd.api+json;ext="https://jsonapi.org/ext/atomic" /// /// { /// "atomic:operations": [{ /// "op": "update", /// "data": { /// "type": "authors", /// "id": 1, /// "attributes": { /// "name": "Jane Doe" /// } /// } /// }] /// } /// ]]></code> /// </example> /// <example> /// The next example deletes an existing resource. /// <code><![CDATA[ /// POST /operations HTTP/1.1 /// Content-Type: application/vnd.api+json;ext="https://jsonapi.org/ext/atomic" /// /// { /// "atomic:operations": [{ /// "op": "remove", /// "ref": { /// "type": "authors", /// "id": 1 /// } /// }] /// } /// ]]></code> /// </example> public virtual async Task<IActionResult> PostOperationsAsync([FromBody] IList<OperationContainer> operations, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { operations }); ArgumentGuard.NotNull(operations, nameof(operations)); ValidateClientGeneratedIds(operations); if (_options.ValidateModelState) { ValidateModelState(operations); } IList<OperationContainer> results = await _processor.ProcessAsync(operations, cancellationToken); return results.Any(result => result != null) ? Ok(results) : NoContent(); } protected virtual void ValidateClientGeneratedIds(IEnumerable<OperationContainer> operations) { if (!_options.AllowClientGeneratedIds) { int index = 0; foreach (OperationContainer operation in operations) { if (operation.Kind == WriteOperationKind.CreateResource && operation.Resource.StringId != null) { throw new ResourceIdInCreateResourceNotAllowedException(index); } index++; } } } protected virtual void ValidateModelState(IEnumerable<OperationContainer> operations) { // We must validate the resource inside each operation manually, because they are typed as IIdentifiable. // Instead of validating IIdentifiable we need to validate the resource runtime-type. var violations = new List<ModelStateViolation>(); int index = 0; foreach (OperationContainer operation in operations) { if (operation.Kind == WriteOperationKind.CreateResource || operation.Kind == WriteOperationKind.UpdateResource) { _targetedFields.Attributes = operation.TargetedFields.Attributes; _targetedFields.Relationships = operation.TargetedFields.Relationships; _request.CopyFrom(operation.Request); var validationContext = new ActionContext(); ObjectValidator.Validate(validationContext, null, string.Empty, operation.Resource); if (!validationContext.ModelState.IsValid) { AddValidationErrors(validationContext.ModelState, operation.Resource.GetType(), index, violations); } } index++; } if (violations.Any()) { throw new InvalidModelStateException(violations, _options.IncludeExceptionStackTraceInErrors, _options.SerializerOptions.PropertyNamingPolicy); } } private static void AddValidationErrors(ModelStateDictionary modelState, Type resourceType, int operationIndex, List<ModelStateViolation> violations) { foreach ((string propertyName, ModelStateEntry entry) in modelState) { AddValidationErrors(entry, propertyName, resourceType, operationIndex, violations); } } private static void AddValidationErrors(ModelStateEntry entry, string propertyName, Type resourceType, int operationIndex, List<ModelStateViolation> violations) { foreach (ModelError error in entry.Errors) { string prefix = $"/atomic:operations[{operationIndex}]/data/attributes/"; var violation = new ModelStateViolation(prefix, propertyName, resourceType, error); violations.Add(violation); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: Version ** ** ** Purpose: ** ** ===========================================================*/ namespace System { using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; using NumberStyles = System.Globalization.NumberStyles; // A Version object contains four hierarchical numeric components: major, minor, // build and revision. Build and revision may be unspecified, which is represented // internally as a -1. By definition, an unspecified component matches anything // (both unspecified and specified), and an unspecified component is "less than" any // specified component. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class Version : ICloneable, IComparable #if GENERICS_WORK , IComparable<Version>, IEquatable<Version> #endif { // AssemblyName depends on the order staying the same private int _Major; private int _Minor; private int _Build = -1; private int _Revision = -1; public Version(int major, int minor, int build, int revision) { if (major < 0) throw new ArgumentOutOfRangeException("major",Environment.GetResourceString("ArgumentOutOfRange_Version")); if (minor < 0) throw new ArgumentOutOfRangeException("minor",Environment.GetResourceString("ArgumentOutOfRange_Version")); if (build < 0) throw new ArgumentOutOfRangeException("build",Environment.GetResourceString("ArgumentOutOfRange_Version")); if (revision < 0) throw new ArgumentOutOfRangeException("revision",Environment.GetResourceString("ArgumentOutOfRange_Version")); Contract.EndContractBlock(); _Major = major; _Minor = minor; _Build = build; _Revision = revision; } public Version(int major, int minor, int build) { if (major < 0) throw new ArgumentOutOfRangeException("major",Environment.GetResourceString("ArgumentOutOfRange_Version")); if (minor < 0) throw new ArgumentOutOfRangeException("minor",Environment.GetResourceString("ArgumentOutOfRange_Version")); if (build < 0) throw new ArgumentOutOfRangeException("build",Environment.GetResourceString("ArgumentOutOfRange_Version")); Contract.EndContractBlock(); _Major = major; _Minor = minor; _Build = build; } public Version(int major, int minor) { if (major < 0) throw new ArgumentOutOfRangeException("major",Environment.GetResourceString("ArgumentOutOfRange_Version")); if (minor < 0) throw new ArgumentOutOfRangeException("minor",Environment.GetResourceString("ArgumentOutOfRange_Version")); Contract.EndContractBlock(); _Major = major; _Minor = minor; } public Version(String version) { Version v = Version.Parse(version); _Major = v.Major; _Minor = v.Minor; _Build = v.Build; _Revision = v.Revision; } #if FEATURE_LEGACYNETCF //required for Mango AppCompat [System.Runtime.CompilerServices.FriendAccessAllowed] #endif public Version() { _Major = 0; _Minor = 0; } // Properties for setting and getting version numbers public int Major { get { return _Major; } } public int Minor { get { return _Minor; } } public int Build { get { return _Build; } } public int Revision { get { return _Revision; } } public short MajorRevision { get { return (short)(_Revision >> 16); } } public short MinorRevision { get { return (short)(_Revision & 0xFFFF); } } public Object Clone() { Version v = new Version(); v._Major = _Major; v._Minor = _Minor; v._Build = _Build; v._Revision = _Revision; return(v); } public int CompareTo(Object version) { if (version == null) { #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { throw new ArgumentOutOfRangeException(); } else { #endif return 1; #if FEATURE_LEGACYNETCF } #endif } Version v = version as Version; if (v == null) { #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { throw new InvalidCastException(Environment.GetResourceString("Arg_MustBeVersion")); } else { #endif throw new ArgumentException(Environment.GetResourceString("Arg_MustBeVersion")); #if FEATURE_LEGACYNETCF } #endif } if (this._Major != v._Major) if (this._Major > v._Major) return 1; else return -1; if (this._Minor != v._Minor) if (this._Minor > v._Minor) return 1; else return -1; if (this._Build != v._Build) if (this._Build > v._Build) return 1; else return -1; if (this._Revision != v._Revision) if (this._Revision > v._Revision) return 1; else return -1; return 0; } #if GENERICS_WORK public int CompareTo(Version value) { if (value == null) return 1; if (this._Major != value._Major) if (this._Major > value._Major) return 1; else return -1; if (this._Minor != value._Minor) if (this._Minor > value._Minor) return 1; else return -1; if (this._Build != value._Build) if (this._Build > value._Build) return 1; else return -1; if (this._Revision != value._Revision) if (this._Revision > value._Revision) return 1; else return -1; return 0; } #endif public override bool Equals(Object obj) { Version v = obj as Version; if (v == null) return false; // check that major, minor, build & revision numbers match if ((this._Major != v._Major) || (this._Minor != v._Minor) || (this._Build != v._Build) || (this._Revision != v._Revision)) return false; return true; } public bool Equals(Version obj) { if (obj == null) return false; // check that major, minor, build & revision numbers match if ((this._Major != obj._Major) || (this._Minor != obj._Minor) || (this._Build != obj._Build) || (this._Revision != obj._Revision)) return false; return true; } public override int GetHashCode() { // Let's assume that most version numbers will be pretty small and just // OR some lower order bits together. int accumulator = 0; accumulator |= (this._Major & 0x0000000F) << 28; accumulator |= (this._Minor & 0x000000FF) << 20; accumulator |= (this._Build & 0x000000FF) << 12; accumulator |= (this._Revision & 0x00000FFF); return accumulator; } public override String ToString() { if (_Build == -1) return(ToString(2)); if (_Revision == -1) return(ToString(3)); return(ToString(4)); } public String ToString(int fieldCount) { switch (fieldCount) { case 0: return(String.Empty); case 1: return(String.Concat(_Major)); case 2: return(String.Concat(_Major,".",_Minor)); default: if (_Build == -1) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "2"), "fieldCount"); if (fieldCount == 3) return( _Major + "." + _Minor + "." + _Build ); if (_Revision == -1) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "3"), "fieldCount"); if (fieldCount == 4) return( Major + "." + _Minor + "." + _Build + "." + _Revision ); throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "4"), "fieldCount"); } } public static Version Parse(string input) { if (input == null) { throw new ArgumentNullException("input"); } Contract.EndContractBlock(); VersionResult r = new VersionResult(); r.Init("input", true); if (!TryParseVersion(input, ref r)) { throw r.GetVersionParseException(); } return r.m_parsedVersion; } public static bool TryParse(string input, out Version result) { VersionResult r = new VersionResult(); r.Init("input", false); bool b = TryParseVersion(input, ref r); result = r.m_parsedVersion; return b; } private static bool TryParseVersion(string version, ref VersionResult result) { int major, minor, build, revision; if ((Object)version == null) { result.SetFailure(ParseFailureKind.ArgumentNullException); return false; } String[] parsedComponents = version.Split(new char[] { '.' }); int parsedComponentsLength = parsedComponents.Length; if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4)) { result.SetFailure(ParseFailureKind.ArgumentException); return false; } if (!TryParseComponent(parsedComponents[0], "version", ref result, out major)) { return false; } if (!TryParseComponent(parsedComponents[1], "version", ref result, out minor)) { return false; } parsedComponentsLength -= 2; if (parsedComponentsLength > 0) { if (!TryParseComponent(parsedComponents[2], "build", ref result, out build)) { return false; } parsedComponentsLength--; if (parsedComponentsLength > 0) { if (!TryParseComponent(parsedComponents[3], "revision", ref result, out revision)) { return false; } else { result.m_parsedVersion = new Version(major, minor, build, revision); } } else { result.m_parsedVersion = new Version(major, minor, build); } } else { result.m_parsedVersion = new Version(major, minor); } return true; } private static bool TryParseComponent(string component, string componentName, ref VersionResult result, out int parsedComponent) { if (!Int32.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent)) { result.SetFailure(ParseFailureKind.FormatException, component); return false; } if (parsedComponent < 0) { result.SetFailure(ParseFailureKind.ArgumentOutOfRangeException, componentName); return false; } return true; } public static bool operator ==(Version v1, Version v2) { if (Object.ReferenceEquals(v1, null)) { return Object.ReferenceEquals(v2, null); } return v1.Equals(v2); } public static bool operator !=(Version v1, Version v2) { return !(v1 == v2); } public static bool operator <(Version v1, Version v2) { if ((Object) v1 == null) throw new ArgumentNullException("v1"); Contract.EndContractBlock(); return (v1.CompareTo(v2) < 0); } public static bool operator <=(Version v1, Version v2) { if ((Object) v1 == null) throw new ArgumentNullException("v1"); Contract.EndContractBlock(); return (v1.CompareTo(v2) <= 0); } public static bool operator >(Version v1, Version v2) { return (v2 < v1); } public static bool operator >=(Version v1, Version v2) { return (v2 <= v1); } internal enum ParseFailureKind { ArgumentNullException, ArgumentException, ArgumentOutOfRangeException, FormatException } internal struct VersionResult { internal Version m_parsedVersion; internal ParseFailureKind m_failure; internal string m_exceptionArgument; internal string m_argumentName; internal bool m_canThrow; internal void Init(string argumentName, bool canThrow) { m_canThrow = canThrow; m_argumentName = argumentName; } internal void SetFailure(ParseFailureKind failure) { SetFailure(failure, String.Empty); } internal void SetFailure(ParseFailureKind failure, string argument) { m_failure = failure; m_exceptionArgument = argument; if (m_canThrow) { throw GetVersionParseException(); } } internal Exception GetVersionParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNullException: return new ArgumentNullException(m_argumentName); case ParseFailureKind.ArgumentException: return new ArgumentException(Environment.GetResourceString("Arg_VersionString")); case ParseFailureKind.ArgumentOutOfRangeException: return new ArgumentOutOfRangeException(m_exceptionArgument, Environment.GetResourceString("ArgumentOutOfRange_Version")); case ParseFailureKind.FormatException: // Regenerate the FormatException as would be thrown by Int32.Parse() try { Int32.Parse(m_exceptionArgument, CultureInfo.InvariantCulture); } catch (FormatException e) { return e; } catch (OverflowException e) { return e; } Contract.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument); return new FormatException(Environment.GetResourceString("Format_InvalidString")); default: Contract.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure); return new ArgumentException(Environment.GetResourceString("Arg_VersionString")); } } } } }
using System; using System.ComponentModel; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Interactivity; using Avalonia.Rendering; using Avalonia.Styling; using Avalonia.VisualTree; #nullable enable namespace Avalonia.Controls { /// <summary> /// Base class for Avalonia controls. /// </summary> /// <remarks> /// The control class extends <see cref="InputElement"/> and adds the following features: /// /// - A <see cref="Tag"/> property to allow user-defined data to be attached to the control. /// - <see cref="ContextRequestedEvent"/> and other context menu related members. /// </remarks> public class Control : InputElement, IControl, INamed, IVisualBrushInitialize, ISetterValue { /// <summary> /// Defines the <see cref="FocusAdorner"/> property. /// </summary> public static readonly StyledProperty<ITemplate<IControl>?> FocusAdornerProperty = AvaloniaProperty.Register<Control, ITemplate<IControl>?>(nameof(FocusAdorner)); /// <summary> /// Defines the <see cref="Tag"/> property. /// </summary> public static readonly StyledProperty<object?> TagProperty = AvaloniaProperty.Register<Control, object?>(nameof(Tag)); /// <summary> /// Defines the <see cref="ContextMenu"/> property. /// </summary> public static readonly StyledProperty<ContextMenu?> ContextMenuProperty = AvaloniaProperty.Register<Control, ContextMenu?>(nameof(ContextMenu)); /// <summary> /// Defines the <see cref="ContextFlyout"/> property /// </summary> public static readonly StyledProperty<FlyoutBase?> ContextFlyoutProperty = AvaloniaProperty.Register<Control, FlyoutBase?>(nameof(ContextFlyout)); /// <summary> /// Event raised when an element wishes to be scrolled into view. /// </summary> public static readonly RoutedEvent<RequestBringIntoViewEventArgs> RequestBringIntoViewEvent = RoutedEvent.Register<Control, RequestBringIntoViewEventArgs>("RequestBringIntoView", RoutingStrategies.Bubble); /// <summary> /// Provides event data for the <see cref="ContextRequested"/> event. /// </summary> public static readonly RoutedEvent<ContextRequestedEventArgs> ContextRequestedEvent = RoutedEvent.Register<Control, ContextRequestedEventArgs>(nameof(ContextRequested), RoutingStrategies.Tunnel | RoutingStrategies.Bubble); private DataTemplates? _dataTemplates; private IControl? _focusAdorner; /// <summary> /// Gets or sets the control's focus adorner. /// </summary> public ITemplate<IControl>? FocusAdorner { get => GetValue(FocusAdornerProperty); set => SetValue(FocusAdornerProperty, value); } /// <summary> /// Gets or sets the data templates for the control. /// </summary> /// <remarks> /// Each control may define data templates which are applied to the control itself and its /// children. /// </remarks> public DataTemplates DataTemplates => _dataTemplates ??= new DataTemplates(); /// <summary> /// Gets or sets a context menu to the control. /// </summary> public ContextMenu? ContextMenu { get => GetValue(ContextMenuProperty); set => SetValue(ContextMenuProperty, value); } /// <summary> /// Gets or sets a context flyout to the control /// </summary> public FlyoutBase? ContextFlyout { get => GetValue(ContextFlyoutProperty); set => SetValue(ContextFlyoutProperty, value); } /// <summary> /// Gets or sets a user-defined object attached to the control. /// </summary> public object? Tag { get => GetValue(TagProperty); set => SetValue(TagProperty, value); } /// <summary> /// Occurs when the user has completed a context input gesture, such as a right-click. /// </summary> public event EventHandler<ContextRequestedEventArgs> ContextRequested { add => AddHandler(ContextRequestedEvent, value); remove => RemoveHandler(ContextRequestedEvent, value); } public new IControl? Parent => (IControl?)base.Parent; /// <inheritdoc/> bool IDataTemplateHost.IsDataTemplatesInitialized => _dataTemplates != null; /// <inheritdoc/> void ISetterValue.Initialize(ISetter setter) { if (setter is Setter s && s.Property == ContextFlyoutProperty) { return; // Allow ContextFlyout to not need wrapping in <Template> } throw new InvalidOperationException( "Cannot use a control as a Setter value. Wrap the control in a <Template>."); } /// <inheritdoc/> void IVisualBrushInitialize.EnsureInitialized() { if (VisualRoot == null) { if (!IsInitialized) { foreach (var i in this.GetSelfAndVisualDescendants()) { var c = i as IControl; if (c?.IsInitialized == false && c is ISupportInitialize init) { init.BeginInit(); init.EndInit(); } } } if (!IsArrangeValid) { Measure(Size.Infinity); Arrange(new Rect(DesiredSize)); } } } /// <summary> /// Gets the element that receives the focus adorner. /// </summary> /// <returns>The control that receives the focus adorner.</returns> protected virtual IControl? GetTemplateFocusTarget() => this; /// <inheritdoc/> protected sealed override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTreeCore(e); InitializeIfNeeded(); } /// <inheritdoc/> protected sealed override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e) { base.OnDetachedFromVisualTreeCore(e); } /// <inheritdoc/> protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); if (IsFocused && (e.NavigationMethod == NavigationMethod.Tab || e.NavigationMethod == NavigationMethod.Directional)) { var adornerLayer = AdornerLayer.GetAdornerLayer(this); if (adornerLayer != null) { if (_focusAdorner == null) { var template = GetValue(FocusAdornerProperty); if (template != null) { _focusAdorner = template.Build(); } } if (_focusAdorner != null && GetTemplateFocusTarget() is Visual target) { AdornerLayer.SetAdornedElement((Visual)_focusAdorner, target); adornerLayer.Children.Add(_focusAdorner); } } } } /// <inheritdoc/> protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); if (_focusAdorner?.Parent != null) { var adornerLayer = (IPanel)_focusAdorner.Parent; adornerLayer.Children.Remove(_focusAdorner); _focusAdorner = null; } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (e.Source == this && !e.Handled && e.InitialPressMouseButton == MouseButton.Right) { var args = new ContextRequestedEventArgs(e); RaiseEvent(args); e.Handled = args.Handled; } } protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (e.Source == this && !e.Handled) { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>().OpenContextMenu; var matches = false; for (var index = 0; index < keymap.Count; index++) { var key = keymap[index]; matches |= key.Matches(e); if (matches) { break; } } if (matches) { var args = new ContextRequestedEventArgs(); RaiseEvent(args); e.Handled = args.Handled; } } } } }
using System; using System.Globalization; using Orleans.Core; using Orleans.Core.Abstractions.Internal; namespace Orleans.Runtime { [Serializable] internal class GrainId : UniqueIdentifier, IEquatable<GrainId>, IGrainIdentity { private static readonly object lockable = new object(); private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_LARGE; private static readonly TimeSpan internCacheCleanupInterval = InternerConstants.DefaultCacheCleanupFreq; private static Interner<UniqueKey, GrainId> grainIdInternCache; public UniqueKey.Category Category { get { return Key.IdCategory; } } public bool IsSystemTarget { get { return Key.IsSystemTargetKey; } } public bool IsGrain { get { return Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain; } } public bool IsClient { get { return Category == UniqueKey.Category.Client || Category == UniqueKey.Category.GeoClient; } } private GrainId(UniqueKey key) : base(key) { } public static GrainId NewId() { return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain)); } public static GrainId NewClientId(string clusterId = null) { return NewClientId(Guid.NewGuid(), clusterId); } internal static GrainId NewClientId(Guid id, string clusterId = null) { return FindOrCreateGrainId(UniqueKey.NewKey(id, clusterId == null ? UniqueKey.Category.Client : UniqueKey.Category.GeoClient, 0, clusterId)); } internal static GrainId GetGrainId(UniqueKey key) { return FindOrCreateGrainId(key); } internal static GrainId GetSystemGrainId(Guid guid) { return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.SystemGrain)); } // For testing only. internal static GrainId GetGrainIdForTesting(Guid guid) { return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.None)); } internal static GrainId NewSystemTargetGrainIdByTypeCode(int typeData) { return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(Guid.NewGuid(), typeData)); } internal static GrainId GetSystemTargetGrainId(short systemGrainId) { return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(systemGrainId)); } internal static GrainId GetGrainId(long typeCode, long primaryKey, string keyExt=null) { return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey, keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain, typeCode, keyExt)); } internal static GrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt=null) { return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey, keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain, typeCode, keyExt)); } internal static GrainId GetGrainId(long typeCode, string primaryKey) { return FindOrCreateGrainId(UniqueKey.NewKey(0L, UniqueKey.Category.KeyExtGrain, typeCode, primaryKey)); } internal static GrainId GetGrainServiceGrainId(short id, int typeData) { return FindOrCreateGrainId(UniqueKey.NewGrainServiceKey(id, typeData)); } public Guid PrimaryKey { get { return GetPrimaryKey(); } } public long PrimaryKeyLong { get { return GetPrimaryKeyLong(); } } public string PrimaryKeyString { get { return GetPrimaryKeyString(); } } public string IdentityString { get { return ToDetailedString(); } } public bool IsLongKey { get { return Key.IsLongKey; } } public long GetPrimaryKeyLong(out string keyExt) { return Key.PrimaryKeyToLong(out keyExt); } internal long GetPrimaryKeyLong() { return Key.PrimaryKeyToLong(); } public Guid GetPrimaryKey(out string keyExt) { return Key.PrimaryKeyToGuid(out keyExt); } internal Guid GetPrimaryKey() { return Key.PrimaryKeyToGuid(); } internal string GetPrimaryKeyString() { string key; var tmp = GetPrimaryKey(out key); return key; } public int TypeCode => Key.BaseTypeCode; private static GrainId FindOrCreateGrainId(UniqueKey key) { // Note: This is done here to avoid a wierd cyclic dependency / static initialization ordering problem involving the GrainId, Constants & Interner classes if (grainIdInternCache != null) return grainIdInternCache.FindOrCreate(key, k => new GrainId(k)); lock (lockable) { if (grainIdInternCache == null) { grainIdInternCache = new Interner<UniqueKey, GrainId>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval); } } return grainIdInternCache.FindOrCreate(key, k => new GrainId(k)); } #region IEquatable<GrainId> Members public bool Equals(GrainId other) { return other != null && Key.Equals(other.Key); } #endregion public override bool Equals(UniqueIdentifier obj) { var o = obj as GrainId; return o != null && Key.Equals(o.Key); } public override bool Equals(object obj) { var o = obj as GrainId; return o != null && Key.Equals(o.Key); } // Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods public override int GetHashCode() { return Key.GetHashCode(); } /// <summary> /// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function. /// NOTE: Hash code value may be positive or NEGATIVE. /// </summary> /// <returns>Hash code for this GrainId</returns> public uint GetUniformHashCode() { return Key.GetUniformHashCode(); } public override string ToString() { return ToStringImpl(false); } // same as ToString, just full primary key and type code internal string ToDetailedString() { return ToStringImpl(true); } // same as ToString, just full primary key and type code private string ToStringImpl(bool detailed) { string name = string.Empty; #if ABSTRACTIONS_TODO if (Constants.TryGetSystemGrainName(this, out name)) { return name; } #endif var keyString = Key.ToString(); // this should grab the least-significant half of n1, suffixing it with the key extension. string idString = keyString; if (!detailed) { if (keyString.Length >= 48) idString = keyString.Substring(24, 8) + keyString.Substring(48); else idString = keyString.Substring(24, 8); } string fullString = null; switch (Category) { case UniqueKey.Category.Grain: case UniqueKey.Category.KeyExtGrain: var typeString = TypeCode.ToString("X"); if (!detailed) typeString = typeString.Substring(Math.Max(0, typeString.Length - 8)); fullString = String.Format("*grn/{0}/{1}", typeString, idString); break; case UniqueKey.Category.Client: fullString = "*cli/" + idString; break; case UniqueKey.Category.GeoClient: fullString = string.Format("*gcl/{0}/{1}", Key.KeyExt, idString); break; case UniqueKey.Category.SystemTarget: #if ABSTRACTIONS_TODO string explicitName = Constants.SystemTargetName(this); if (TypeCode != 0) { var typeStr = TypeCode.ToString("X"); return String.Format("{0}/{1}/{2}", explicitName, typeStr, idString); } fullString = explicitName; break; #endif default: fullString = "???/" + idString; break; } return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString; } internal string ToFullString() { string kx; string pks = Key.IsLongKey ? GetPrimaryKeyLong(out kx).ToString(CultureInfo.InvariantCulture) : GetPrimaryKey(out kx).ToString(); string pksHex = Key.IsLongKey ? GetPrimaryKeyLong(out kx).ToString("X") : GetPrimaryKey(out kx).ToString("X"); return String.Format( "[GrainId: {0}, IdCategory: {1}, BaseTypeCode: {2} (x{3}), PrimaryKey: {4} (x{5}), UniformHashCode: {6} (0x{7, 8:X8}){8}]", ToDetailedString(), // 0 Category, // 1 TypeCode, // 2 TypeCode.ToString("X"), // 3 pks, // 4 pksHex, // 5 GetUniformHashCode(), // 6 GetUniformHashCode(), // 7 Key.HasKeyExt ? String.Format(", KeyExtension: {0}", kx) : ""); // 8 } internal string ToStringWithHashCode() { return String.Format("{0}-0x{1, 8:X8}", this.ToString(), this.GetUniformHashCode()); } /// <summary> /// Return this GrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method. /// </summary> /// <returns>GrainId in a standard string format.</returns> internal string ToParsableString() { // NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably. return Key.ToHexString(); } /// <summary> /// Create a new GrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method. /// </summary> /// <param name="grainId">String containing the GrainId info to be parsed.</param> /// <returns>New GrainId object created from the input data.</returns> internal static GrainId FromParsableString(string grainId) { // NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably. var key = UniqueKey.Parse(grainId); return FindOrCreateGrainId(key); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Mail.Net.RTP { #region usings using System; using System.Text; #endregion /// <summary> /// This class implements RTCP SDES packet one "chunk". /// </summary> public class RTCP_Packet_SDES_Chunk { #region Members private string m_CName; private string m_Email; private string m_Location; private string m_Name; private string m_Note; private string m_Phone; private uint m_Source; private string m_Tool; #endregion #region Properties /// <summary> /// Gets SSRC or CSRC identifier. /// </summary> public uint Source { get { return m_Source; } } /// <summary> /// Gets Canonical End-Point Identifier. /// </summary> public string CName { get { return m_CName; } } /// <summary> /// Gets or sets the real name, eg. "John Doe". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Name { get { return m_Name; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Name' value must be <= 255 bytes."); } m_Name = value; } } /// <summary> /// Gets or sets email address. For example "John.Doe@example.com". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Email { get { return m_Email; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Email' value must be <= 255 bytes."); } m_Email = value; } } /// <summary> /// Gets or sets phone number. For example "+1 908 555 1212". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Phone { get { return m_Phone; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Phone' value must be <= 255 bytes."); } m_Phone = value; } } /// <summary> /// Gets or sets location string. It may be geographic address or for example chat room name. /// Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Location { get { return m_Location; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Location' value must be <= 255 bytes."); } m_Location = value; } } /// <summary> /// Gets or sets streaming application name/version. /// Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Tool { get { return m_Tool; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Tool' value must be <= 255 bytes."); } m_Tool = value; } } /// <summary> /// Gets or sets note text. The NOTE item is intended for transient messages describing the current state /// of the source, e.g., "on the phone, can't talk". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Note { get { return m_Note; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Note' value must be <= 255 bytes."); } m_Note = value; } } /// <summary> /// Gets number of bytes needed for this SDES chunk. /// </summary> public int Size { get { int size = 4; if (!string.IsNullOrEmpty(m_CName)) { size += 2; size += Encoding.UTF8.GetByteCount(m_CName); } if (!string.IsNullOrEmpty(m_Name)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Name); } if (!string.IsNullOrEmpty(m_Email)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Email); } if (!string.IsNullOrEmpty(m_Phone)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Phone); } if (!string.IsNullOrEmpty(m_Location)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Location); } if (!string.IsNullOrEmpty(m_Tool)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Tool); } if (!string.IsNullOrEmpty(m_Note)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Note); } // Add terminate byte and padding bytes. size++; size += size%4; return size; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="source">SSRC or CSRC identifier.</param> /// <param name="cname">Canonical End-Point Identifier.</param> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public RTCP_Packet_SDES_Chunk(uint source, string cname) { if (source == 0) { throw new ArgumentException("Argument 'source' value must be > 0."); } if (string.IsNullOrEmpty(cname)) { throw new ArgumentException("Argument 'cname' value may not be null or empty."); } m_Source = source; m_CName = cname; } /// <summary> /// Parser constructor. /// </summary> internal RTCP_Packet_SDES_Chunk() {} #endregion #region Methods /// <summary> /// Parses SDES chunk from the specified buffer. /// </summary> /// <param name="buffer">Buffer which contains SDES chunk.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Parse(byte[] buffer, ref int offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } /* RFC 3550 6.5. The list of items in each chunk MUST be terminated by one or more null octets, the first of which is interpreted as an item type of zero to denote the end of the list. No length octet follows the null item type octet, but additional null octets MUST be included if needed to pad until the next 32-bit boundary. Note that this padding is separate from that indicated by the P bit in the RTCP header. A chunk with zero items (four null octets) is valid but useless. */ int startOffset = offset; // Read SSRC/CSRC m_Source = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); // Read SDES items while reach end of buffer or we get chunk terminator(\0). while (offset < buffer.Length && buffer[offset] != 0) { int type = buffer[offset++]; int length = buffer[offset++]; // CNAME if (type == 1) { m_CName = Encoding.UTF8.GetString(buffer, offset, length); } // NAME else if (type == 2) { m_Name = Encoding.UTF8.GetString(buffer, offset, length); } // EMAIL else if (type == 3) { m_Email = Encoding.UTF8.GetString(buffer, offset, length); } // PHONE else if (type == 4) { m_Phone = Encoding.UTF8.GetString(buffer, offset, length); } // LOC else if (type == 5) { m_Location = Encoding.UTF8.GetString(buffer, offset, length); } // TOOL else if (type == 6) { m_Tool = Encoding.UTF8.GetString(buffer, offset, length); } // NOTE else if (type == 7) { m_Note = Encoding.UTF8.GetString(buffer, offset, length); } // PRIV else if (type == 8) { // TODO: } offset += length; } // Terminator 0. offset++; // Pad to 32-bit boundary, if it isn't. See not above. offset += (offset - startOffset)%4; } /// <summary> /// Stores SDES junk to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store data.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void ToByte(byte[] buffer, ref int offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } int startOffset = offset; // SSRC/SDES buffer[offset++] = (byte) ((m_Source >> 24) & 0xFF); buffer[offset++] = (byte) ((m_Source >> 16) & 0xFF); buffer[offset++] = (byte) ((m_Source >> 8) & 0xFF); buffer[offset++] = (byte) ((m_Source) & 0xFF); //--- SDES items ----------------------------------- if (!string.IsNullOrEmpty(m_CName)) { byte[] b = Encoding.UTF8.GetBytes(m_CName); buffer[offset++] = 1; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Name)) { byte[] b = Encoding.UTF8.GetBytes(m_Name); buffer[offset++] = 2; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Email)) { byte[] b = Encoding.UTF8.GetBytes(m_Email); buffer[offset++] = 3; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Phone)) { byte[] b = Encoding.UTF8.GetBytes(m_Phone); buffer[offset++] = 4; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Location)) { byte[] b = Encoding.UTF8.GetBytes(m_Location); buffer[offset++] = 5; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Tool)) { byte[] b = Encoding.UTF8.GetBytes(m_Tool); buffer[offset++] = 6; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Note)) { byte[] b = Encoding.UTF8.GetBytes(m_Note); buffer[offset++] = 7; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } // Terminate chunk buffer[offset++] = 0; // Pad to 4(32-bit) bytes boundary. while ((offset - startOffset)%4 > 0) { buffer[offset++] = 0; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Mahjong; using ShantenHelper.Tiles; using System.Collections.ObjectModel; namespace ShantenHelper { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont shantenFont; Vector2 shantenTextPosition; string shantenText = "Shanten #: {0}"; string shantenWarning = "You need to have 14 tiles in hand to get the shanten number"; Vector2 shantenWarningPosition; private bool tenpai = false; private string tenpaiText = "Tenpai"; string handText = "Your hand:"; string handTextWarning = "Your hand is empty, click on a tile to add it"; Vector2 handTextPosition; ICollection<TileGameObject> SampleTiles; ObservableCollection<TileGameObject> PlayerHandTiles; int? ShantenNumber = null; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.IsFullScreen = false; graphics.PreferredBackBufferWidth = 700; } private const int TILE_WIDTH = 42; private const int TILE_HEIGHT = 64; private const int MARGIN_LEFT = 20; private const int MARGIN_TOP = 20; /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here this.IsMouseVisible = true; //Setting up one of each tile this.SampleTiles = new List<TileGameObject>(34); var Tiles = new List<Tile>(34); Tiles.AddRange(SuitedTile.GetAll()); Tiles.AddRange(HonorTile.GetAll()); Tiles.AddRange(DragonTile.GetAll()); int x = 0; int y = 0; Vector2 TopLeft = new Vector2(MARGIN_LEFT, MARGIN_TOP); foreach (var tile in Tiles) { var TileComp = new TileGameObject(this); TileComp.Tile = tile; TileComp.Position = TopLeft + new Vector2(x * TILE_WIDTH, y * TILE_HEIGHT); this.Components.Add(TileComp); this.SampleTiles.Add(TileComp); if (x == 8) { x = 0; y++; } else { x++; } } //Setting up player's hand this.PlayerHandTiles = new ObservableCollection<TileGameObject>(); this.PlayerHandTiles.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(PlayerHandTiles_CollectionChanged); //Text this.shantenTextPosition = new Vector2(MARGIN_LEFT, 350); this.shantenWarningPosition = shantenTextPosition + new Vector2(0, -25); this.handTextPosition = shantenTextPosition + new Vector2(0, +25); base.Initialize(); } void PlayerHandTiles_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: case System.Collections.Specialized.NotifyCollectionChangedAction.Replace: case System.Collections.Specialized.NotifyCollectionChangedAction.Reset: IDictionary<Tile,float> ShantenTiles; float BaseIntensity = 0; if (this.PlayerHandTiles.Count == 14) { var hand = this.PlayerHandTiles.Select(t => t.Tile).ToList(); //var foo = Mahjong.Hand.GetShantenTiles(hand, new List<Mahjong.Meld>()); //ShantenTiles = foo.Value; //ShantenNumber = foo.Key; ShantenTiles = Mahjong.Async.Players.AIShantenPlus.GetUndesirability(hand, out ShantenNumber); this.tenpai = ShantenNumber == 0; if (ShantenTiles.Count > 0) { BaseIntensity = -1f * ShantenTiles.Values.Min(); //Mark the "sample" tiles as non highlighteable foreach (var item in this.SampleTiles) { item.Highlighteable = false; } } else if (this.tenpai) { var riichiDiscards = Hand.GetDiscardsForTenpai(typeof(ScorerJapanese), hand, new List<Mahjong.Meld>(), null, null); } } else { ShantenTiles = new Dictionary<Tile,float>(); ShantenNumber = null; this.tenpai = false; //Mark the "sample" tiles as highlighteable foreach (var item in this.SampleTiles) { item.Highlighteable = true; } } int i = 0; foreach (var item in this.PlayerHandTiles.OrderBy(t => t.Tile.Value())) { item.Position = new Vector2(MARGIN_LEFT + i * TILE_WIDTH, 400); item.RecommendedDiscard = ShantenTiles.Keys.Any(shanten => shanten.Value() == item.Tile.Value()); if (item.RecommendedDiscard) { item.RecommendedDiscardIntensity = ShantenTiles[item.Tile] + BaseIntensity; } else { item.RecommendedDiscardIntensity = null; } i++; } break; case System.Collections.Specialized.NotifyCollectionChangedAction.Move: break; } } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); this.Services.AddService(typeof(SpriteBatch), spriteBatch); // TODO: use this.Content to load your game content here this.shantenFont = Content.Load<SpriteFont>("CourierNew"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } MouseState lastMouseState; MouseState currentMouseState; /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here #region Input if (this.IsActive) //Handle Input { lastMouseState = currentMouseState; currentMouseState = Mouse.GetState(); // Recognize a single click of the left mouse button if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed) { var SelectedSampleTile = this.SampleTiles.LastOrDefault(t => t.Highlighted); if (SelectedSampleTile != null && this.PlayerHandTiles.Count < 14) { var newTileComp = new TileGameObject(this); newTileComp.Tile = SelectedSampleTile.Tile; //newTileComp.Position = new Vector2(MARGIN_LEFT + this.PlayerHandTiles.Count * TILE_WIDTH , 400); this.PlayerHandTiles.Add(newTileComp); this.Components.Add(newTileComp); } else { var SelectedHandTile = this.PlayerHandTiles.LastOrDefault(t => t.Highlighted); this.Components.Remove(SelectedHandTile); this.PlayerHandTiles.Remove(SelectedHandTile); } } } #endregion base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here this.spriteBatch.Begin(); if (this.tenpai) { this.spriteBatch.DrawString(this.shantenFont, this.tenpaiText, shantenTextPosition, Color.DarkRed); } else { this.spriteBatch.DrawString(this.shantenFont, string.Format(shantenText, this.ShantenNumber.HasValue ? this.ShantenNumber.Value.ToString() : "N/A"), shantenTextPosition, Color.Black); } if (!this.ShantenNumber.HasValue) { this.spriteBatch.DrawString(this.shantenFont, shantenWarning, shantenWarningPosition, Color.DarkRed); } if (this.PlayerHandTiles.Count == 0) { this.spriteBatch.DrawString(this.shantenFont, handTextWarning, handTextPosition, Color.DarkRed); } else { this.spriteBatch.DrawString(this.shantenFont, handText, handTextPosition, Color.Black); } this.spriteBatch.End(); base.Draw(gameTime); } } }
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> namespace System.Activities.Presentation.Validation { using System.Activities.Validation; using System.Runtime; using System.Threading; using System.Windows.Threading; internal class BackgroundValidationSynchronizer<TValidationResult> : ValidationSynchronizer { internal readonly SynchronizerState Idle; internal readonly SynchronizerState Validating; internal readonly SynchronizerState CancellingForNextValidation; internal readonly SynchronizerState CancellingForDeactivation; internal readonly SynchronizerState ValidationDeactivated; private readonly object thisLock = new object(); private Func<ValidationReason, CancellationToken, TValidationResult> validationWork; private Action<TValidationResult> updateWork; private CancellationTokenSource cancellationTokenSource; private TaskDispatcher dispatcher; private SynchronizerState currentState; private ValidationReason lastValidationReason; private int deactivationReferenceCount; internal BackgroundValidationSynchronizer(TaskDispatcher dispatcher, Func<ValidationReason, CancellationToken, TValidationResult> validationWork, Action<TValidationResult> updateWork) { Fx.Assert(validationWork != null, "validationWork should not be null and is ensured by caller."); Fx.Assert(updateWork != null, "updateWork should not be null and is ensured by caller."); this.Idle = new IdleState(this); this.Validating = new ValidatingState(this); this.CancellingForNextValidation = new CancellingForNextValidationState(this); this.CancellingForDeactivation = new CancellingForDeactivationState(this); this.ValidationDeactivated = new ValidationDeactivatedState(this); this.dispatcher = dispatcher; this.validationWork = validationWork; this.updateWork = updateWork; this.currentState = this.Idle; } internal SynchronizerState CurrentState { get { return this.currentState; } private set { this.currentState = value; this.OnCurrentStateChanged(); } } internal override void Validate(ValidationReason validationReason) { lock (this.thisLock) { this.CurrentState = this.CurrentState.Validate(validationReason); } } internal override void DeactivateValidation() { lock (this.thisLock) { Fx.Assert(this.deactivationReferenceCount >= 0, "It should never happen -- deactivationReferenceCount < 0."); if (this.deactivationReferenceCount == 0) { this.CurrentState = this.CurrentState.DeactivateValidation(); if (this.CurrentState != this.ValidationDeactivated) { Monitor.Wait(this.thisLock); } } this.deactivationReferenceCount++; } } internal override void ActivateValidation() { lock (this.thisLock) { this.deactivationReferenceCount--; Fx.Assert(this.deactivationReferenceCount >= 0, "It should never happen -- deactivationReferenceCount < 0."); if (this.deactivationReferenceCount == 0) { this.CurrentState = this.CurrentState.ActivateValidation(); } } } // for unit test only protected virtual void OnCurrentStateChanged() { } private void ValidationCompleted(TValidationResult result) { lock (this.thisLock) { this.CurrentState = this.CurrentState.ValidationCompleted(result); } } private void ValidationCancelled() { lock (this.thisLock) { this.CurrentState = this.CurrentState.ValidationCancelled(); } } private void CancellableValidate(object state) { Fx.Assert(state is ValidationReason, "unusedState should always be a ValidationReason."); ValidationReason reason = (ValidationReason)state; try { Fx.Assert(this.cancellationTokenSource != null, "this.cancellationTokenSource should be constructed"); TValidationResult result = this.validationWork(reason, this.cancellationTokenSource.Token); this.ValidationCompleted(result); } catch (OperationCanceledException) { this.ValidationCancelled(); } } private void Cancel() { Fx.Assert(this.cancellationTokenSource != null, "Cancel should be called only when the work is active, and by the time the cancellationTokenSource should not be null."); Fx.Assert(this.cancellationTokenSource.IsCancellationRequested == false, "We should only request for cancel once."); this.cancellationTokenSource.Cancel(); } private void ValidationWork(ValidationReason reason) { this.cancellationTokenSource = new CancellationTokenSource(); this.dispatcher.DispatchWorkOnBackgroundThread(Fx.ThunkCallback(new WaitCallback(this.CancellableValidate)), reason); } private void UpdateUI(TValidationResult result) { this.dispatcher.DispatchWorkOnUIThread(DispatcherPriority.ApplicationIdle, new Action(() => { this.updateWork(result); })); } internal abstract class SynchronizerState { public SynchronizerState(BackgroundValidationSynchronizer<TValidationResult> parent) { Fx.Assert(parent != null, "parent should not be null."); this.Parent = parent; } protected BackgroundValidationSynchronizer<TValidationResult> Parent { get; private set; } public abstract SynchronizerState Validate(ValidationReason reason); public abstract SynchronizerState ValidationCompleted(TValidationResult result); public abstract SynchronizerState ValidationCancelled(); public abstract SynchronizerState DeactivateValidation(); public abstract SynchronizerState ActivateValidation(); } private class IdleState : SynchronizerState { public IdleState(BackgroundValidationSynchronizer<TValidationResult> parent) : base(parent) { } public override SynchronizerState Validate(ValidationReason reason) { this.Parent.ValidationWork(reason); return this.Parent.Validating; } public override SynchronizerState ValidationCompleted(TValidationResult result) { Fx.Assert(false, "This should never happen - we are idle, so there is no work to complete."); return this; } public override SynchronizerState ValidationCancelled() { Fx.Assert(false, "This should never happen - we are idle, so there is no work to be cancelled."); return this; } public override SynchronizerState DeactivateValidation() { return this.Parent.ValidationDeactivated; } public override SynchronizerState ActivateValidation() { Fx.Assert(false, "This should never happen - validation hasn't been deactivated, so there is no possibility for activate validation."); return this; } } private class ValidatingState : SynchronizerState { public ValidatingState(BackgroundValidationSynchronizer<TValidationResult> parent) : base(parent) { } public override SynchronizerState Validate(ValidationReason reason) { this.Parent.Cancel(); this.Parent.lastValidationReason = reason; return this.Parent.CancellingForNextValidation; } public override SynchronizerState ValidationCompleted(TValidationResult result) { this.Parent.cancellationTokenSource = null; this.Parent.UpdateUI(result); return this.Parent.Idle; } public override SynchronizerState ValidationCancelled() { Fx.Assert(false, "This should never happen - we haven't request for cancel yet, so there is no work to be cancelled."); return this; } public override SynchronizerState DeactivateValidation() { this.Parent.Cancel(); return this.Parent.CancellingForDeactivation; } public override SynchronizerState ActivateValidation() { Fx.Assert(false, "This should never happen - validation hasn't been deactivated, so there is no possibility for activate validation."); return this; } } private class CancellingForNextValidationState : SynchronizerState { public CancellingForNextValidationState(BackgroundValidationSynchronizer<TValidationResult> parent) : base(parent) { } public override SynchronizerState Validate(ValidationReason reason) { this.Parent.lastValidationReason = reason; return this.Parent.CancellingForNextValidation; } public override SynchronizerState ValidationCompleted(TValidationResult result) { this.Parent.cancellationTokenSource = null; this.Parent.UpdateUI(result); this.Parent.ValidationWork(this.Parent.lastValidationReason); return this.Parent.Validating; } public override SynchronizerState ValidationCancelled() { this.Parent.cancellationTokenSource = null; this.Parent.ValidationWork(this.Parent.lastValidationReason); return this.Parent.Validating; } public override SynchronizerState DeactivateValidation() { return this.Parent.CancellingForDeactivation; } public override SynchronizerState ActivateValidation() { Fx.Assert(false, "This should never happen - validation hasn't been deactivated, so there is no possibility for activate validation."); return this; } } private class CancellingForDeactivationState : SynchronizerState { public CancellingForDeactivationState(BackgroundValidationSynchronizer<TValidationResult> parent) : base(parent) { } public override SynchronizerState Validate(ValidationReason reason) { // Validation need to give way to commit so that we have a responsive UI. return this.Parent.CancellingForDeactivation; } public override SynchronizerState ValidationCompleted(TValidationResult result) { this.Parent.cancellationTokenSource = null; this.Parent.UpdateUI(result); Monitor.Pulse(this.Parent.thisLock); return this.Parent.ValidationDeactivated; } public override SynchronizerState ValidationCancelled() { this.Parent.cancellationTokenSource = null; Monitor.Pulse(this.Parent.thisLock); return this.Parent.ValidationDeactivated; } public override SynchronizerState DeactivateValidation() { return this.Parent.CancellingForDeactivation; } public override SynchronizerState ActivateValidation() { Fx.Assert(false, "This should never happen - validation hasn't been deactivated, so there is no possibility for activate validation."); return this; } } private class ValidationDeactivatedState : SynchronizerState { public ValidationDeactivatedState(BackgroundValidationSynchronizer<TValidationResult> parent) : base(parent) { } public override SynchronizerState Validate(ValidationReason reason) { // no-op - because commit will trigger validation anyway. return this.Parent.ValidationDeactivated; } public override SynchronizerState ValidationCompleted(TValidationResult result) { Fx.Assert(false, "This should never happen - we are committing, so there is no validation work in progress, not to mention the possibility for them to be completed."); return this; } public override SynchronizerState ValidationCancelled() { Fx.Assert(false, "This should never happen - we are committing, not to mention the possibility for them to be cancelled."); return this; } public override SynchronizerState DeactivateValidation() { Fx.Assert(false, "This should never happen - validation has already been deactivated, so we shouldn't DeactivateValidation again."); return this; } public override SynchronizerState ActivateValidation() { return this.Parent.Idle; } } } }
// 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 Xunit; namespace System.Globalization.Tests { public class CompareInfoLastIndexOfTests { private static CompareInfo s_invariantCompare = CultureInfo.InvariantCulture.CompareInfo; private static CompareInfo s_hungarianCompare = new CultureInfo("hu-HU").CompareInfo; private static CompareInfo s_turkishCompare = new CultureInfo("tr-TR").CompareInfo; private static CompareInfo s_slovakCompare = new CultureInfo("sk-SK").CompareInfo; public static IEnumerable<object[]> LastIndexOf_TestData() { // Empty strings yield return new object[] { s_invariantCompare, "foo", "", 2, 3, CompareOptions.None, 2 }; yield return new object[] { s_invariantCompare, "", "", 0, 0, CompareOptions.None, 0 }; yield return new object[] { s_invariantCompare, "", "a", 0, 0, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "", "", -1, 0, CompareOptions.None, 0 }; yield return new object[] { s_invariantCompare, "", "a", -1, 0, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "", "", 0, -1, CompareOptions.None, 0 }; yield return new object[] { s_invariantCompare, "", "a", 0, -1, CompareOptions.None, -1 }; // Start index = source.Length yield return new object[] { s_invariantCompare, "Hello", "l", 5, 5, CompareOptions.None, 3 }; yield return new object[] { s_invariantCompare, "Hello", "b", 5, 5, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "Hello", "l", 5, 0, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "Hello", "", 5, 5, CompareOptions.None, 4 }; yield return new object[] { s_invariantCompare, "Hello", "", 5, 0, CompareOptions.None, 4 }; // OrdinalIgnoreCase yield return new object[] { s_invariantCompare, "Hello", "l", 4, 5, CompareOptions.OrdinalIgnoreCase, 3 }; yield return new object[] { s_invariantCompare, "Hello", "L", 4, 5, CompareOptions.OrdinalIgnoreCase, 3 }; yield return new object[] { s_invariantCompare, "Hello", "h", 4, 5, CompareOptions.OrdinalIgnoreCase, 0 }; // Long strings yield return new object[] { s_invariantCompare, new string('a', 5555) + new string('b', 100), "aaaaaaaaaaaaaaa", 5654, 5655, CompareOptions.None, 5540 }; yield return new object[] { s_invariantCompare, new string('b', 101) + new string('a', 5555), new string('a', 5000), 5655, 5656, CompareOptions.None, 656 }; yield return new object[] { s_invariantCompare, new string('a', 5555), new string('a', 5000) + "b", 5554, 5555, CompareOptions.None, -1 }; // Hungarian yield return new object[] { s_hungarianCompare, "foobardzsdzs", "rddzs", 11, 12, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, "foobardzsdzs", "rddzs", 11, 12, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "foobardzsdzs", "rddzs", 11, 12, CompareOptions.Ordinal, -1 }; // Slovak yield return new object[] { s_slovakCompare, "ch", "h", 0, 1, CompareOptions.None, -1 }; yield return new object[] { s_slovakCompare, "hore chodit", "HO", 11, 12, CompareOptions.IgnoreCase, 0 }; yield return new object[] { s_slovakCompare, "chh", "h", 2, 2, CompareOptions.None, 2 }; // Turkish yield return new object[] { s_turkishCompare, "Hi", "I", 1, 2, CompareOptions.None, -1 }; yield return new object[] { s_turkishCompare, "Hi", "I", 1, 2, CompareOptions.IgnoreCase, -1 }; yield return new object[] { s_turkishCompare, "Hi", "\u0130", 1, 2, CompareOptions.None, -1 }; yield return new object[] { s_turkishCompare, "Hi", "\u0130", 1, 2, CompareOptions.IgnoreCase, 1 }; yield return new object[] { s_invariantCompare, "Hi", "I", 1, 2, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "Hi", "I", 1, 2, CompareOptions.IgnoreCase, 1 }; yield return new object[] { s_invariantCompare, "Hi", "\u0130", 1, 2, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "Hi", "\u0130", 1, 2, CompareOptions.IgnoreCase, -1 }; // Unicode yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "A\u0300", 8, 9, CompareOptions.None, 8 }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "A\u0300", 8, 9, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.IgnoreCase, 8 }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.OrdinalIgnoreCase, -1 }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, "FooBar", "Foo\u0400Bar", 5, 6, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, "TestFooBA\u0300R", "FooB\u00C0R", 10, 11, CompareOptions.IgnoreNonSpace, 4 }; yield return new object[] { s_invariantCompare, "o\u0308", "o", 1, 2, CompareOptions.None, -1 }; // Ignore symbols yield return new object[] { s_invariantCompare, "More Test's", "Tests", 10, 11, CompareOptions.IgnoreSymbols, 5 }; yield return new object[] { s_invariantCompare, "More Test's", "Tests", 10, 11, CompareOptions.None, -1 }; yield return new object[] { s_invariantCompare, "cbabababdbaba", "ab", 12, 13, CompareOptions.None, 10 }; // Platform differences yield return new object[] { s_hungarianCompare, "foobardzsdzs", "rddzs", 11, 12, CompareOptions.None, PlatformDetection.IsWindows ? 5 : -1 }; } public static IEnumerable<object[]> LastIndexOf_Aesc_Ligature_TestData() { bool isWindows = PlatformDetection.IsWindows; // Searches for the ligature \u00C6 string source = "Is AE or ae the same as \u00C6 or \u00E6?"; yield return new object[] { s_invariantCompare, source, "AE", 25, 18, CompareOptions.None, isWindows ? 24 : -1 }; yield return new object[] { s_invariantCompare, source, "ae", 25, 18, CompareOptions.None, 9 }; yield return new object[] { s_invariantCompare, source, '\u00C6', 25, 18, CompareOptions.None, 24 }; yield return new object[] { s_invariantCompare, source, '\u00E6', 25, 18, CompareOptions.None, isWindows ? 9 : -1 }; yield return new object[] { s_invariantCompare, source, "AE", 25, 18, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, source, "ae", 25, 18, CompareOptions.Ordinal, 9 }; yield return new object[] { s_invariantCompare, source, '\u00C6', 25, 18, CompareOptions.Ordinal, 24 }; yield return new object[] { s_invariantCompare, source, '\u00E6', 25, 18, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, source, "AE", 25, 18, CompareOptions.IgnoreCase, isWindows ? 24 : 9 }; yield return new object[] { s_invariantCompare, source, "ae", 25, 18, CompareOptions.IgnoreCase, isWindows ? 24 : 9 }; yield return new object[] { s_invariantCompare, source, '\u00C6', 25, 18, CompareOptions.IgnoreCase, 24 }; yield return new object[] { s_invariantCompare, source, '\u00E6', 25, 18, CompareOptions.IgnoreCase, 24 }; } public static IEnumerable<object[]> LastIndexOf_U_WithDiaeresis_TestData() { // Searches for the combining character sequence Latin capital letter U with diaeresis or Latin small letter u with diaeresis. string source = "Is \u0055\u0308 or \u0075\u0308 the same as \u00DC or \u00FC?"; yield return new object[] { s_invariantCompare, source, "U\u0308", 25, 18, CompareOptions.None, 24 }; yield return new object[] { s_invariantCompare, source, "u\u0308", 25, 18, CompareOptions.None, 9 }; yield return new object[] { s_invariantCompare, source, '\u00DC', 25, 18, CompareOptions.None, 24 }; yield return new object[] { s_invariantCompare, source, '\u00FC', 25, 18, CompareOptions.None, 9 }; yield return new object[] { s_invariantCompare, source, "U\u0308", 25, 18, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, source, "u\u0308", 25, 18, CompareOptions.Ordinal, 9 }; yield return new object[] { s_invariantCompare, source, '\u00DC', 25, 18, CompareOptions.Ordinal, 24 }; yield return new object[] { s_invariantCompare, source, '\u00FC', 25, 18, CompareOptions.Ordinal, -1 }; yield return new object[] { s_invariantCompare, source, "U\u0308", 25, 18, CompareOptions.IgnoreCase, 24 }; yield return new object[] { s_invariantCompare, source, "u\u0308", 25, 18, CompareOptions.IgnoreCase, 24 }; yield return new object[] { s_invariantCompare, source, '\u00DC', 25, 18, CompareOptions.IgnoreCase, 24 }; yield return new object[] { s_invariantCompare, source, '\u00FC', 25, 18, CompareOptions.IgnoreCase, 24 }; } [Theory] [MemberData(nameof(LastIndexOf_TestData))] [MemberData(nameof(LastIndexOf_U_WithDiaeresis_TestData))] public void LastIndexOf_String(CompareInfo compareInfo, string source, string value, int startIndex, int count, CompareOptions options, int expected) { if (value.Length == 1) { LastIndexOf_Char(compareInfo, source, value[0], startIndex, count, options, expected); } if (options == CompareOptions.None) { // Use LastIndexOf(string, string, int, int) or LastIndexOf(string, string) if (startIndex + 1 == source.Length && count == source.Length) { // Use LastIndexOf(string, string) Assert.Equal(expected, compareInfo.LastIndexOf(source, value)); } // Use LastIndexOf(string, string, int, int) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, startIndex, count)); } if (count - startIndex - 1 == 0) { // Use LastIndexOf(string, string, int, CompareOptions) or LastIndexOf(string, string, CompareOptions) if (startIndex == source.Length) { // Use LastIndexOf(string, string, CompareOptions) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, options)); } // Use LastIndexOf(string, string, int, CompareOptions) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, startIndex, options)); } // Use LastIndexOf(string, string, int, int, CompareOptions) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, startIndex, count, options)); if ((compareInfo == s_invariantCompare) && ((options == CompareOptions.None) || (options == CompareOptions.IgnoreCase))) { StringComparison stringComparison = (options == CompareOptions.IgnoreCase) ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture; // Use int string.LastIndexOf(string, StringComparison) Assert.Equal(expected, source.LastIndexOf(value, startIndex, count, stringComparison)); // Use int MemoryExtensions.LastIndexOf(this ReadOnlySpan<char>, ReadOnlySpan<char>, StringComparison) // Filter differences betweeen string-based and Span-based LastIndexOf // - Empty value handling - https://github.com/dotnet/coreclr/issues/26608 // - Negative count if (value.Length == 0 || count < 0) return; if (startIndex == source.Length) { startIndex--; if (count > 0) count--; } int leftStartIndex = (startIndex - count + 1); Assert.Equal((expected == -1) ? -1 : (expected - leftStartIndex), source.AsSpan(leftStartIndex, count).LastIndexOf(value.AsSpan(), stringComparison)); } } private static void LastIndexOf_Char(CompareInfo compareInfo, string source, char value, int startIndex, int count, CompareOptions options, int expected) { if (options == CompareOptions.None) { // Use LastIndexOf(string, char, int, int) or LastIndexOf(string, char) if (startIndex + 1 == source.Length && count == source.Length) { // Use LastIndexOf(string, char) Assert.Equal(expected, compareInfo.LastIndexOf(source, value)); } // Use LastIndexOf(string, char, int, int) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, startIndex, count)); } if (count - startIndex - 1 == 0) { // Use LastIndexOf(string, char, int, CompareOptions) or LastIndexOf(string, char, CompareOptions) if (startIndex == source.Length) { // Use LastIndexOf(string, char, CompareOptions) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, options)); } // Use LastIndexOf(string, char, int, CompareOptions) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, startIndex, options)); } // Use LastIndexOf(string, char, int, int, CompareOptions) Assert.Equal(expected, compareInfo.LastIndexOf(source, value, startIndex, count, options)); } [Theory] [MemberData(nameof(LastIndexOf_Aesc_Ligature_TestData))] public void LastIndexOf_Aesc_Ligature(CompareInfo compareInfo, string source, string value, int startIndex, int count, CompareOptions options, int expected) { LastIndexOf_String(compareInfo, source, value, startIndex, count, options, expected); } [Fact] public void LastIndexOf_UnassignedUnicode() { bool isWindows = PlatformDetection.IsWindows; LastIndexOf_String(s_invariantCompare, "FooBar", "Foo\uFFFFBar", 5, 6, CompareOptions.None, isWindows ? 0 : -1); LastIndexOf_String(s_invariantCompare, "~FooBar", "Foo\uFFFFBar", 6, 7, CompareOptions.IgnoreNonSpace, isWindows ? 1 : -1); } [Fact] public void LastIndexOf_Invalid() { // Source is null AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, "a")); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, "a", CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, "a", 0, 0)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, "a", 0, CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, "a", 0, 0, CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, 'a')); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, 'a', CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, 'a', 0, 0)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, 'a', 0, CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, 'a', 0, 0, CompareOptions.None)); // Value is null AssertExtensions.Throws<ArgumentNullException>("value", () => s_invariantCompare.LastIndexOf("", null)); AssertExtensions.Throws<ArgumentNullException>("value", () => s_invariantCompare.LastIndexOf("", null, CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("value", () => s_invariantCompare.LastIndexOf("", null, 0, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => s_invariantCompare.LastIndexOf("", null, 0, CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("value", () => s_invariantCompare.LastIndexOf("", null, 0, 0, CompareOptions.None)); // Source and value are null AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, null)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, null, CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, null, 0, 0)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, null, 0, CompareOptions.None)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.LastIndexOf(null, null, 0, 0, CompareOptions.None)); // Options are invalid AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", CompareOptions.StringSort)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, CompareOptions.StringSort)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, 2, CompareOptions.StringSort)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', CompareOptions.StringSort)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, CompareOptions.StringSort)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, 2, CompareOptions.StringSort)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", CompareOptions.Ordinal | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, CompareOptions.Ordinal | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, 2, CompareOptions.Ordinal | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', CompareOptions.Ordinal | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, CompareOptions.Ordinal | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, 2, CompareOptions.Ordinal | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, 2, CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, 2, CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", (CompareOptions)(-1))); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, (CompareOptions)(-1))); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, 2, (CompareOptions)(-1))); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", (CompareOptions)(-1))); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, (CompareOptions)(-1))); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, 2, (CompareOptions)(-1))); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", (CompareOptions)0x11111111)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, (CompareOptions)0x11111111)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", "Tests", 0, 2, (CompareOptions)0x11111111)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', (CompareOptions)0x11111111)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, (CompareOptions)0x11111111)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.LastIndexOf("Test's", 'a', 0, 2, (CompareOptions)0x11111111)); // StartIndex < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", "Test", -1, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", "Test", -1, 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", "Test", -1, 2, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", 'a', -1, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", 'a', -1, 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", 'a', -1, 2, CompareOptions.None)); // StartIndex >= source.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", "Test", 5, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", "Test", 5, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", "Test", 5, 0, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", 'a', 5, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", 'a', 5, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => s_invariantCompare.LastIndexOf("Test", 'a', 5, 0, CompareOptions.None)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 0, -1, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 0, -1, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 4, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 4, -1, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 4, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 4, -1, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "", 4, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "", 4, -1, CompareOptions.None)); // Count > source.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 0, 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 0, 5, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 0, 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 0, 5, CompareOptions.None)); // StartIndex + count > source.Length + 1 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 3, 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "Test", 3, 5, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 3, 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 'a', 3, 5, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "s", 4, 6)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", "s", 4, 7, CompareOptions.None)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 's', 4, 6)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s_invariantCompare.LastIndexOf("Test", 's', 4, 7, CompareOptions.None)); } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Collections; using System.IO; using SpiffLib; using System.Diagnostics; using System.Text; using m; namespace m { public class OutputTools { public static void ImportExportPdbs(string[] astr) { // Expand filespecs ArrayList alsFiles = new ArrayList(); for (int n = 1; n < astr.Length; n++) { string strFileT = Path.GetFileName(astr[n]); string strDirT = Path.GetDirectoryName(astr[n]); if (strDirT == "") strDirT = "."; string[] astrFiles = Directory.GetFiles(strDirT, strFileT); foreach (string filename in astrFiles) { if (filename.EndsWith(".pdb")) { alsFiles.Add(filename); } } } // Import, then save each pdb foreach (string filename in alsFiles) { try { if (File.Exists(filename + "_new")) { Console.WriteLine("Exists: " + filename + "_new"); continue; } ImportExpansionPdb(filename); LevelDocTemplate doctLevel = (LevelDocTemplate)DocManager.FindDocTemplate(typeof(LevelDoc)); Document[] adoc = doctLevel.GetDocuments(); SaveExpansionPdb(filename + "_new", adoc, "1.1"); foreach (Document doc in adoc) { doc.SetModified(false); } doctLevel.CloseAllDocuments(); } catch { Console.WriteLine("Error loading " + filename + ", skipping"); } } } public static void ImportExpansionPdb(string strFile) { PdbPacker pdbp = new PdbPacker(strFile); ArrayList alsTileSets = new ArrayList(); for (int i = 0; i < pdbp.Count; i++) { PdbPacker.File file = pdbp[i]; if (!file.str.EndsWith(".lvl")) { continue; } // Load up the pieces Ini ini = Ini.LoadBinary(new MemoryStream(file.ab)); string strTileMapFilename = ini["General"]["TileMap"].Value; TileMap tmap = TileMap.Load(new MemoryStream(pdbp[strTileMapFilename].ab)); // First, tell the active LevelDoc not to switch its templates based on the following // template load LevelDoc lvldActive = (LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc)); if (lvldActive != null) { lvldActive.SwitchTemplatesEnabled = false; } // If the TileSet for this level is not yet available, load it now TemplateDoc tmpd = (TemplateDoc)DocManager.OpenDocument(tmap.Filename.Replace(".tset", ".tc")); TileSet tset = null; foreach (TileSet tsetT in alsTileSets) { if (tsetT.FileName == tmap.Filename) { tset = tsetT; break; } } if (tset == null) { tset = new TileSet(tmpd, tmap.Filename); alsTileSets.Add(tset); } // Re-enable template switching if (lvldActive != null) { lvldActive.SwitchTemplatesEnabled = true; } // Create a new level description, and deduce which templates are in it, with what visibility LevelDoc lvld = (LevelDoc)DocManager.NewDocument(typeof(LevelDoc), null); lvld.OutputFilename = file.str; ImportTileMap(tmap, tset, tmpd, lvld); // Walls are stored in the terrain map. Load them. string strTrmapFilename = ini["General"]["TerrainMap"].Value; TerrainMap trmap = TerrainMap.Load(new MemoryStream(pdbp[strTrmapFilename].ab)); ImportWalls(trmap, lvld); // Load everything else lvld.LoadIni(ini); } } static void ImportWalls(TerrainMap trmap, LevelDoc lvld) { ArrayList alsmi = new ArrayList(); for (int ty = 0; ty < trmap.Map.GetLength(0); ty++) { for (int tx = 0; tx < trmap.Map.GetLength(1); tx++) { if (trmap.Map[ty, tx] == TerrainTypes.Wall) { IMapItem mi = new Wall(100, lvld.Bounds.Left + tx, lvld.Bounds.Top + ty); alsmi.Add(mi); } } } lvld.AddMapItems((IMapItem[])alsmi.ToArray(typeof(IMapItem))); } class TemplatePos { public Template tmpl; public int txOrigin; public int tyOrigin; public bool[,] afMapped; public TemplatePos(Template tmpl, int txOrigin, int tyOrigin, bool[,] afMapped) { this.tmpl = tmpl; this.txOrigin = txOrigin; this.tyOrigin = tyOrigin; this.afMapped = afMapped; } } static void ImportTileMap(TileMap tmap, TileSet tset, TemplateDoc tmpd, LevelDoc lvld) { // The TileMap is a list of indexes into a tile set. A Tileset is a list of tiles compiled // from Templates. Reverse the tilemap into Templates, and set into lvld. bool[,] afCellTaken = new bool[64, 64]; ArrayList alsTemplPos = new ArrayList(); Template[] atmpl = tmpd.GetTemplates(); for (int ty = 0; ty < tmap.Height; ty++) { for (int tx = 0; tx < tmap.Width; tx++) { // Cell mapped already? if (afCellTaken[ty, tx]) { continue; } // Cell not mapped. Create TemplatePos. int iTile = tmap.GetTileIndex(tx, ty); TileData tdata = tset.GetTileData(iTile); Template tmpl = atmpl[tdata.iTemplate]; // Don't bother with background tiles if (tmpl == tmpd.GetBackgroundTemplate()) { continue; } int txOrigin = tx - tdata.txTemplate; int tyOrigin = ty - tdata.tyTemplate; bool[,] afMapped = new bool[tmpl.Cty, tmpl.Ctx]; for (int tyTmpl = 0; tyTmpl < tmpl.Cty; tyTmpl++) { for (int txTmpl = 0; txTmpl < tmpl.Ctx; txTmpl++) { int txT = txOrigin + txTmpl; int tyT = tyOrigin + tyTmpl; if (txT < 0 || txT >= 64 || tyT < 0 || tyT >= 64) { continue; } if (afCellTaken[tyT, txT]) { continue; } int iTileT = tmap.GetTileIndex(txT, tyT); if (iTileT != -1) { TileData tdataT = tset.GetTileData(iTileT); if (tdataT.iTemplate != tdata.iTemplate) { continue; } if (tdataT.txTemplate != txTmpl || tdataT.tyTemplate != tyTmpl) { continue; } } afMapped[tyTmpl, txTmpl] = true; afCellTaken[tyT, txT] = true; } } alsTemplPos.Add(new TemplatePos(tmpl, txOrigin, tyOrigin, afMapped)); } } // Figure out the bounds. Rectangle rcBounds = new Rectangle((64 - tmap.Width) / 2, (64 - tmap.Height) / 2, tmap.Width, tmap.Height); lvld.Bounds = rcBounds; // The list of TemplatePos's has been created. Add to LevelDoc. ArrayList alsTiles = new ArrayList(); foreach (TemplatePos tpos in alsTemplPos) { Tile tile = new Tile(tpos.tmpl.Name, tpos.txOrigin + rcBounds.Left, tpos.tyOrigin + rcBounds.Top, tpos.afMapped, tpos.tmpl.OccupancyMap); alsTiles.Add(tile); } lvld.AddMapItems((IMapItem[])alsTiles.ToArray(typeof(IMapItem))); } public static void SaveExpansionPdb(string strFile, Document[] adoc, string strVersion) { // First save all level docs //annoying //DocManager.SaveAllModified(typeof(LevelDoc)); // Remember active document LevelDoc lvldActive = (LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc)); // Save documents adoc in an expansion .pdb. Expansion .pdbs need: // - .lvl, .tmap, .trmap, but not .tsets since these come from game .pdbs // - need a version.txt // - need an if demo trigger check "inserted" at save time // - .pdb needs WARI creator, ADD1 type // - data should be compressed for obfuscation purposes PdbPacker pdbp = new PdbPacker(); // Add version.txt byte[] abT = new byte[strVersion.Length + 1]; for (int n = 0; n < strVersion.Length; n++) abT[n] = (byte)strVersion[n]; abT[abT.Length - 1] = 0; pdbp.Add(new PdbPacker.File("version.txt", abT)); // Load res.h from embedded resource in prep for pre-process System.Reflection.Assembly ass = typeof(GobImage).Module.Assembly; Stream stmResDotH = ass.GetManifestResourceStream("m.EmbeddedResources." + "res.h"); if (stmResDotH == null) throw new Exception("Cannot load res.h"); // Compile levels Random rand = new Random(); ArrayList alsTileSets = new ArrayList(); foreach (LevelDoc lvld in adoc) { // Need to do this unfortunately; some of the "saving" code relies on what the "active" document // is!! DocManager.SetActiveDocument(typeof(LevelDoc), lvld); TemplateDoc tmpd = lvld.GetTemplateDoc(); // Get appropriate TileSet, or make one if this map // uses a new tile collection TileSet tset = null; foreach (TileSet tsetT in alsTileSets) { if (tsetT.TemplateDoc == tmpd) { tset = tsetT; break; } } // Create new tile set if none found if (tset == null) { tset = new TileSet(tmpd, tmpd.GetName() + ".tset"); alsTileSets.Add(tset); } #if false // Generate base file name for this level (this is never user-visible, but it should be // as unique as possible char[] achBase = new char[16]; for (int n = 0; n < achBase.Length; n++) { int nT = rand.Next() % (26 + 10); if (nT < 26) { achBase[n] = (char)(nT + 97); } else { achBase[n] = (char)(nT + 48 - 26); } } if (lvld.MaxPlayers > 1) { achBase[0] = 'm'; achBase[1] = '_'; } string strBase = new String(achBase); #else // This isn't unique which can cause problems due to how packfiles work. // Could change packfile api to accept .pdb parameter. // Note1: set next mission action requires predictable filename // Note2: mission sorting is based on filename, not title // Could put lots of "support" in to fix these problems, or just ship // it like this. // // Hack: filename length 29 // Maximum extension on filename: 7 string strBase = lvld.Title; if (strBase.Length > 29 - 7) strBase = strBase.Substring(0, 29 - 7); // If multiplayer, add "m_" to the name by losing the last two characters // so sort order is preserved if (lvld.MaxPlayers > 1) strBase = "m_" + strBase.Substring(0, strBase.Length - 2); #endif // Get tile map file for this level MemoryStream stmTmap = new MemoryStream(); TileMap tmap = TileMap.CreateFromImage(tset, lvld.GetMapBitmap(tmpd.TileSize, tmpd, true), tmpd.TileSize); tmap.Save(stmTmap); string strTmap = strBase + ".tmap"; pdbp.Add(new PdbPacker.File(strTmap, stmTmap.ToArray())); stmTmap.Close(); // Get the terrain map file for this level MemoryStream stmTRmap = new MemoryStream(); TerrainMap trmap = new TerrainMap(lvld.GetTerrainMap(tmpd.TileSize, tmpd, false)); trmap.Save(stmTRmap); string strTRmap = strBase + ".trmap"; pdbp.Add(new PdbPacker.File(strTRmap, stmTRmap.ToArray())); stmTRmap.Close(); // Save .ini file for this level doc MemoryStream stmLvld = new MemoryStream(); lvld.SaveIni(stmLvld, -1, strTmap, strTRmap, tmpd.GetName() + ".palbin", true); // Pre-process stmLvld.Seek(0, SeekOrigin.Begin); MemoryStream stmPreprocessed = Misc.PreprocessStream(stmLvld, stmResDotH); stmPreprocessed.Seek(0, SeekOrigin.Begin); Ini iniPreProcessed = new Ini(stmPreprocessed); MemoryStream stmLvldPreProcessedBinary = new MemoryStream(); iniPreProcessed.SaveBinary(stmLvldPreProcessedBinary); stmLvldPreProcessedBinary.Close(); string strLvlName = lvld.OutputFilename; if (strLvlName == null) { strLvlName = strBase + ".lvl"; } pdbp.Add(new PdbPacker.File(strLvlName, stmLvldPreProcessedBinary.ToArray())); stmLvldPreProcessedBinary.Close(); } stmResDotH.Close(); // Restore active document if (lvldActive != null) DocManager.SetActiveDocument(typeof(LevelDoc), lvldActive); // Now save out pdb pdbp.Save(strFile, "WARI", "ADD2"); } public static void MixMapImportSpecial(Theater theater, TemplateDoc tmpdCopyTerrain, string strFileSave) { TemplateDoc tmpd24 = (TemplateDoc)DocManager.NewDocument(typeof(TemplateDoc), new Object[] { new Size(24, 24) }); MixTemplate[] amixt = MixSuck.LoadTemplates(theater); MixSuck.ImportTemplates(amixt, tmpd24); Template[] atmpl24 = tmpd24.GetTemplates(); Template[] atmpl16 = tmpdCopyTerrain.GetTemplates(); for (int n = 0; n < atmpl24.Length; n++) { Template tmpl24 = atmpl24[n]; Template tmpl16 = atmpl16[n]; tmpl24.TerrainMap = tmpl16.TerrainMap; } tmpd24.SetBackgroundTemplate(atmpl24[0]); tmpd24.SaveAs(strFileSave); } public static void MakePalette(string[] astr) { // -makepal 16 templates.tc palsize fixpalsize backgroundpalsize fixed.pal out.pal // tile size Size sizTile = new Size(0, 0); sizTile.Width = int.Parse(astr[1]); sizTile.Height = sizTile.Width; // Load template collection TemplateDoc tmpd = (TemplateDoc)DocManager.OpenDocument(astr[2]); // palette size int cPalEntries = int.Parse(astr[3]); // entries fixed int cPalEntriesFixed = int.Parse(astr[4]); // entries for background int cPalEntriesBackground = int.Parse(astr[5]); // fixed palette Palette palFixed = new Palette(astr[6]); // output palette string strFilePalOut = astr[7]; // If this template collection already has a palette it has already been quantized; we don't // want that. if (tmpd.GetPalette() != null) new Exception("Template collection has already been quantized!"); // Scale templates if needed if (sizTile.Width != tmpd.TileSize.Width || sizTile.Height != tmpd.TileSize.Height) TemplateTools.ScaleTemplates(tmpd, sizTile); // Quantize TemplateTools.QuantizeTemplates(tmpd, palFixed, cPalEntries, cPalEntriesFixed, cPalEntriesBackground); // Save the new palette out Palette palNew = tmpd.GetPalette(); palNew.SaveJasc(strFilePalOut); } public static void ExportMixMaps(string[] astr) { // Expand filespecs ArrayList alsFiles = new ArrayList(); for (int n = 1; n < astr.Length; n++) { string strFileT = Path.GetFileName(astr[n]); string strDirT = Path.GetDirectoryName(astr[n]); if (strDirT == "") strDirT = "."; string[] astrFiles = Directory.GetFiles(strDirT, strFileT); alsFiles.AddRange(astrFiles); } foreach (string strFile in alsFiles) { LevelDoc lvld = (LevelDoc)DocManager.NewDocument(typeof(LevelDoc), null); Console.Write("Exporting " + strFile + " as "); string strFileExport = MixSuck.ImportExportMixMap(strFile, lvld); if (strFileExport == null) { Console.Write("Error exporting!\n"); } else { Console.Write(strFileExport + "\n"); } lvld.Dispose(); } } public static void ExportImages(string[] astr) { // Get directory //string strDir = Path.GetFullPath(astr[1]); string strDir = "."; string strPrefix = astr[1]; // Expand filespecs ArrayList alsFiles = new ArrayList(); for (int n = 2; n < astr.Length; n++) { string strFileT = Path.GetFileName(astr[n]); string strDirT = Path.GetDirectoryName(astr[n]); if (strDirT == "") strDirT = "."; string[] astrFiles = Directory.GetFiles(strDirT, strFileT); alsFiles.AddRange(astrFiles); } // Attempt to process these level docs foreach (string strFile in alsFiles) { Console.Write("Map of " + strFile + " -> "); LevelDoc lvld = (LevelDoc)DocManager.OpenDocument(strFile); if (lvld == null) throw new Exception("Could not load level doc " + strFile); string strPng = strDir + Path.DirectorySeparatorChar + strPrefix + Path.GetFileName(strFile).Replace(".ld", ".png"); Console.Write(strPng + "..."); TemplateDoc tmpd = lvld.GetTemplateDoc(); Bitmap bm = lvld.GetMapBitmap(tmpd.TileSize, tmpd, true); bm.Save(strPng, ImageFormat.Png); bm.Dispose(); lvld.Dispose(); Console.Write(" Done.\n"); } } public static void ExportLevels(string[] astr, int nVersion) { // Get tile size Size sizTile = new Size(0, 0); sizTile.Width = int.Parse(astr[1]); sizTile.Height = sizTile.Width; // Get depth int nDepth = Int32.Parse(astr[2]); // Get background threshold double nAreaBackgroundThreshold = double.Parse(astr[3]); // Background luminance multiplier double nLuminanceMultBackground = double.Parse(astr[4]); // Background saturation multiplier double nSaturationMultBackground = double.Parse(astr[5]); // Foreground luminance multiplier double nLuminanceMultForeground = double.Parse(astr[6]); // Foreground saturation multiplier double nSaturationMultForeground = double.Parse(astr[7]); // Palette directory string strPalDir = astr[8]; // Get output directory string strDir = Path.GetFullPath(astr[9]); // Expand filespecs ArrayList alsFiles = new ArrayList(); for (int n = 9; n < astr.Length; n++) { string strFileT = Path.GetFileName(astr[n]); string strDirT = Path.GetDirectoryName(astr[n]); if (strDirT == "") strDirT = "."; string[] astrFiles = Directory.GetFiles(strDirT, strFileT); alsFiles.AddRange(astrFiles); } // Attempt to process these level doc ArrayList alsTileSets = new ArrayList(); foreach (string strFile in alsFiles) { Console.Write("Loading " + strFile + "..."); LevelDoc lvld = (LevelDoc)DocManager.OpenDocument(strFile); if (lvld == null) throw new Exception("Could not load level doc " + strFile); Console.Write(" Done.\n"); // Size this template collection if necessary TemplateDoc tmpd = lvld.GetTemplateDoc(); if (sizTile.Width != tmpd.TileSize.Width || sizTile.Height != tmpd.TileSize.Height) TemplateTools.ScaleTemplates(tmpd, sizTile); // Get appropriate TileSet, or make one if this map // uses a new tile collection TileSet tset = null; foreach (TileSet tsetT in alsTileSets) { if (tsetT.TileCollectionFileName == Path.GetFileName(lvld.GetTemplateDoc().GetPath())) { tset = tsetT; break; } } // Create new tile set if none found if (tset == null) { string strTcPath = lvld.GetTemplateDoc().GetPath(); string strTcName = Path.GetFileNameWithoutExtension(strTcPath); string strTcDir = Path.GetDirectoryName(strTcPath); string strT3 = strTcDir + Path.DirectorySeparatorChar + strPalDir + Path.DirectorySeparatorChar + strTcName; tset = new TileSet(lvld.GetTemplateDoc(), Path.GetFileName(strTcPath), strT3, nDepth, sizTile); alsTileSets.Add(tset); } // Get and save a tile map for this level string strTmap = Path.GetFileName(lvld.GetPath().Replace(".ld", ".tmap")); string strFileTmap = strDir + Path.DirectorySeparatorChar + strTmap; Console.Write("Creating & writing " + strFileTmap + "..."); TileMap tmap = TileMap.CreateFromImage(tset, lvld.GetMapBitmap(tmpd.TileSize, tmpd, true), tmpd.TileSize); tmap.Save(strFileTmap); Console.Write(" Done.\n"); // Get and save terrain map for this level string strTrmap = Path.GetFileName(lvld.GetPath().Replace(".ld", ".trmap")); string strFileTrmap = strDir + Path.DirectorySeparatorChar + strTrmap; Console.Write("Creating & writing " + strFileTrmap + "..."); TerrainMap trmap = new TerrainMap(lvld.GetTerrainMap(tmpd.TileSize, tmpd, false)); trmap.Save(strFileTrmap); Console.Write(" Done.\n"); // Save .ini for this level doc string strFileIni = strDir + Path.DirectorySeparatorChar + Path.GetFileName(strFile).Replace(".ld", ".lvl"); Console.Write("Writing " + strFileIni + "..."); lvld.SaveIni(strFileIni, nVersion, strTmap, strTrmap, tset.PalBinFileName); Console.Write(" Done.\n"); lvld.Dispose(); } // Now write out tilesets foreach (TileSet tset in alsTileSets) { // Save tile set string strFileTset = strDir + Path.DirectorySeparatorChar + tset.FileName; Console.Write("Creating & writing " + strFileTset + ", " + tset.Count.ToString() + " tiles..."); tset.Save(strFileTset); tset.SaveMini(strFileTset, nAreaBackgroundThreshold, nLuminanceMultBackground, nSaturationMultBackground, nLuminanceMultForeground, nSaturationMultForeground); Console.Write(" Done.\n"); } } public static void ExportText(string[] astr) { // Expand filespecs ArrayList alsFiles = new ArrayList(); for (int n = 1; n < astr.Length; n++) { string strFileT = Path.GetFileName(astr[n]); string strDirT = Path.GetDirectoryName(astr[n]); if (strDirT == "") strDirT = "."; string[] astrFiles = Directory.GetFiles(strDirT, strFileT); alsFiles.AddRange(astrFiles); } Console.WriteLine("Exporting text from {0} files", alsFiles.Count); // Attempt to process these level docs foreach (string strFile in alsFiles) { Console.Write("Writing text of " + strFile + "..."); LevelDoc lvld = (LevelDoc)DocManager.OpenDocument(strFile); if (lvld == null) throw new Exception("Could not load level doc " + strFile); string strTextFile = "." + Path.DirectorySeparatorChar + Path.GetFileName(strFile).Replace(".ld", ".txt"); string str = lvld.GetLevelText(); str = str.Replace("\n", "\r\n"); StreamWriter stmw = new StreamWriter(strTextFile); stmw.Write(str); stmw.Close(); lvld.Dispose(); Console.WriteLine(" done"); } } public static void ImportText(string[] astr) { // Expand filespecs ArrayList alsFiles = new ArrayList(); for (int n = 1; n < astr.Length; n++) { string strFileT = Path.GetFileName(astr[n]); string strDirT = Path.GetDirectoryName(astr[n]); if (strDirT == "") strDirT = "."; string[] astrFiles = Directory.GetFiles(strDirT, strFileT); alsFiles.AddRange(astrFiles); } Console.WriteLine("Importing text from {0} files", alsFiles.Count); // Attempt to process these text files/level docs foreach (string strTextFile in alsFiles) { string strFile = "." + Path.DirectorySeparatorChar + Path.GetFileName(strTextFile).Replace(".txt", ".ld"); Console.Write("Writing " + strTextFile + " to " + strFile + "..."); LevelDoc lvld = (LevelDoc)DocManager.OpenDocument(strFile); if (lvld == null) throw new Exception("Could not load level doc " + strFile); StreamReader stmr = new StreamReader(strTextFile); string str = stmr.ReadToEnd(); stmr.Close(); str = str.Replace("\r\n", "\n"); int ichErrorPos; if (!lvld.SetLevelText(str, out ichErrorPos)) { Console.WriteLine(" error at char " + ichErrorPos); } else { lvld.Save(); Console.WriteLine(" saved"); } lvld.Dispose(); } } } class TerrainMap { private TerrainTypes[,] m_aterMap; public TerrainMap(TerrainTypes[,] aterMap) { m_aterMap = aterMap; } public void Save(string strFileTrmap) { Stream stm = new FileStream(strFileTrmap, FileMode.Create, FileAccess.Write, FileShare.None); Save(stm); } public void Save(Stream stm) { BinaryWriter bwtr = new BinaryWriter(stm); //struct TerrainMapHeader { // trmhdr // word ctx; // word cty; //}; bwtr.Write(Misc.SwapUShort((ushort)m_aterMap.GetLength(1))); bwtr.Write(Misc.SwapUShort((ushort)m_aterMap.GetLength(0))); for (int ty = 0; ty < m_aterMap.GetLength(0); ty++) { for (int tx = 0; tx < m_aterMap.GetLength(1); tx++) { byte b = 0; switch (m_aterMap[ty, tx]) { default: case TerrainTypes.Open: b = 1; break; case TerrainTypes.Area: b = 0; break; case TerrainTypes.Wall: b = 2; break; case TerrainTypes.Blocked: b = 3; break; } bwtr.Write(b); } } bwtr.Close(); } public static TerrainMap Load(MemoryStream stm) { BinaryReader brdr = new BinaryReader(stm); int ctx = (int)Misc.SwapUShort(brdr.ReadUInt16()); int cty = (int)Misc.SwapUShort(brdr.ReadUInt16()); TerrainTypes[,] map = new TerrainTypes[cty, ctx]; for (int ty = 0; ty < cty; ty++) { for (int tx = 0; tx < ctx; tx++) { byte b = brdr.ReadByte(); switch (b) { case 0: // Area map[ty, tx] = TerrainTypes.Area; break; case 1: // Open map[ty, tx] = TerrainTypes.Open; break; case 2: // Wall map[ty, tx] = TerrainTypes.Wall; break; case 3: // Blocked map[ty, tx] = TerrainTypes.Blocked; break; default: // Default to Open map[ty, tx] = TerrainTypes.Open; break; } } } brdr.Close(); return new TerrainMap(map); } public TerrainTypes[,] Map { get { return m_aterMap; } } } class TileMap { int m_ctx; int m_cty; Size m_sizTile; int[,] m_aiTile; string m_strTSetFileName; public TileMap(string strTSetFileName, int ctx, int cty, Size sizTile) { m_strTSetFileName = strTSetFileName; m_ctx = ctx; m_cty = cty; m_sizTile = sizTile; m_aiTile = new int[cty, ctx]; } public TileMap(string strTSetFileName, int ctx, int cty, int[,] aiTile, Size sizTile) { m_strTSetFileName = strTSetFileName; m_ctx = ctx; m_cty = cty; m_aiTile = aiTile; m_sizTile = sizTile; } public string Filename { get { return m_strTSetFileName; } } public int Width { get { return m_ctx; } } public int Height { get { return m_cty; } } public static TileMap CreateFromImage(TileSet tset, Bitmap bm, Size sizTile) { int ctx = bm.Width / sizTile.Width; int cty = bm.Height / sizTile.Height; TileMap tmap = new TileMap(tset.FileName, ctx, cty, sizTile); tmap.InitFromImage(tset, bm); return tmap; } public void InitFromImage(TileSet tset, Bitmap bm) { Color[] aclrTile = new Color[m_sizTile.Width * m_sizTile.Height]; for (int ty = 0; ty < m_cty; ty++) { for (int tx = 0; tx < m_ctx; tx++) { TileSet.ExtractTilePixels(bm, tx, ty, m_sizTile, ref aclrTile); int index = tset.FindTileIndex(aclrTile); if (index == -1) throw new Exception("Couldn't find tile index!"); m_aiTile[ty, tx] = index; } } } public void Save(string strFileTmap) { Stream stm = new FileStream(strFileTmap, FileMode.Create, FileAccess.Write, FileShare.None); Save(stm); } public void Save(Stream stm) { BinaryWriter bwtr = new BinaryWriter(stm); // #define kcbFilename 28 // struct TileMapHeader { // thdr // char szFnTset[kcbFilename]; // word ctx; // word cty; // }; char[] szFnTset = new char[28]; m_strTSetFileName.CopyTo(0, szFnTset, 0, m_strTSetFileName.Length); bwtr.Write(szFnTset); bwtr.Write(Misc.SwapUShort((ushort)m_ctx)); bwtr.Write(Misc.SwapUShort((ushort)m_cty)); for (int ty = 0; ty < m_cty; ty++) { for (int tx = 0; tx < m_ctx; tx++) { bwtr.Write(Misc.SwapUShort((ushort)(m_aiTile[ty, tx] << 2))); } } bwtr.Close(); } public static TileMap Load(MemoryStream stm) { BinaryReader brdr = new BinaryReader(stm); byte[] ab = brdr.ReadBytes(28); int i = 0; for (; i < ab.Length; i++) { if (ab[i] == 0) { break; } } string strFilename = Encoding.ASCII.GetString(ab, 0, i); int ctx = Misc.SwapUShort(brdr.ReadUInt16()); int cty = Misc.SwapUShort(brdr.ReadUInt16()); int [,] aiTile = new int[cty, ctx]; for (int ty = 0; ty < cty; ty++) { for (int tx = 0; tx < ctx; tx++) { aiTile[ty, tx] = Misc.SwapUShort(brdr.ReadUInt16()) >> 2; } } brdr.Close(); Size sizTile = new Size(24, 24); // hardwired return new TileMap(strFilename, ctx, cty, aiTile, sizTile); } public int GetTileIndex(int tx, int ty) { if (tx < 0 || tx >= m_aiTile.GetLength(1)) { return -1; } if (ty < 0 || ty >= m_aiTile.GetLength(0)) { return -1; } return m_aiTile[ty, tx]; } } struct TileData { public int hash; public Color[] aclr; public int iTemplate; public int txTemplate; public int tyTemplate; } class TileSet { public string FileName; public string TileCollectionFileName; public string PalBinFileName; public TemplateDoc TemplateDoc; private ArrayList m_alsTileData = new ArrayList(); private Palette m_pal = null; private static int s_cbFileMax = 32000; Size m_sizTile; public TileSet(TemplateDoc tmpd, string strFile) { TemplateDoc = tmpd; m_pal = tmpd.GetPalette(); m_sizTile = tmpd.TileSize; FileName = strFile.Replace(".tc", ".tset"); SuckTemplates(); } public TileSet(TemplateDoc tmpd, string strFile, string strFilePal, int nDepth, Size sizTile) { TemplateDoc = tmpd; m_pal = new Palette(strFilePal + "_" + nDepth.ToString() + "bpp.pal"); TileCollectionFileName = strFile; FileName = strFile.Replace(".tc", ".tset"); PalBinFileName = Path.GetFileName(strFilePal) + ".palbin"; m_sizTile = sizTile; SuckTemplates(); } private void SuckTemplates() { // Suck all the tiles in Template[] atmpl = TemplateDoc.GetTemplates(); int iTemplate = 0; foreach (Template tmpl in atmpl) { bool[,] afOccupancy = tmpl.OccupancyMap; for (int ty = 0; ty < afOccupancy.GetLength(0); ty++) { for (int tx = 0; tx < afOccupancy.GetLength(1); tx++) { if (!afOccupancy[ty, tx]) continue; TileData tdata = new TileData(); tdata.iTemplate = iTemplate; tdata.txTemplate = tx; tdata.tyTemplate = ty; tdata.aclr = new Color[m_sizTile.Width * m_sizTile.Height]; ExtractTilePixels(tmpl.Bitmap, tx, ty, m_sizTile, ref tdata.aclr); tdata.hash = HashTile(tdata.aclr); m_alsTileData.Add(tdata); } } iTemplate++; } } public static unsafe void ExtractTilePixels(Bitmap bm, int tx, int ty, Size sizTile, ref Color[] aclrTile) { Rectangle rcSrc = new Rectangle(tx * sizTile.Width, ty * sizTile.Height, sizTile.Width, sizTile.Height); BitmapData bmd = bm.LockBits(rcSrc, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); IntPtr p = bmd.Scan0; byte *pbBase = (byte *)p.ToPointer(); for (int y = 0; y < sizTile.Height; y++) { for (int x = 0; x < sizTile.Width; x++) { byte *pb = pbBase + y * bmd.Stride + x * 3; aclrTile[y * sizTile.Width + x] = Color.FromArgb(pb[2], pb[1], pb[0]); } } bm.UnlockBits(bmd); } public int FindTileIndex(Color[] aclrTile) { int hash = HashTile(aclrTile); for (int n = 0; n < m_alsTileData.Count; n++) { TileData td = (TileData)m_alsTileData[n]; if (hash == td.hash && CheckTileMatch(aclrTile, td.aclr)) return n; } return -1; } int HashTile(Color[] aclrTile) { int hash = 0; for (int n = 0; n < aclrTile.Length; n++) { Color clr = aclrTile[n]; hash += (hash << 1) | (clr.R << 16) + (clr.G << 8) + clr.B; } return hash; } bool CheckTileMatch(Color[] aclr1, Color[] aclr2) { for (int n = 0; n < aclr1.Length; n++) { if (aclr1[n] != aclr2[n]) return false; } return true; } public void Save(string strFileTset) { // struct TileSetHeader { // tshdr // ushort cTiles; // ushort cxTile; // ushort cyTile; // }; int cbTile = m_sizTile.Width * m_sizTile.Height; int cTilesFit = (s_cbFileMax - 6) / cbTile; int cTilesLeft = m_alsTileData.Count; int nFile = 0; int nTile = 0; while (cTilesLeft != 0) { // Get filename string strT = strFileTset; if (nFile > 0) strT = strFileTset.Replace(".tset", ".tset." + nFile.ToString()); nFile++; // Open file for writing Stream stm = new FileStream(strT, FileMode.Create, FileAccess.Write, FileShare.None); BinaryWriter bwtr = new BinaryWriter(stm); // Figure out how many tiles will go in this file int cTilesWrite = Math.Min(cTilesFit, cTilesLeft); // Write out the header bwtr.Write(Misc.SwapUShort((ushort)cTilesWrite)); bwtr.Write(Misc.SwapUShort((ushort)m_sizTile.Width)); bwtr.Write(Misc.SwapUShort((ushort)m_sizTile.Height)); // Write out the tiles for (int n = 0; n < cTilesWrite; n++) { bwtr.Write(GetTileBytes(nTile)); nTile++; } // Next file bwtr.Close(); cTilesLeft -= cTilesWrite; } } public void SaveMini(string strFileTset, double nAreaBackgroundThreshold, double nLuminanceMultBackground, double nSaturationMultBackground, double nLuminanceMultForeground, double nSaturationMultForeground) { // Now write out minimap tiles, 2x2 and 1x1 Stream stmT = new FileStream(strFileTset.Replace(".tset", ".tsetmini"), FileMode.Create, FileAccess.Write, FileShare.None); BinaryWriter bwtrMini = new BinaryWriter(stmT); WriteMiniTiles(bwtrMini, m_pal, TemplateDoc, 2, true, nAreaBackgroundThreshold, nLuminanceMultBackground, nSaturationMultBackground, nLuminanceMultForeground, nSaturationMultForeground); WriteMiniTiles(bwtrMini, m_pal, TemplateDoc, 1, false, nAreaBackgroundThreshold, nLuminanceMultBackground, nSaturationMultBackground, nLuminanceMultForeground, nSaturationMultForeground); bwtrMini.Close(); } void WriteMiniTiles(BinaryWriter bwtr, Palette pal, TemplateDoc tmpd, int cx, bool fNext, double nAreaBackgroundThreshold, double nLuminanceMultBackground, double nSaturationMultBackground, double nLuminanceMultForeground, double nSaturationMultForeground) { // struct MiniTileSetHeader { // mtshdr // ushort offNext; // ushort cTiles; // ushort cxTile; // ushort cyTile; // }; ushort offNext = 0; if (fNext) offNext = (ushort)(8 + m_alsTileData.Count * cx * cx); bwtr.Write(Misc.SwapUShort(offNext)); bwtr.Write(Misc.SwapUShort((ushort)m_alsTileData.Count)); bwtr.Write(Misc.SwapUShort((ushort)cx)); bwtr.Write(Misc.SwapUShort((ushort)cx)); // If a background template exists, use it to distinguish foreground from background objects for better minimaps Size sizTile = tmpd.TileSize; ArrayList alsColors = new ArrayList(); Template tmplBackground = tmpd.GetBackgroundTemplate(); if (tmplBackground != null && nAreaBackgroundThreshold >= 0.0) { // Get despeckled hue map of background, calc mean and // std dev for filtering purposes Bitmap bmHueBackground = TemplateTools.MakeHueMap(tmplBackground.Bitmap); TemplateTools.DespeckleGrayscaleBitmap(bmHueBackground, 9, 50); double nMean = TemplateTools.CalcGrayscaleMean(bmHueBackground); double nStdDev = TemplateTools.CalcGrayscaleStandardDeviation(bmHueBackground, nMean); // Go through each tile, first make a mask that'll delineate foreground from background Bitmap bmTile = new Bitmap(sizTile.Width, sizTile.Height); foreach (TileData td in m_alsTileData) { // Need to turn data back into a bitmap - doh! for (int y = 0; y < sizTile.Height; y++) { for (int x = 0; x < sizTile.Width; x++) { Color clr = (Color)td.aclr[y * sizTile.Width + x]; bmTile.SetPixel(x, y, clr); } } // Create mask which'll replace background with transparent color (255, 0, 255) Bitmap bmMask = TemplateTools.MakeHueMap(bmTile); TemplateTools.DespeckleGrayscaleBitmap(bmMask, 9, 50); TemplateTools.SubtractGrayscaleDistribution(bmMask, nMean, nStdDev); // Now scale tile down to desired size, using mask as input Bitmap bmScaled = TemplateTools.ScaleTemplateBitmap(bmTile, bmMask, cx, cx, nAreaBackgroundThreshold, nLuminanceMultBackground, nSaturationMultBackground, nLuminanceMultForeground, nSaturationMultForeground); // Grab the data for (int y = 0; y < cx; y++) { for (int x = 0; x < cx; x++) { alsColors.Add(bmScaled.GetPixel(x, y)); } } bmScaled.Dispose(); bmMask.Dispose(); } } else { // No background template; just scale Bitmap bmTile = new Bitmap(sizTile.Width, sizTile.Height); foreach (TileData td in m_alsTileData) { // Need to turn data back into a bitmap - doh! for (int y = 0; y < sizTile.Height; y++) { for (int x = 0; x < sizTile.Width; x++) { Color clr = (Color)td.aclr[y * sizTile.Width + x]; bmTile.SetPixel(x, y, clr); } } // Now scale tile down to desired size, using mask as input Bitmap bmScaled = TemplateTools.ScaleTemplateBitmap(bmTile, null, cx, cx, 1.0, 1.0, 1.0, 1.0, 1.0); // Grab the data for (int y = 0; y < cx; y++) { for (int x = 0; x < cx; x++) { alsColors.Add(bmScaled.GetPixel(x, y)); } } bmScaled.Dispose(); } } // Palette match and write results foreach (Color clr in alsColors) bwtr.Write((byte)pal.FindClosestEntry(clr)); } byte[] GetTileBytes(int nTile) { byte[] ab = new byte[m_sizTile.Width * m_sizTile.Height]; TileData tdata = (TileData)m_alsTileData[nTile]; for (int n = 0; n < tdata.aclr.Length; n++) ab[n] = (byte)m_pal.FindClosestEntry(tdata.aclr[n]); return ab; } public int Count { get { return m_alsTileData.Count; } } public TileData GetTileData(int iTile) { return (TileData)m_alsTileData[iTile]; } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Globalization; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// This abstract class handles opening, saving of items in the hierarchy. /// </summary> internal abstract class DocumentManager { #region fields private readonly HierarchyNode node = null; #endregion #region properties protected HierarchyNode Node { get { return this.node; } } #endregion #region ctors protected DocumentManager(HierarchyNode node) { Utilities.ArgumentNotNull("node", node); this.node = node; } #endregion #region virtual methods /// <summary> /// Open a document using the standard editor. This method has no implementation since a document is abstract in this context /// </summary> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager class for an implementation of this method</remarks> public virtual int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Open a document using a specific editor. This method has no implementation. /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="frame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager for an implementation of this method</remarks> public virtual int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Open a document using a specific editor. This method has no implementation. /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="frame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager for an implementation of this method</remarks> public virtual int ReOpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { return OpenWithSpecific(editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out frame, windowFrameAction); } /// <summary> /// Close an open document window /// </summary> /// <param name="closeFlag">Decides how to close the document</param> /// <returns>S_OK if successful, otherwise an error is returned</returns> public virtual int Close(__FRAMECLOSE closeFlag) { if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.IsClosing) { return VSConstants.E_FAIL; } if (IsOpenedByUs) { IVsUIShellOpenDocument shell = this.Node.ProjectMgr.Site.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; Guid logicalView = Guid.Empty; uint grfIDO = 0; IVsUIHierarchy pHierOpen; uint[] itemIdOpen = new uint[1]; IVsWindowFrame windowFrame; int fOpen; ErrorHandler.ThrowOnFailure(shell.IsDocumentOpen(this.Node.ProjectMgr, this.Node.ID, this.Node.Url, ref logicalView, grfIDO, out pHierOpen, itemIdOpen, out windowFrame, out fOpen)); if (windowFrame != null) { return windowFrame.CloseFrame((uint)closeFlag); } } return VSConstants.S_OK; } /// <summary> /// Silently saves an open document /// </summary> /// <param name="saveIfDirty">Save the open document only if it is dirty</param> /// <remarks>The call to SaveDocData may return Microsoft.VisualStudio.Shell.Interop.PFF_RESULTS.STG_S_DATALOSS to indicate some characters could not be represented in the current codepage</remarks> public virtual void Save(bool saveIfDirty) { if (saveIfDirty && IsDirty) { IVsPersistDocData persistDocData = DocData; if (persistDocData != null) { string name; int cancelled; ErrorHandler.ThrowOnFailure(persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out name, out cancelled)); } } } #endregion /// <summary> /// Queries the RDT to see if the document is currently edited and not saved. /// </summary> public bool IsDirty { get { #if DEV12_OR_LATER var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(node.GetMkDocument())) { return false; } return docTable.IsDocumentDirty(docTable.GetDocumentCookie(node.GetMkDocument())); #else bool isOpen, isDirty, isOpenedByUs; uint docCookie; IVsPersistDocData persistDocData; GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData); return isDirty; #endif } } /// <summary> /// Queries the RDT to see if the document was opened by our project. /// </summary> public bool IsOpenedByUs { get { #if DEV12_OR_LATER var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(node.GetMkDocument())) { return false; } IVsHierarchy hierarchy; uint itemId; docTable.GetDocumentHierarchyItem( docTable.GetDocumentCookie(node.GetMkDocument()), out hierarchy, out itemId ); return Utilities.IsSameComObject(node.ProjectMgr, hierarchy); #else bool isOpen, isDirty, isOpenedByUs; uint docCookie; IVsPersistDocData persistDocData; GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData); return isOpenedByUs; #endif } } /// <summary> /// Returns the doc cookie in the RDT for the associated file. /// </summary> public uint DocCookie { get { #if DEV12_OR_LATER var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(node.GetMkDocument())) { return (uint)ShellConstants.VSDOCCOOKIE_NIL; } return docTable.GetDocumentCookie(node.GetMkDocument()); #else bool isOpen, isDirty, isOpenedByUs; uint docCookie; IVsPersistDocData persistDocData; GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData); return docCookie; #endif } } /// <summary> /// Returns the IVsPersistDocData associated with the document, or null if there isn't one. /// </summary> public IVsPersistDocData DocData { get { #if DEV12_OR_LATER var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)); if (!docTable.IsMonikerValid(node.GetMkDocument())) { return null; } return docTable.GetDocumentData(docTable.GetDocumentCookie(node.GetMkDocument())) as IVsPersistDocData; #else bool isOpen, isDirty, isOpenedByUs; uint docCookie; IVsPersistDocData persistDocData; GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData); return persistDocData; #endif } } #region helper methods #if !DEV12_OR_LATER /// <summary> /// Get document properties from RDT /// </summary> private void GetDocInfo( out bool isOpen, // true if the doc is opened out bool isDirty, // true if the doc is dirty out bool isOpenedByUs, // true if opened by our project out uint docCookie, // VSDOCCOOKIE if open out IVsPersistDocData persistDocData) { isOpen = isDirty = isOpenedByUs = false; docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL; persistDocData = null; if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed) { return; } IVsHierarchy hierarchy; uint vsitemid = VSConstants.VSITEMID_NIL; VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectMgr.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie); if (hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL) { return; } isOpen = true; // check if the doc is opened by another project if (Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy)) { isOpenedByUs = true; } if (persistDocData != null) { int isDocDataDirty; ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty)); isDirty = (isDocDataDirty != 0); } } #endif protected string GetOwnerCaption() { Debug.Assert(this.node != null, "No node has been initialized for the document manager"); object pvar; ErrorHandler.ThrowOnFailure(node.ProjectMgr.GetProperty(node.ID, (int)__VSHPROPID.VSHPROPID_Caption, out pvar)); return (pvar as string); } protected static void CloseWindowFrame(ref IVsWindowFrame windowFrame) { if (windowFrame != null) { try { ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame(0)); } finally { windowFrame = null; } } } protected string GetFullPathForDocument() { string fullPath = String.Empty; // Get the URL representing the item fullPath = this.node.GetMkDocument(); Debug.Assert(!String.IsNullOrEmpty(fullPath), "Could not retrive the fullpath for the node" + this.Node.ID.ToString(CultureInfo.CurrentCulture)); return fullPath; } #endregion #region static methods /// <summary> /// Updates the caption for all windows associated to the document. /// </summary> /// <param name="site">The service provider.</param> /// <param name="caption">The new caption.</param> /// <param name="docData">The IUnknown interface to a document data object associated with a registered document.</param> public static void UpdateCaption(IServiceProvider site, string caption, IntPtr docData) { Utilities.ArgumentNotNull("site", site); if (String.IsNullOrEmpty(caption)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "caption"); } IVsUIShell uiShell = site.GetService(typeof(SVsUIShell)) as IVsUIShell; // We need to tell the windows to update their captions. IEnumWindowFrames windowFramesEnum; ErrorHandler.ThrowOnFailure(uiShell.GetDocumentWindowEnum(out windowFramesEnum)); IVsWindowFrame[] windowFrames = new IVsWindowFrame[1]; uint fetched; while (windowFramesEnum.Next(1, windowFrames, out fetched) == VSConstants.S_OK && fetched == 1) { IVsWindowFrame windowFrame = windowFrames[0]; object data; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out data)); IntPtr ptr = Marshal.GetIUnknownForObject(data); try { if (ptr == docData) { ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption)); } } finally { if (ptr != IntPtr.Zero) { Marshal.Release(ptr); } } } } /// <summary> /// Rename document in the running document table from oldName to newName. /// </summary> /// <param name="provider">The service provider.</param> /// <param name="oldName">Full path to the old name of the document.</param> /// <param name="newName">Full path to the new name of the document.</param> /// <param name="newItemId">The new item id of the document</param> public static void RenameDocument(IServiceProvider site, string oldName, string newName, uint newItemId) { Utilities.ArgumentNotNull("site", site); if (String.IsNullOrEmpty(oldName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "oldName"); } if (String.IsNullOrEmpty(newName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "newName"); } if (newItemId == VSConstants.VSITEMID_NIL) { throw new ArgumentNullException("newItemId"); } IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; IVsUIShellOpenDocument doc = site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (pRDT == null || doc == null) return; IVsHierarchy pIVsHierarchy; uint itemId; IntPtr docData; uint uiVsDocCookie; ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie)); if (docData != IntPtr.Zero && pIVsHierarchy != null) { try { IntPtr pUnk = Marshal.GetIUnknownForObject(pIVsHierarchy); Guid iid = typeof(IVsHierarchy).GUID; IntPtr pHier; Marshal.QueryInterface(pUnk, ref iid, out pHier); try { ErrorHandler.ThrowOnFailure(pRDT.RenameDocument(oldName, newName, pHier, newItemId)); } finally { if (pHier != IntPtr.Zero) Marshal.Release(pHier); if (pUnk != IntPtr.Zero) Marshal.Release(pUnk); } } finally { Marshal.Release(docData); } } } #endregion } }
// --------------------------------------------------------------------------- // <copyright file="TethysAppConfig2.cs" company="Tethys"> // Copyright (C) 1998-2021 T. Graf // </copyright> // // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 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. // --------------------------------------------------------------------------- // ReSharper disable once CheckNamespace namespace Tethys.App { using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Linq; /// <summary> /// This class stores the application configuration. At the beginning /// of the application all the properties are read from either the /// registry or an XML fileName. At the end of the application the data /// is stored again. /// </summary> public class TethysAppConfig2 : TethysAppConfigBase { #region PUBLIC PROPERTIES #endregion // PUBLIC PROPERTIES //// --------------------------------------------------------------------- #region CONSTRUCTION /// <summary> /// Initializes a new instance of the <see cref="TethysAppConfig2"/> class. /// </summary> /// <param name="applicationAssembly">The application assembly.</param> public TethysAppConfig2(Assembly applicationAssembly) : base(applicationAssembly) { } // TethysAppConfig2() #endregion // CONSTRUCTION //// --------------------------------------------------------------------- #region PROTECTED METHODS #region VIRTUAL (EMPTY) METHODS /// <summary> /// Reads the application configuration from a string. /// </summary> /// <param name="fileContents">The file contents.</param> /// <returns>The function returns true if all configuration data has /// been successfully read; otherwise false will be returned. /// </returns> protected virtual bool ReadFromString(string fileContents) { return true; } // ReadFromString() /// <summary> /// Writes the configuration to an <see cref="XDocument"/>. /// </summary> /// <returns>An <see cref="XDocument"/>.</returns> public virtual XDocument WriteToXDocument() { return null; } // WriteToXDocument() #endregion // VIRTUAL (EMPTY) METHODS #endregion // PROTECTED METHODS //// --------------------------------------------------------------------- #region PUBLIC METHODS /// <summary> /// This function writes the (user dependent) application configuration /// to an XML file that is located in the path for the application data /// of a roaming user, i.e. something like: /// Base Path\CompanyName\ProductName\filename. /// </summary> /// <param name="fileName">Name of the XML fileName to be used.</param> public void WriteToFile(string fileName) { // generate complete filename fileName = this.GetCompleteFilename(fileName); // we have to delete the previous files, because if (File.Exists(fileName)) { File.Delete(fileName); } // if using (var stream = File.OpenWrite(fileName)) { this.WriteToFile(stream); } // using } // WriteToFile() /// <summary> /// This function writes the (user dependent) application configuration to /// the given file stream. /// </summary> /// <param name="stream">The stream.</param> public void WriteToFile(Stream stream) { using (var sw = new StreamWriter(stream, this.Encoding)) { var xdoc = this.WriteToXDocument(); xdoc?.Save(sw); sw.Flush(); } // using } // WriteToFile() /// <summary> /// This function reads the (user dependent) application configuration /// from a XML file that is located in the path for the application data /// of a roaming user, i.e. something like: /// Base Path\CompanyName\ProductName\filename. /// </summary> /// <param name="fileName">Name of the XML fileName to be used.</param> /// <returns>The function returns true if all configuration data has /// been successfully read; otherwise false will be returned. /// </returns> public bool ReadFromFile(string fileName) { // generate complete filename fileName = this.GetCompleteFilename(fileName); var encoding = this.Encoding; using (var stream = File.OpenRead(fileName)) { return this.ReadFromFile(stream, encoding); } // using } // ReadFromFile() /// <summary> /// This function reads the (user dependent) application configuration /// from a XML file using the given encoding. /// </summary> /// <param name="stream">The stream.</param> /// <param name="encoding">The encoding.</param> /// <returns>The function returns true if all configuration data has /// been successfully read; otherwise false will be returned. /// </returns> public bool ReadFromFile(Stream stream, Encoding encoding) { using (var sr = new StreamReader(stream, encoding)) { return this.ReadFromString(sr.ReadToEnd()); } // using } // ReadFromFile() //// ===== Taken from Tethys.XmlSupport ===== /// <summary> /// Gets the attribute value. /// </summary> /// <param name="parent">The parent.</param> /// <param name="name">The name.</param> /// <param name="throwException">if set to <c>true</c> throws an exception /// if the node was not found.</param> /// <returns>The requested attribute value.</returns> public static string GetAttributeValue(XElement parent, string name, bool throwException = true) { var attribute = parent.Attributes().FirstOrDefault(e => e.Name.LocalName == name); if (attribute == null) { if (throwException) { throw new XmlException($"No attribute '{name}' found!"); } // if return null; } // if return attribute.Value; } // GetAttributeValue() /// <summary> /// Gets the first sub node. /// </summary> /// <param name="parent">The parent.</param> /// <param name="name">The name.</param> /// <param name="throwException">if set to <c>true</c> throws an exception /// if the node was not found.</param> /// <returns>The requested sub node.</returns> public static XElement GetFirstSubNode(XContainer parent, string name, bool throwException = true) { var nodes = parent.Elements().Where(e => e.Name.LocalName == name); var xnode = nodes.FirstOrDefault(); if ((xnode == null) && throwException) { throw new XmlException($"No node '{name}' found!"); } // if return xnode; } // GetFirstSubNode() /// <summary> /// Gets the value of the first sub node with the given name. /// </summary> /// <param name="parent">The parent.</param> /// <param name="name">The name.</param> /// <param name="throwException">if set to <c>true</c> throws an exception /// if the node was not found.</param> /// <returns>The requested sub node value as string.</returns> public static string GetFirstSubNodeValue(XContainer parent, string name, bool throwException = true) { var nodes = parent.Elements().Where(e => e.Name.LocalName == name); var xnode = nodes.FirstOrDefault(); if (xnode == null) { if (throwException) { throw new XmlException($"No node '{name}' found!"); } // if return null; } // if return xnode.Value; } // GetFirstSubNode() #endregion // PUBLIC METHODS } // TethysAppConfig2 } // Tethys.App
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SouthwindRepository{ /// <summary> /// Strongly-typed collection for the SalesByCategory class. /// </summary> [Serializable] public partial class SalesByCategoryCollection : ReadOnlyList<SalesByCategory, SalesByCategoryCollection> { public SalesByCategoryCollection() {} } /// <summary> /// This is Read-only wrapper class for the sales by category view. /// </summary> [Serializable] public partial class SalesByCategory : ReadOnlyRecord<SalesByCategory>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("sales by category", TableType.View, DataService.GetInstance("SouthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema); colvarCategoryID.ColumnName = "CategoryID"; colvarCategoryID.DataType = DbType.Int32; colvarCategoryID.MaxLength = 10; colvarCategoryID.AutoIncrement = false; colvarCategoryID.IsNullable = false; colvarCategoryID.IsPrimaryKey = false; colvarCategoryID.IsForeignKey = false; colvarCategoryID.IsReadOnly = false; schema.Columns.Add(colvarCategoryID); TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema); colvarCategoryName.ColumnName = "CategoryName"; colvarCategoryName.DataType = DbType.String; colvarCategoryName.MaxLength = 15; colvarCategoryName.AutoIncrement = false; colvarCategoryName.IsNullable = false; colvarCategoryName.IsPrimaryKey = false; colvarCategoryName.IsForeignKey = false; colvarCategoryName.IsReadOnly = false; schema.Columns.Add(colvarCategoryName); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarProductSales = new TableSchema.TableColumn(schema); colvarProductSales.ColumnName = "ProductSales"; colvarProductSales.DataType = DbType.Decimal; colvarProductSales.MaxLength = 0; colvarProductSales.AutoIncrement = false; colvarProductSales.IsNullable = true; colvarProductSales.IsPrimaryKey = false; colvarProductSales.IsForeignKey = false; colvarProductSales.IsReadOnly = false; schema.Columns.Add(colvarProductSales); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["SouthwindRepository"].AddSchema("sales by category",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public SalesByCategory() { SetSQLProps(); SetDefaults(); MarkNew(); } public SalesByCategory(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public SalesByCategory(object keyID) { SetSQLProps(); LoadByKey(keyID); } public SalesByCategory(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("CategoryID")] [Bindable(true)] public int CategoryID { get { return GetColumnValue<int>("CategoryID"); } set { SetColumnValue("CategoryID", value); } } [XmlAttribute("CategoryName")] [Bindable(true)] public string CategoryName { get { return GetColumnValue<string>("CategoryName"); } set { SetColumnValue("CategoryName", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("ProductSales")] [Bindable(true)] public decimal? ProductSales { get { return GetColumnValue<decimal?>("ProductSales"); } set { SetColumnValue("ProductSales", value); } } #endregion #region Columns Struct public struct Columns { public static string CategoryID = @"CategoryID"; public static string CategoryName = @"CategoryName"; public static string ProductName = @"ProductName"; public static string ProductSales = @"ProductSales"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using System; using System.Collections.Generic; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; using InitializrBootstrap.Models.Sitemap; using MvcSiteMapProvider; using MvcSiteMapProvider.Web.Html; namespace InitializrBootstrap.Extensions.Sitemap { /// <summary> /// MvcSiteMapHtmlHelper extension methods /// </summary> public static class NavExtensions { /// <summary> /// Source metadata /// </summary> private static Dictionary<string, object> NavSourceMetadata = new Dictionary<string, object> { { "HtmlHelper", typeof(NavExtensions).FullName } }; /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper) { return Nav(helper, helper.Provider.RootNode, true, true, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, bool showStartingNode) { return Nav(helper, helper.Provider.RootNode, true, showStartingNode, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode) { return Nav(helper, startingNode, startingNodeInChildLevel, showStartingNode, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startFromCurrentNode">Start from current node if set to <c>true</c>.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, bool startFromCurrentNode, bool startingNodeInChildLevel, bool showStartingNode) { SiteMapNode startingNode = startFromCurrentNode ? GetCurrentNode(helper.Provider) : helper.Provider.RootNode; return Nav(helper, startingNode, startingNodeInChildLevel, showStartingNode, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="allowForwardSearch">if set to <c>true</c> allow forward search. Forward search will search all parent nodes and child nodes, where in other circumstances only parent nodes are searched.</param> /// <param name="drillDownToContent">if set to <c>true</c> [drill down to content].</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, int startingNodeLevel, int maxDepth, bool allowForwardSearch, bool drillDownToContent) { SiteMapNode startingNode = GetStartingNode(GetCurrentNode(helper.Provider), startingNodeLevel, allowForwardSearch); if (startingNode == null) { return MvcHtmlString.Empty; } return Nav(helper, startingNode, true, false, maxDepth + 1, drillDownToContent); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, int startingNodeLevel, int maxDepth) { return Nav(helper, startingNodeLevel, maxDepth, false, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="allowForwardSearch">if set to <c>true</c> allow forward search. Forward search will search all parent nodes and child nodes, where in other circumstances only parent nodes are searched.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, int startingNodeLevel, int maxDepth, bool allowForwardSearch) { return Nav(helper, startingNodeLevel, maxDepth, allowForwardSearch, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="allowForwardSearch">if set to <c>true</c> allow forward search. Forward search will search all parent nodes and child nodes, where in other circumstances only parent nodes are searched.</param> /// <param name="drillDownToContent">if set to <c>true</c> [drill down to content].</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, int startingNodeLevel, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth, bool allowForwardSearch, bool drillDownToContent) { SiteMapNode startingNode = GetStartingNode(GetCurrentNode(helper.Provider), startingNodeLevel, allowForwardSearch); if (startingNode == null) { return MvcHtmlString.Empty; } return Nav(helper, startingNode, startingNodeInChildLevel, showStartingNode, maxDepth + 1, drillDownToContent); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, int startingNodeLevel, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth) { return Nav(helper, startingNodeLevel, startingNodeInChildLevel, showStartingNode, maxDepth, false, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="drillDownToContent">if set to <c>true</c> [drill down to content].</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth, bool drillDownToContent) { return Nav(helper, null, startingNode, startingNodeInChildLevel, showStartingNode, maxDepth, drillDownToContent); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth) { return Nav(helper, startingNode, startingNodeInChildLevel, showStartingNode, maxDepth, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName) { return Nav(helper, templateName, helper.Provider.RootNode, true, true, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, bool showStartingNode) { return Nav(helper, templateName, helper.Provider.RootNode, true, showStartingNode, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode) { return Nav(helper, templateName, startingNode, startingNodeInChildLevel, showStartingNode, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startFromCurrentNode">Start from current node if set to <c>true</c>.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, bool startFromCurrentNode, bool startingNodeInChildLevel, bool showStartingNode) { SiteMapNode startingNode = startFromCurrentNode ? GetCurrentNode(helper.Provider) : helper.Provider.RootNode; return Nav(helper, templateName, startingNode, startingNodeInChildLevel, showStartingNode, Int32.MaxValue, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="allowForwardSearch">if set to <c>true</c> allow forward search. Forward search will search all parent nodes and child nodes, where in other circumstances only parent nodes are searched.</param> /// <param name="drillDownToCurrent">Should the model exceed the maxDepth to reach the current node</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, int startingNodeLevel, int maxDepth, bool allowForwardSearch, bool drillDownToCurrent) { SiteMapNode startingNode = GetStartingNode(GetCurrentNode(helper.Provider), startingNodeLevel, false); if (startingNode == null) { return MvcHtmlString.Empty; } return Nav(helper, templateName, startingNode, true, true, maxDepth + 1, drillDownToCurrent); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, int startingNodeLevel, int maxDepth) { return Nav(helper, templateName, startingNodeLevel, maxDepth, false, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="allowForwardSearch">if set to <c>true</c> allow forward search. Forward search will search all parent nodes and child nodes, where in other circumstances only parent nodes are searched.</param> /// <param name="drillDownToCurrent">Should the model exceed the maxDepth to reach the current node</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, int startingNodeLevel, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth, bool allowForwardSearch, bool drillDownToCurrent) { SiteMapNode startingNode = GetStartingNode(GetCurrentNode(helper.Provider), startingNodeLevel, allowForwardSearch); if (startingNode == null) { return MvcHtmlString.Empty; } return Nav(helper, templateName, startingNode, startingNodeInChildLevel, showStartingNode, maxDepth + 1, drillDownToCurrent); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, int startingNodeLevel, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth) { return Nav(helper, templateName, startingNodeLevel, startingNodeInChildLevel, showStartingNode, maxDepth, false, false); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="drillDownToCurrent">Should the model exceed the maxDepth to reach the current node</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth, bool drillDownToCurrent) { var model = BuildModel(helper, startingNode, startingNodeInChildLevel, showStartingNode, maxDepth, drillDownToCurrent); return helper .CreateHtmlHelperForModel(model) .DisplayFor(m => model, "Sitemap/Nav"); } /// <summary> /// Build a menu, based on the MvcSiteMap /// </summary> /// <param name="helper">The helper.</param> /// <param name="templateName">Name of the template.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Show starting node in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>Html markup</returns> public static MvcHtmlString Nav(this MvcSiteMapHtmlHelper helper, string templateName, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth) { return Nav(helper, templateName, startingNode, startingNodeInChildLevel, showStartingNode, maxDepth, false); } /// <summary> /// Builds the model. /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Renders startingNode in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <param name="drillDownToCurrent">Should the model exceed the maxDepth to reach the current node</param> /// <returns>The model.</returns> private static NavHelperModel BuildModel(MvcSiteMapHtmlHelper helper, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth, bool drillDownToCurrent) { // Build model var model = new NavHelperModel(); var node = startingNode; // Check if a starting node has been given if (node == null) { return model; } var mvcNode = node as MvcSiteMapNode; bool continueBuilding = ReachedMaximalNodelevel(maxDepth, node, drillDownToCurrent); // Check if maximal node level has not been reached if (!continueBuilding) { return model; } // Check visibility bool nodeVisible = true; if (mvcNode != null) { nodeVisible = mvcNode.VisibilityProvider.IsVisible( node, HttpContext.Current, NavSourceMetadata); } // Check ACL if (node.IsAccessibleToUser(HttpContext.Current)) { // Add node? var nodeToAdd = SiteMapNodeModelMapper.MapToSiteMapNodeModel(node, mvcNode, NavSourceMetadata); if (nodeVisible) { if (showStartingNode || !startingNodeInChildLevel) { model.Nodes.Add(nodeToAdd); } } // Add child nodes if (node.HasChildNodes) { foreach (SiteMapNode childNode in node.ChildNodes) { var childNodes = BuildModel(helper, childNode, false, true, maxDepth - 1, drillDownToCurrent).Nodes; foreach (var childNodeToAdd in childNodes) { if (!startingNodeInChildLevel) { nodeToAdd.Children.Add(childNodeToAdd); } else { model.Nodes.Add(childNodeToAdd); } } } } } return model; } /// <summary> /// Builds the model. /// </summary> /// <param name="helper">The helper.</param> /// <param name="startingNode">The starting node.</param> /// <param name="startingNodeInChildLevel">Renders startingNode in child level if set to <c>true</c>.</param> /// <param name="showStartingNode">Show starting node if set to <c>true</c>.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>The model.</returns> private static NavHelperModel BuildModel(MvcSiteMapHtmlHelper helper, SiteMapNode startingNode, bool startingNodeInChildLevel, bool showStartingNode, int maxDepth) { return BuildModel(helper, startingNode, startingNodeInChildLevel, showStartingNode, maxDepth, false); } public static SiteMapNode GetCurrentNode(SiteMapProvider selectedSiteMapProvider) { // get the node matching the current URL location var currentNode = selectedSiteMapProvider.CurrentNode; // if there is no node matching the current URL path, // remove parts until we get a hit if (currentNode == null) { var url = HttpContext.Current.Request.Url.LocalPath; while (url.Length > 0) { // see if we can find a matching node currentNode = selectedSiteMapProvider.FindSiteMapNode(url); // if we get a hit, stop if (currentNode != null) break; // if not, remove the last path item var lastSlashlocation = url.LastIndexOf("/"); if (lastSlashlocation < 0) break; // protects us from malformed URLs url = url.Remove(lastSlashlocation); } } return currentNode; } /// <summary> /// Gets the starting node. /// </summary> /// <param name="currentNode">The current node.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <param name="allowForwardSearch">if set to <c>true</c> allow forward search. Forward search will search all parent nodes and child nodes, where in other circumstances only parent nodes are searched.</param> /// <returns>The starting node.</returns> public static SiteMapNode GetStartingNode(SiteMapNode currentNode, int startingNodeLevel, bool allowForwardSearch) { SiteMapNode startingNode = GetNodeAtLevel(currentNode, startingNodeLevel, allowForwardSearch); if (startingNode == null) { return null; } if (startingNode.ParentNode != null) { startingNode = startingNode.ParentNode; } return startingNode; } /// <summary> /// Gets the starting node. /// </summary> /// <param name="currentNode">The current node.</param> /// <param name="startingNodeLevel">The starting node level.</param> /// <returns>The starting node.</returns> public static SiteMapNode GetStartingNode(SiteMapNode currentNode, int startingNodeLevel) { return GetStartingNode(currentNode, startingNodeLevel, false); } /// <summary> /// Gets the node at level. /// </summary> /// <param name="startingNode">The starting node.</param> /// <param name="level">The level.</param> /// <param name="allowForwardSearch">if set to <c>true</c> allow forward search. Forward search will search all parent nodes and child nodes, where in other circumstances only parent nodes are searched.</param> /// <returns>The node at level.</returns> public static SiteMapNode GetNodeAtLevel(SiteMapNode startingNode, int level, bool allowForwardSearch) { var startingNodeLevel = startingNode.GetNodeLevel(); if (startingNodeLevel == level) { return startingNode; } if (startingNodeLevel > level) { var node = startingNode; while (node != null) { if (node.GetNodeLevel() == level) { return node; } node = node.ParentNode; } } else if (startingNodeLevel < level && allowForwardSearch) { var node = startingNode; while (node != null) { if (node.GetNodeLevel() == level) { return node; } if (node.HasChildNodes) { node = node.ChildNodes[0]; } else { break; } } } if (startingNode != null && startingNode.Provider.RootNode != null && allowForwardSearch) { return startingNode.Provider.RootNode; } return null; } /// <summary> /// Test if the maximal nodelevel has not been reached /// </summary> /// <param name="maxDepth">The normal max depth.</param> /// <param name="node">The starting node</param> /// <param name="drillDownToCurrent">Should the model exceed the maxDepth to reach the current node</param> /// <returns></returns> private static bool ReachedMaximalNodelevel(int maxDepth, SiteMapNode node, bool drillDownToCurrent) { if (maxDepth > 0) return true; if (!drillDownToCurrent) return false; if (node.IsInCurrentPath()) return true; if (node.ParentNode == node.Provider.CurrentNode) return true; foreach (SiteMapNode sibling in node.ParentNode.ChildNodes) { if (sibling.IsInCurrentPath()) return true; } return false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Collections.Generic; using System; namespace Microsoft.PowerShell.Commands { /// <summary> /// Cmdlet to get available list of results. /// </summary> [Cmdlet(VerbsCommon.Get, "Job", DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113328")] [OutputType(typeof(Job))] public class GetJobCommand : JobCmdletBase { #region Parameters /// <summary> /// IncludeChildJob parameter. /// </summary> [Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)] public SwitchParameter IncludeChildJob { get; set; } /// <summary> /// ChildJobState parameter. /// </summary> [Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)] public JobState ChildJobState { get; set; } /// <summary> /// HasMoreData parameter. /// </summary> [Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)] public bool HasMoreData { get; set; } /// <summary> /// Before time filter. /// </summary> [Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)] public DateTime Before { get; set; } /// <summary> /// After time filter. /// </summary> [Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)] public DateTime After { get; set; } /// <summary> /// Newest returned count. /// </summary> [Parameter(ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.InstanceIdParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.NameParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.StateParameterSet)] [Parameter(ParameterSetName = JobCmdletBase.CommandParameterSet)] public int Newest { get; set; } /// <summary> /// SessionId for which job /// need to be obtained. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, Position = 0, ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public override int[] Id { get { return base.Id; } set { base.Id = value; } } #endregion Parameters #region Overrides /// <summary> /// Extract result objects corresponding to the specified /// names or expressions. /// </summary> protected override void ProcessRecord() { List<Job> jobList = FindJobs(); jobList.Sort((x, y) => x != null ? x.Id.CompareTo(y != null ? y.Id : 1) : -1); WriteObject(jobList, true); } #endregion Overrides #region Protected Members /// <summary> /// Helper method to find jobs based on parameter set. /// </summary> /// <returns>Matching jobs.</returns> protected List<Job> FindJobs() { List<Job> jobList = new List<Job>(); switch (ParameterSetName) { case NameParameterSet: { jobList.AddRange(FindJobsMatchingByName(true, false, true, false)); } break; case InstanceIdParameterSet: { jobList.AddRange(FindJobsMatchingByInstanceId(true, false, true, false)); } break; case SessionIdParameterSet: { if (Id != null) { jobList.AddRange(FindJobsMatchingBySessionId(true, false, true, false)); } else { // Get-Job with no filter. jobList.AddRange(JobRepository.Jobs); jobList.AddRange(JobManager.GetJobs(this, true, false, null)); } } break; case CommandParameterSet: { jobList.AddRange(FindJobsMatchingByCommand(false)); } break; case StateParameterSet: { jobList.AddRange(FindJobsMatchingByState(false)); } break; case FilterParameterSet: { jobList.AddRange(FindJobsMatchingByFilter(false)); } break; default: break; } jobList.AddRange(FindChildJobs(jobList)); jobList = ApplyHasMoreDataFiltering(jobList); return ApplyTimeFiltering(jobList); } #endregion #region Private Members /// <summary> /// Filter jobs based on HasMoreData. /// </summary> /// <param name="jobList"></param> /// <returns>Return the list of jobs after applying HasMoreData filter.</returns> private List<Job> ApplyHasMoreDataFiltering(List<Job> jobList) { bool hasMoreDataParameter = MyInvocation.BoundParameters.ContainsKey(nameof(HasMoreData)); if (!hasMoreDataParameter) { return jobList; } List<Job> matches = new List<Job>(); foreach (Job job in jobList) { if (job.HasMoreData == HasMoreData) { matches.Add(job); } } return matches; } /// <summary> /// Find the all child jobs with specified ChildJobState in the job list. /// </summary> /// <param name="jobList"></param> /// <returns>Returns job list including all child jobs with ChildJobState or all if IncludeChildJob is specified.</returns> private List<Job> FindChildJobs(List<Job> jobList) { bool childJobStateParameter = MyInvocation.BoundParameters.ContainsKey(nameof(ChildJobState)); bool includeChildJobParameter = MyInvocation.BoundParameters.ContainsKey(nameof(IncludeChildJob)); List<Job> matches = new List<Job>(); if (!childJobStateParameter && !includeChildJobParameter) { return matches; } // add all child jobs if ChildJobState is not specified // if (!childJobStateParameter && includeChildJobParameter) { foreach (Job job in jobList) { if (job.ChildJobs != null && job.ChildJobs.Count > 0) { matches.AddRange(job.ChildJobs); } } } else { foreach (Job job in jobList) { foreach (Job childJob in job.ChildJobs) { if (childJob.JobStateInfo.State != ChildJobState) continue; matches.Add(childJob); } } } return matches; } /// <summary> /// Applys the appropriate time filter to each job in the job list. /// Only Job2 type jobs can be time filtered so older Job types are skipped. /// </summary> /// <param name="jobList"></param> /// <returns></returns> private List<Job> ApplyTimeFiltering(List<Job> jobList) { bool beforeParameter = MyInvocation.BoundParameters.ContainsKey(nameof(Before)); bool afterParameter = MyInvocation.BoundParameters.ContainsKey(nameof(After)); bool newestParameter = MyInvocation.BoundParameters.ContainsKey(nameof(Newest)); if (!beforeParameter && !afterParameter && !newestParameter) { return jobList; } // Apply filtering. List<Job> filteredJobs; if (beforeParameter || afterParameter) { filteredJobs = new List<Job>(); foreach (Job job in jobList) { if (job.PSEndTime == DateTime.MinValue) { // Skip invalid dates. continue; } if (beforeParameter && afterParameter) { if (job.PSEndTime < Before && job.PSEndTime > After) { filteredJobs.Add(job); } } else if ((beforeParameter && job.PSEndTime < Before) || (afterParameter && job.PSEndTime > After)) { filteredJobs.Add(job); } } } else { filteredJobs = jobList; } if (!newestParameter || filteredJobs.Count == 0) { return filteredJobs; } // // Apply Newest count. // // Sort filtered jobs filteredJobs.Sort((firstJob, secondJob) => { if (firstJob.PSEndTime > secondJob.PSEndTime) { return -1; } else if (firstJob.PSEndTime < secondJob.PSEndTime) { return 1; } else { return 0; } }); List<Job> newestJobs = new List<Job>(); int count = 0; foreach (Job job in filteredJobs) { if (++count > Newest) { break; } if (!newestJobs.Contains(job)) { newestJobs.Add(job); } } return newestJobs; } #endregion Private Members } }
/****************************************************************************/ /* */ /* The Mondo Libraries */ /* */ /* Namespace: Mondo.Common */ /* File: Utility.cs */ /* Class(es): Utility */ /* Purpose: Utility for global functions */ /* */ /* Original Author: Jim Lightfoot */ /* Creation Date: 19 Sep 2001 */ /* */ /* Copyright (c) 2001-2016 - Jim Lightfoot, All rights reserved */ /* */ /* Licensed under the MIT license: */ /* http://www.opensource.org/licenses/mit-license.php */ /* */ /****************************************************************************/ using System; using System.Diagnostics; using System.IO; using System.Xml; using System.Xml.XPath; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.Specialized; using System.Runtime.InteropServices; namespace Mondo.Common { /****************************************************************************/ /****************************************************************************/ public class Pair<T> { public T First; public T Second; /****************************************************************************/ public Pair(T obj1, T obj2) { First = obj1; Second = obj2; } } /****************************************************************************/ /****************************************************************************/ public sealed class cDebug { /****************************************************************************/ [Conditional("DEBUG")] public static void Notify(string strCategory, string strMessage) { EventLog.Error(strCategory, strMessage); } /****************************************************************************/ [Conditional("DEBUG")] public static void Capture(Exception e) { // Do nothing } /****************************************************************************/ [Conditional("DEBUG")] public static void ToFile(string strData, string strFileName) { try { DiskFile.ToFile(strData, "c:\\Documents\\Development\\Output\\" + strFileName); } catch(Exception ex) { cDebug.Capture(ex); //ErrorHandler.Handle(new Exception("Unable to write debug file", ex)); } } /****************************************************************************/ [Conditional("DEBUG")] public static void ToFile(byte[] aData, string strFileName) { try { DiskFile.ToFile(aData, "c:\\Documents\\Development\\Output\\" + strFileName); } catch(Exception ex) { cDebug.Capture(ex); //ErrorHandler.Handle(new Exception("Unable to write debug file", ex)); } } /****************************************************************************/ [Conditional("DEBUG")] public static void Append(ref string strAppendTo, string strText) { strAppendTo += strText; } /****************************************************************************/ [Conditional("DEBUG")] public static void Prepend(ref string strAppendTo, string strText) { strAppendTo = strText + strAppendTo; } } /****************************************************************************/ /****************************************************************************/ public sealed class DebugConsole { /****************************************************************************/ [Conditional("DEBUG")] public static void WriteLine(string strMessage) { Console.WriteLine(strMessage); } } /****************************************************************************/ /****************************************************************************/ public class ValueOutOfRangeException : Exception {} public class NotFoundException : Exception {} /****************************************************************************/ /****************************************************************************/ public static class UtilityExtensions { private static DateTime _daydexBase = new DateTime(1900, 1, 1); /****************************************************************************/ public static int Age(this DateTime dtBirth, DateTime dtCurrent) { return((int)Math.Floor((dtCurrent - dtBirth).TotalHours / (double)8766)); } /*****************************************************************************/ public static int Daydex(this DateTime dtValue) { if(dtValue == DateTime.MinValue) return(0); if(dtValue == DateTime.MaxValue) return(int.MaxValue); return((dtValue.Date - _daydexBase).Days); } /*****************************************************************************/ public static DateTime FromDaydex(this int value) { if(value <= 0) return DateTime.MinValue; if(value == int.MaxValue) return DateTime.MaxValue; return _daydexBase.AddDays(value); } /****************************************************************************/ public static string ToShortString(this bool bValue) { return(bValue ? "1" : "0"); } /****************************************************************************/ public static string ToLongString(this bool bValue) { return(bValue ? "True" : "False"); } /****************************************************************************/ public static long ValidateID(this long val) { if(val <= 0) throw new ValueOutOfRangeException(); return val; } /****************************************************************************/ public static string ToGuidString(this Guid idValue) { return(Utility.ToGuidString(idValue)); } /****************************************************************************/ public static short ToBit(this bool bValue) { return((short)(bValue ? 1 : 0)); } /****************************************************************************/ public static byte[] ToByteArray(this Stream objFrom) { return(Utility.StreamToStream(objFrom).ToArray()); } /****************************************************************************/ public static bool TestFlag(this int iFlags, int iFlag) { return(Flag.Test(iFlags, iFlag)); } /****************************************************************************/ public static MemoryStream ToStream(this byte[] aBytes) { MemoryStream objStream = new MemoryStream(); objStream.Write(aBytes, 0, aBytes.Length); objStream.Position = 0; return(objStream); } /****************************************************************************/ public static void Clear(this byte[] aBytes) { int nBytes = aBytes.Length; for(int i = 0; i < nBytes; ++i) aBytes[i] = 0; return; } /****************************************************************************/ public static void Clear(this char[] aChars) { int nChars = aChars.Length; for(int i = 0; i < nChars; ++i) aChars[i] = '\0'; return; } /****************************************************************************/ public static byte[] DeepClone(this byte[] aBytes) { byte[] aNew = new byte[aBytes.Length]; aBytes.CopyTo(aNew, 0); return(aNew); } /****************************************************************************/ public static byte[] DeepClone(this byte[] aBytes, int srcOffset, int iLength) { if(iLength == -1) iLength = aBytes.Length - srcOffset; byte[] aNew = new byte[iLength]; Buffer.BlockCopy(aBytes, srcOffset, aNew, 0, iLength); return(aNew); } /****************************************************************************/ public static bool IsEmptyList<T>(this IEnumerable<T> list) { foreach(T obj in list) return(false); return(true); } } /****************************************************************************/ /****************************************************************************/ public static class StreamExtensions { private const int kBufferSize = 512 * 1024; // 512k /****************************************************************************/ public static void Write(this Stream objDestination, Stream objSource) { byte[] aBuffer = new byte[kBufferSize]; int nRead = 0; do { nRead = objSource.Read(aBuffer, 0, kBufferSize); if(nRead > 0) objDestination.Write(aBuffer, 0, nRead); } while(nRead > 0); objDestination.Flush(); } } /****************************************************************************/ /****************************************************************************/ public sealed class Utility { /****************************************************************************/ public static Guid NullGuid { get { return(Guid.Empty); } } /****************************************************************************/ public static int GuidLength { get { return(Guid.Empty.ToString().Length); } } /****************************************************************************/ public static bool IsEven(uint uValue) { return(!IsOdd(uValue)); } /****************************************************************************/ public static bool IsEven(int iValue) { return(!IsOdd(iValue)); } /****************************************************************************/ public static bool IsOdd(uint uValue) { return(Flag.Test(uValue, 1)); } /****************************************************************************/ public static bool IsOdd(int iValue) { return(Flag.Test(iValue, 1)); } /****************************************************************************/ public static uint ClearFlag(uint uFlags, uint uFlag) { return(Flag.Clear(uFlags, uFlag)); } /****************************************************************************/ public static void WriteMessageFile(string strMessage, string strPath) { using(StreamWriter sw = new StreamWriter(strPath)) sw.WriteLine(strMessage); } /****************************************************************************/ public static string GetHashString(uint uValue) { string strCode = string.Format("{0:X}", uValue); strCode = strCode.PadLeft(8, '0'); return(strCode); } /****************************************************************************/ public static string GetHashString(ulong uValue) { string strCode = string.Format("{0:X}", uValue); strCode = strCode.PadLeft(16, '0'); return(strCode); } /****************************************************************************/ public static string GetHashString(object obj) { return(GetHashString((uint)obj.GetHashCode())); } /****************************************************************************/ public static byte ToByte(object objValue) { return(ToByte(objValue, 0)); } /****************************************************************************/ public static byte ToByte(object objValue, byte bDefault) { if(objValue == null) return(bDefault); if(objValue.ToString().Trim().Length == 0) return(bDefault); return(byte.Parse(objValue.ToString())); } /****************************************************************************/ public static int ToInt(object objValue) { return(ToInt(objValue, 0, false)); } /****************************************************************************/ public static T Convert<T>(object val, T defaultVal = default(T), bool bThrow = false) where T : struct { if(val == null) return(defaultVal); if(typeof(T) == typeof(bool)) val = ToBoolString(val); if(typeof(T) == typeof(Guid)) return((T)((object)ToGuid(val))); try { return((T)System.Convert.ChangeType(val, typeof(T))); } catch(Exception ex) { if(bThrow) throw ex; return(defaultVal); } } /****************************************************************************/ public static object ConvertType(object objValue, System.Type objType) { if(objType == typeof(string)) return(objValue.Normalized()); if(objType == typeof(bool)) return(Utility.ToBool(objValue)); if(objType == typeof(int)) return(Utility.ToInt(objValue)); if(objType == typeof(long)) return(Utility.ToLong(objValue)); if(objType == typeof(short)) return(Utility.ToShort(objValue)); if(objType == typeof(uint)) return(Utility.ToUint(objValue)); if(objType == typeof(ushort)) return(Utility.ToUShort(objValue)); if(objType == typeof(ulong)) return(Utility.ToULong(objValue)); if(objType == typeof(decimal)) return(Utility.ToDecimal(objValue)); if(objType == typeof(float)) return(Utility.ToFloat(objValue)); if(objType == typeof(double)) return(Utility.ToDouble(objValue)); if(objType == typeof(DateTime)) return(Utility.ToDateTime(objValue)); if(objType == typeof(Guid)) return(Utility.ToGuid(objValue)); return(objValue); } /****************************************************************************/ public static int ToInt(object objValue, bool bTrim) { return(ToInt(objValue, 0, bTrim)); } /****************************************************************************/ public static int ToInt(object objValue, int iDefault) { return(ToInt(objValue, iDefault, false)); } /****************************************************************************/ public static int ToInt(object objValue, int iDefault, bool bTrim) { if(objValue == null) return(iDefault); if(objValue is int) return((int)objValue); if(objValue is long) return(int.Parse(objValue.ToString())); decimal dValue = 0m; if(decimal.TryParse(objValue.ToString(), out dValue)) { if(Math.Floor(dValue) == dValue) { if(bTrim) { if(dValue <= (decimal)int.MinValue) return(int.MinValue); if(dValue >= (decimal)int.MaxValue) return(int.MaxValue); } if(dValue >= (decimal)int.MinValue && dValue <= (decimal)int.MaxValue) return((int)dValue); } // Just to get the right exception return(int.Parse(objValue.ToString())); } if(objValue is XPathNodeIterator) { XPathNodeIterator objIterator = objValue as XPathNodeIterator; string strValue = ""; try { objIterator.MoveNext(); strValue = objIterator.Current.Value; } catch { } return(Utility.ToInt(strValue)); } // Blank string - return default if(objValue.ToString().Trim().Length == 0) return(iDefault); // Probably not an int at this point return(int.Parse(objValue.ToString())); } /****************************************************************************/ public static short ToShort(object objValue) { return(ToShort(objValue, 0)); } /****************************************************************************/ public static short ToShort(object objValue, short iDefault) { if(objValue == null) return(iDefault); if(objValue.ToString().Trim().Length == 0) return(iDefault); return(short.Parse(objValue.ToString())); } /****************************************************************************/ public static ushort ToUShort(object objValue) { return(ToUShort(objValue, 0)); } /****************************************************************************/ public static ushort ToUShort(object objValue, ushort iDefault) { if(objValue == null) return(iDefault); if(objValue.ToString().Trim().Length == 0) return(iDefault); return(ushort.Parse(objValue.ToString())); } /****************************************************************************/ public static long ToLong(object objValue) { return(ToLong(objValue, 0)); } /****************************************************************************/ public static long ToLong(object objValue, long iDefault) { if(objValue == null) return(iDefault); if(objValue.ToString().Trim().Length == 0) return(iDefault); return(long.Parse(objValue.ToString())); } /****************************************************************************/ public static ulong ToULong(object objValue) { return(ToULong(objValue, 0)); } /****************************************************************************/ public static ulong ToULong(object objValue, ulong iDefault) { if(objValue == null) return(iDefault); if(objValue.ToString().Trim().Length == 0) return(iDefault); return(ulong.Parse(objValue.ToString())); } /****************************************************************************/ /// <summary> /// Convert the given value into a boolean /// </summary> /// <param name="objValue">Value to convert</param> /// <returns></returns> public static bool ToBool(object objValue) { return(ToBool(objValue, false)); } /****************************************************************************/ /// <summary> /// Convert the given value into a boolean /// </summary> /// <param name="objValue">Value to convert</param> /// <returns></returns> private static string ToBoolString(object objValue) { try { if(objValue == null) return(""); if(objValue is bool) return((bool)objValue ? "true" : "false"); string strValue = objValue.ToString().ToLower(); long iValue = 0; if(long.TryParse(strValue, out iValue) && iValue > 0) return("true"); switch(strValue) { case "x": case "y": case "yes": case "t": case "checked": case "true": return("true"); case "": case "n": case "no": case "f": case "false": case "0": return("false"); default: return(""); } } catch { return(""); } } /****************************************************************************/ /// <summary> /// Convert the given value into a boolean /// </summary> /// <param name="objValue">Value to convert</param> /// <returns></returns> public static bool ToBool(object objValue, bool bDefault) { try { if(objValue == null) return(bDefault); if(objValue is bool) return((bool)objValue); string strValue = objValue.ToString().ToLower(); long iValue = 0; if(long.TryParse(strValue, out iValue) && iValue > 0) return(true); switch(strValue) { case "x": case "y": case "yes": case "t": case "checked": case "true": return(true); case "": case "n": case "no": case "f": case "false": case "0": return(false); default: return(bDefault); } } catch { return(bDefault); } } /****************************************************************************/ public static bool IsTrue(string strValue) { return(ToBool(strValue)); } /****************************************************************************/ public static bool IsGuid(string strValue) { Guid guidValue = Guid.Empty; return(Guid.TryParse(strValue, out guidValue)); } /****************************************************************************/ public static Guid ToGuid(object objValue) { if(objValue == null) return(Guid.Empty); if(objValue is Guid) return((Guid)objValue); string strValue = objValue.ToString().Trim(); if(strValue == "") return(Guid.Empty); Guid guidValue = Guid.Empty; Guid.TryParse(strValue, out guidValue); return(guidValue); } /****************************************************************************/ public static string ToGuidString(object objValue) { if(objValue == null) return(NullGuid.ToString()); string strValue = objValue.ToString().Trim(); if(strValue == "") return(NullGuid.ToString()); return(strValue.ToUpper()); } /****************************************************************************/ /// <summary> /// Converts an object to an decimal. If the string is not a valid decimal it will return zero. /// </summary> /// <param name="objValue">The object to convert</param> /// <returns>The resulting value</returns> public static decimal ToDecimal(object objValue) { return(ToDecimal(objValue, 0M)); } /****************************************************************************/ /// <summary> /// Converts an object to an decimal. If the string is not a valid decimal it will return the default value. /// </summary> /// <param name="objValue">The object to convert</param> /// <param name="iDefault">The default value to use if the object is not a valid decimal</param> /// <returns>The resulting value</returns> public static decimal ToDecimal(object objValue, decimal iDefault) { try { if(objValue != null) return(decimal.Parse(objValue.ToString())); } catch { } return(iDefault); } /****************************************************************************/ /// <summary> /// Converts an object to an double. If the string is not a valid double it will return zero. /// </summary> /// <param name="objValue">The object to convert</param> /// <returns>The resulting value</returns> public static double ToDouble(object objValue) { return(ToDouble(objValue, 0d)); } /****************************************************************************/ /// <summary> /// Converts an object to an double. If the string is not a valid double it will return the default value. /// </summary> /// <param name="objValue">The object to convert</param> /// <param name="iDefault">The default value to use if the object is not a valid decimal</param> /// <returns>The resulting value</returns> public static double ToDouble(object objValue, double dDefault) { try { return(double.Parse(objValue.ToString())); } catch { return(dDefault); } } /****************************************************************************/ /// <summary> /// Converts an object to a DateTime. If the string is not a valid date it will return DateTime.MinValue. /// </summary> /// <param name="objValue">The object to convert</param> /// <returns>The resulting integer</returns> public static DateTime ToDateTime(object objValue) { try { if(objValue != null) { if(objValue is DateTime) return((DateTime)objValue); return(DateTime.Parse(objValue.ToString())); } } catch { } return DateTime.MinValue; } /*****************************************************************************/ public static int ToDaydex(object objValue) { try { return Utility.ToDateTime(objValue).Daydex(); } catch { return 0; } } /*****************************************************************************/ public static DateTime FromDaydex(object value) { try { int daydex = Utility.ToInt(value, 0); return daydex.FromDaydex(); } catch { return DateTime.MinValue; } } /****************************************************************************/ public static decimal ToCurrency(object objValue) { if(!objValue.IsEmpty()) { try { string strCurrency = objValue.Normalized(); if(strCurrency == "") return(0); string strNew = ""; foreach(char chCheck in strCurrency) if(char.IsDigit(chCheck) || chCheck == '.' || chCheck == ',' || chCheck == '-' || chCheck == '(' || chCheck == ')') strNew += chCheck; return(decimal.Parse(strNew, System.Globalization.NumberStyles.Currency)); } catch { } } return(0M); } /****************************************************************************/ /// <summary> /// Converts an object to an float. If the string is not a valid float it will return zero. /// </summary> /// <param name="objValue">The object to convert</param> /// <returns>The resulting float</returns> public static float ToFloat(object objValue) { return(ToFloat(objValue, 0f)); } /****************************************************************************/ /// <summary> /// Converts an object to an float. If the string is not a valid float it will return the default value. /// </summary> /// <param name="objValue">The object to convert</param> /// <param name="iDefault">The default value to use if the object is not a valid integer</param> /// <returns>The resulting float</returns> public static float ToFloat(object objValue, float fDefault) { try { return(float.Parse(objValue.ToString())); } catch { return(fDefault); } } /****************************************************************************/ /// <summary> /// Converts an object to an float. If the string is not a valid float it will return the default value. /// </summary> /// <param name="objValue">The object to convert</param> /// <param name="bThrow">Indicates whether to throw an exception if a parsing error occurs</param> /// <returns>The resulting float</returns> public static float ToFloat(object objValue, bool bThrow) { try { if(objValue == null) return(0f); if(objValue.ToString().Trim() == "") return(0f); return(float.Parse(objValue.ToString())); } catch { if(bThrow) throw; return(0f); } } /****************************************************************************/ public static uint ToUint(string strValue) { if(strValue != null && strValue.Trim() != "") { try { return(uint.Parse(strValue)); } catch { } } return(0); } /****************************************************************************/ /// <summary> /// Converts an object to an uint. If the string is not a valid integer it will return zero. /// </summary> /// <param name="objValue">The object to convert</param> /// <returns>The resulting value</returns> public static uint ToUint(object objValue) { return(ToUint(objValue, 0)); } /****************************************************************************/ /// <summary> /// Converts an object to an uint. If the string is not a valid integer it will return the default value. /// </summary> /// <param name="objValue">The object to convert</param> /// <param name="iDefault">The default value to use if the object is not a valid uint</param> /// <returns>The resulting value</returns> public static uint ToUint(object objValue, uint iDefault) { try { return (uint.Parse(objValue.ToString())); } catch { return (iDefault); } } /****************************************************************************/ public static string RemoveUpTo(string strValue, string strRemove) { int iIndex = strValue.IndexOf(strRemove); if(iIndex != -1) return(strValue.Remove(0, iIndex + strRemove.Length)); return(strValue); } /****************************************************************************/ public static string Pack(StringCollection aStrings) { string strPacked = ""; foreach(string str in aStrings) { if(strPacked.Length > 0) strPacked += "//"; strPacked += str; } return(strPacked); } /****************************************************************************/ public static IComparable ToComparable(object objComparable) { if(objComparable is IComparable) return(objComparable as IComparable); return(objComparable.ToString()); } /****************************************************************************/ public static string ToString(byte[] pData) { try { ASCIIEncoding objEncoder = new ASCIIEncoding(); string strValue = objEncoder.GetString(pData); int iIndex = 0; while(iIndex < strValue.Length) { char chValue = strValue[iIndex]; // ??? This filters out characters it shouldn't if(char.IsLetterOrDigit(chValue) || char.IsPunctuation(chValue) || char.IsWhiteSpace(chValue) || char.IsSeparator(chValue)) { ++iIndex; continue; } strValue = strValue.Remove(iIndex, 1); } return(strValue); } catch { } return(""); } /****************************************************************************/ public static MemoryStream StreamToStream(Stream objFrom) { if(objFrom is MemoryStream) return(objFrom as MemoryStream); const int kBufferSize = 65536; int nRead = 0; byte[] aBuffer = new byte[kBufferSize]; MemoryStream objStream = new MemoryStream(); try { // Reset the stream if(objStream.CanSeek) objStream.Seek(0, SeekOrigin.Begin); nRead = objFrom.Read(aBuffer, 0, kBufferSize); while(nRead > 0) { objStream.Write(aBuffer, 0, nRead); nRead = objFrom.Read(aBuffer, 0, kBufferSize); } } catch(Exception ex) { objStream.Dispose(); objStream = null; throw ex; } finally { // Reset the source stream if(objFrom.CanSeek) objFrom.Seek(0, SeekOrigin.Begin); } objStream.Position = 0; return(objStream); } /****************************************************************************/ public static async Task<MemoryStream> StreamToStreamAsync(Stream objFrom) { if(objFrom is MemoryStream) return(objFrom as MemoryStream); const int kBufferSize = 65536; int nRead = 0; byte[] aBuffer = new byte[kBufferSize]; MemoryStream objStream = new MemoryStream(); try { // Reset the stream if(objStream.CanSeek) objStream.Seek(0, SeekOrigin.Begin); nRead = await objFrom.ReadAsync(aBuffer, 0, kBufferSize); while(nRead > 0) { await objStream.WriteAsync(aBuffer, 0, nRead); nRead = await objFrom.ReadAsync(aBuffer, 0, kBufferSize); } } catch(Exception ex) { objStream.Dispose(); objStream = null; throw ex; } finally { // Reset the source stream if(objFrom.CanSeek) objFrom.Seek(0, SeekOrigin.Begin); } objStream.Position = 0; return(objStream); } /****************************************************************************/ public static string StreamToString(System.IO.Stream objBuffer) { StreamReader objReader = new StreamReader(objBuffer); try { return(objReader.ReadToEnd()); } finally { objReader.Close(); } } /****************************************************************************/ public static MemoryStream StringToStream(string strValue) { return(StringToStream(strValue, new ASCIIEncoding())); } /****************************************************************************/ public static MemoryStream StringToStream(string strValue, Encoding objEncoder) { MemoryStream objStream = new MemoryStream(); byte[] pData = objEncoder.GetBytes(strValue); objStream.Write(pData, 0, pData.Length); objStream.Position = 0; return(objStream); } /****************************************************************************/ public static void Dispose(object objData) { if(objData != null && objData is IDisposable) { try { (objData as IDisposable).Dispose(); } catch { } } } /****************************************************************************/ public static void Swap(ref int v1, ref int v2) { int temp = v1; v1 = v2; v2 = temp; return; } /****************************************************************************/ public static bool InException { get { return(Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0); } } /****************************************************************************/ public static decimal Pin(decimal dValue, decimal dMin, decimal dMax) { return((dValue < dMin) ? dMin : ((dValue > dMax) ? dMax : dValue)); } /****************************************************************************/ public static double Pin(double dValue, double dMin, double dMax) { return((dValue < dMin) ? dMin : ((dValue > dMax) ? dMax : dValue)); } /****************************************************************************/ public static int Pin(int iValue, int iMin, int iMax) { return((iValue < iMin) ? iMin : ((iValue > iMax) ? iMax : iValue)); } /****************************************************************************/ public static long Pin(long iValue, long iMin, long iMax) { return((iValue < iMin) ? iMin : ((iValue > iMax) ? iMax : iValue)); } /****************************************************************************/ public static short Pin(short iValue, short iMin, short iMax) { return((iValue < iMin) ? iMin : ((iValue > iMax) ? iMax : iValue)); } #region Date/Time Functions /****************************************************************************/ public static DateTime TruncateSeconds(DateTime dtValue) { return(new DateTime(dtValue.Year, dtValue.Month, dtValue.Day, dtValue.Hour, dtValue.Minute, 0)); } /****************************************************************************/ public static DateTime TruncateMinutes(DateTime dtValue) { return(new DateTime(dtValue.Year, dtValue.Month, dtValue.Day, dtValue.Hour, 0, 0)); } #endregion /****************************************************************************/ public static byte[] XOR(byte[] a1, byte[] a2) { int iLength = a1.Length; byte[] aResults = new byte[a1.Length]; for(int i = 0; i < iLength; ++i) aResults[i] = (byte)(a1[i] ^ a2[i]); return(aResults); } /****************************************************************************/ public static byte[] XOR(byte[] a1, byte[] a2, byte[] a3, byte[] a4) { byte[] p1 = XOR(a1, a2); byte[] p2 = XOR(a3, a4); byte[] p3 = XOR(p1, p2); p1.Clear(); p2.Clear(); return(p3); } /****************************************************************************/ private Utility() { } } /****************************************************************************/ /****************************************************************************/ public sealed class Flag { /****************************************************************************/ public static bool Test(int uFlags, int uFlag) { return((uFlags & uFlag) == uFlag); } /****************************************************************************/ public static bool Test(long uFlags, long uFlag) { return((uFlags & uFlag) == uFlag); } /****************************************************************************/ public static bool Test(uint uFlags, uint uFlag) { return((uFlags & uFlag) == uFlag); } /****************************************************************************/ public static bool Test(byte uFlags, byte uFlag) { return((uFlags & uFlag) == uFlag); } /****************************************************************************/ public static uint Clear(uint uFlags, uint uFlag) { return(uFlags & (~uFlag)); } /****************************************************************************/ public static int Clear(int uFlags, int uFlag) { return(uFlags & (~uFlag)); } /****************************************************************************/ public static long Clear(long uFlags, long uFlag) { return(uFlags & (~uFlag)); } /****************************************************************************/ public static short Clear(short uFlags, short uFlag) { return((short)((int)uFlags & (~((int)uFlag)))); } /****************************************************************************/ public static uint Set(uint uFlags, uint uFlag, bool bSet) { return(Clear(uFlags, uFlag) | ((bSet ? uFlag : 0))); } /****************************************************************************/ public static long Set(long uFlags, long uFlag, bool bSet) { return(Clear(uFlags, uFlag) | ((bSet ? uFlag : 0))); } /****************************************************************************/ public static short Set(short sFlags, short sFlag, bool bSet) { long iFlags = sFlags; long iFlag = sFlag; return((short)Set(iFlags, iFlag, bSet)); } /****************************************************************************/ private Flag() { } } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class OnesComplementTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementShortTest(bool useInterpreter) { short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementShort(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementUShortTest(bool useInterpreter) { ushort[] values = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementUShort(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementIntTest(bool useInterpreter) { int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementUIntTest(bool useInterpreter) { uint[] values = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementUInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementLongTest(bool useInterpreter) { long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementLong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementULongTest(bool useInterpreter) { ulong[] values = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementULong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementByteTest(bool useInterpreter) { byte[] values = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementByte(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3737, "https://github.com/dotnet/corefx/issues/3737")] public static void CheckUnaryArithmeticOnesComplementSByteTest(bool useInterpreter) { sbyte[] values = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticOnesComplementSByte(values[i], useInterpreter); } } [Fact] public static void CheckUnaryArithmeticOnesComplementBooleanTest() { Expression operand = Expression.Variable(typeof(bool)); Assert.Throws<InvalidOperationException>(() => Expression.OnesComplement(operand)); } [Fact] public static void ToStringTest() { UnaryExpression e = Expression.OnesComplement(Expression.Parameter(typeof(int), "x")); Assert.Equal("~(x)", e.ToString()); } #endregion #region Test verifiers private static void VerifyArithmeticOnesComplementShort(short value, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.OnesComplement(Expression.Constant(value, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal((short)(~value), f()); } private static void VerifyArithmeticOnesComplementUShort(ushort value, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.OnesComplement(Expression.Constant(value, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort)(~value)), f()); } private static void VerifyArithmeticOnesComplementInt(int value, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.OnesComplement(Expression.Constant(value, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal((int)(~value), f()); } private static void VerifyArithmeticOnesComplementUInt(uint value, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.OnesComplement(Expression.Constant(value, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal((uint)(~value), f()); } private static void VerifyArithmeticOnesComplementLong(long value, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.OnesComplement(Expression.Constant(value, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal((long)(~value), f()); } private static void VerifyArithmeticOnesComplementULong(ulong value, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.OnesComplement(Expression.Constant(value, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal((ulong)(~value), f()); } private static void VerifyArithmeticOnesComplementByte(byte value, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( Expression.OnesComplement(Expression.Constant(value, typeof(byte))), Enumerable.Empty<ParameterExpression>()); Func<byte> f = e.Compile(useInterpreter); Assert.Equal(unchecked((byte)(~value)), f()); } private static void VerifyArithmeticOnesComplementSByte(sbyte value, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( Expression.OnesComplement(Expression.Constant(value, typeof(sbyte))), Enumerable.Empty<ParameterExpression>()); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal((sbyte)(~value), f()); } #endregion public static IEnumerable<object[]> Int32OnesComplements() { yield return new object[] { 0, ~0 }; yield return new object[] { 1, ~1 }; yield return new object[] { -1, ~-1 }; yield return new object[] { int.MinValue, ~int.MinValue }; yield return new object[] { int.MaxValue, ~int.MaxValue }; } [Theory, PerCompilationType(nameof(Int32OnesComplements))] public static void MakeUnaryOnesComplement(int value, int expected, bool useInterpreter) { Expression<Func<int>> lambda = Expression.Lambda<Func<int>>( Expression.MakeUnary(ExpressionType.OnesComplement, Expression.Constant(value), null)); Func<int> func = lambda.Compile(useInterpreter); Assert.Equal(expected, func()); } [Fact] public static void OnesComplementNonIntegral() { Expression operand = Expression.Constant(2.0); Assert.Throws<InvalidOperationException>(() => Expression.OnesComplement(operand)); } private class Complementary { public int Value { get; set; } public static Complementary operator ~(Complementary c) => new Complementary {Value = ~c.Value}; public static Complementary OnesComplement(Complementary c) => new Complementary { Value = ~c.Value }; } [Theory, ClassData(typeof(CompilationTypes))] public static void CustomOperatorOnesComplement(bool useInterpreter) { Complementary value = new Complementary {Value = 43}; Expression<Func<Complementary>> lambda = Expression.Lambda<Func<Complementary>>( Expression.OnesComplement(Expression.Constant(value))); Func<Complementary> func = lambda.Compile(useInterpreter); Assert.Equal(~43, func().Value); } [Theory, ClassData(typeof(CompilationTypes))] public static void ExplicitOperatorOnesComplement(bool useInterpreter) { Complementary value = new Complementary {Value = 43}; MethodInfo method = typeof(Complementary).GetMethod(nameof(Complementary.OnesComplement)); Expression<Func<Complementary>> lambda = Expression.Lambda<Func<Complementary>>( Expression.OnesComplement(Expression.Constant(value), method)); Func<Complementary> func = lambda.Compile(useInterpreter); Assert.Equal(~43, func().Value); } } }
// 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.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Xml.Serialization; using System.Security; using System.Runtime.CompilerServices; #if !uapaot using ExtensionDataObject = System.Object; #endif namespace System.Runtime.Serialization { #if USE_REFEMIT || uapaot public class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #endif { private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack(); private XmlSerializableWriter _xmlSerializableWriter; private const int depthToCheckCyclicReference = 512; private ObjectToIdCache _serializedObjects; private bool _isGetOnlyCollection; private readonly bool _unsafeTypeForwardingEnabled; protected bool serializeReadOnlyTypes; protected bool preserveObjectReferences; internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver); } protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver) : base(serializer, rootTypeDataContract, resolver) { this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; // Known types restricts the set of types that can be deserialized _unsafeTypeForwardingEnabled = true; } internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { // Known types restricts the set of types that can be deserialized _unsafeTypeForwardingEnabled = true; } #if USE_REFEMIT || uapaot internal ObjectToIdCache SerializedObjects #else protected ObjectToIdCache SerializedObjects #endif { get { if (_serializedObjects == null) _serializedObjects = new ObjectToIdCache(); return _serializedObjects; } } internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } internal bool SerializeReadOnlyTypes { get { return this.serializeReadOnlyTypes; } } internal bool UnsafeTypeForwardingEnabled { get { return _unsafeTypeForwardingEnabled; } } #if USE_REFEMIT public void StoreIsGetOnlyCollection() #else internal void StoreIsGetOnlyCollection() #endif { _isGetOnlyCollection = true; } internal void ResetIsGetOnlyCollection() { _isGetOnlyCollection = false; } #if USE_REFEMIT public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #else internal void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #endif { if (!OnHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/)) InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); OnEndHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/); } #if USE_REFEMIT public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #else internal virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #endif { if (writeXsiType) { Type declaredType = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, obj.GetType().TypeHandle, null/*type*/, -1, declaredType.TypeHandle, declaredType); } else if (isDeclaredType) { DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle); SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle); } else { RuntimeTypeHandle objTypeHandle = obj.GetType().TypeHandle; if (declaredTypeHandle.GetHashCode() == objTypeHandle.GetHashCode()) // semantically the same as Value == Value; Value is not available in SL { DataContract dataContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, null /*type*/); SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle)); } } } internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); scopedKnownTypes.Pop(); } else { WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); } } internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type declaredType = rootTypeDataContract.UnderlyingType; if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { if (DataContractResolver != null) { WriteResolvedTypeInfo(xmlWriter, graphType, declaredType); } } else if (!declaredType.IsArray) //Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType); } protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool verifyKnownType = false; DataContract dataContract; if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { #if !uapaot dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; dataContract = GetDataContract(declaredTypeHandle, declaredType); #else dataContract = DataContract.GetDataContract(declaredType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode)) dataContract = dataContract.GetValidContract(this.Mode); else dataContract = GetDataContract(declaredTypeHandle, declaredType); #endif if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null) { if (objectType == null) { objectType = Type.GetTypeFromHandle(objectTypeHandle); } WriteResolvedTypeInfo(xmlWriter, objectType, declaredType); } } else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { // A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference dataContract = GetDataContract(objectTypeHandle, objectType); WriteClrTypeInfo(xmlWriter, dataContract); dataContract = GetDataContract(declaredTypeHandle, declaredType); } else { dataContract = GetDataContract(objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (!WriteClrTypeInfo(xmlWriter, dataContract)) { DataContract declaredTypeContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType); verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract); } } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType); } internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj) { if (preserveObjectReferences || !contract.IsReference || _isGetOnlyCollection) { return false; } bool isNew = true; int objectId = SerializedObjects.GetId(obj, ref isNew); _byValObjectsInScope.EnsureSetAsIsReference(obj); if (isNew) { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return false; } else { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return true; } } protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } #if !uapaot if (verifyKnownType) { if (!IsKnownType(dataContract, declaredType)) { DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/); if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } } } #endif WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, SerializationInfo serInfo) { return false; } #if USE_REFEMIT || uapaot public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #else internal virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #endif { xmlWriter.WriteAnyType(value); } #if USE_REFEMIT || uapaot public virtual void WriteString(XmlWriterDelegator xmlWriter, string value) #else internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value) #endif { xmlWriter.WriteString(value); } #if USE_REFEMIT || uapaot public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || uapaot public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #else internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #endif { xmlWriter.WriteBase64(value); } #if USE_REFEMIT || uapaot public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || uapaot public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #else internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #endif { xmlWriter.WriteUri(value); } #if USE_REFEMIT || uapaot public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || uapaot public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #else internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #endif { xmlWriter.WriteQName(value); } #if USE_REFEMIT || uapaot public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { if (ns != null && ns.Value != null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } } internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract) { writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace); if (contract.IsISerializable) { writer.WriteXmlnsAttribute(Globals.XsdPrefix, DictionaryGlobals.SchemaNamespace); } OnHandleReference(writer, obj, true /*canContainReferences*/); } internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return false; if (canContainCyclicReference) { if (_byValObjectsInScope.Contains(obj)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType())))); _byValObjectsInScope.Push(obj); } return false; } internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return; if (canContainCyclicReference) { _byValObjectsInScope.Pop(obj); } } #if USE_REFEMIT public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) #else internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) #endif { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); WriteNull(xmlWriter); } internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteStartElement(name, ns); WriteNull(xmlWriter, memberType, isMemberTypeSerializable); xmlWriter.WriteEndElement(); } #if USE_REFEMIT public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) #else internal void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) #endif { IncrementCollectionCount(xmlWriter, array.GetLength(0)); } #if USE_REFEMIT public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) #else internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) #endif { IncrementCollectionCount(xmlWriter, collection.Count); } #if USE_REFEMIT public void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection) #else internal void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection) #endif { IncrementCollectionCount(xmlWriter, collection.Count); } private void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size) { IncrementItemCount(size); WriteArraySize(xmlWriter, size); } internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { } #if USE_REFEMIT public static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType) #else internal static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType) #endif { if (obj == null || memberType == null) return false; return obj.GetType().TypeHandle.Equals(memberType.TypeHandle); } #if USE_REFEMIT public static T GetDefaultValue<T>() #else internal static T GetDefaultValue<T>() #endif { return default(T); } #if USE_REFEMIT public static T GetNullableValue<T>(Nullable<T> value) where T : struct #else internal static T GetNullableValue<T>(Nullable<T> value) where T : struct #endif { // value.Value will throw if hasValue is false return value.Value; } #if USE_REFEMIT public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) #else internal static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) #endif { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.RequiredMemberMustBeEmitted, memberName, type.FullName))); } #if USE_REFEMIT public static bool GetHasValue<T>(Nullable<T> value) where T : struct #else internal static bool GetHasValue<T>(Nullable<T> value) where T : struct #endif { return value.HasValue; } internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { if (_xmlSerializableWriter == null) _xmlSerializableWriter = new XmlSerializableWriter(); WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter); } internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter()); } private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter) { xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj); IXmlSerializable xmlSerializable = obj as IXmlSerializable; if (xmlSerializable != null) xmlSerializable.WriteXml(xmlSerializableWriter); else { XmlElement xmlElement = obj as XmlElement; if (xmlElement != null) xmlElement.WriteTo(xmlSerializableWriter); else { XmlNode[] xmlNodes = obj as XmlNode[]; if (xmlNodes != null) foreach (XmlNode xmlNode in xmlNodes) xmlNode.WriteTo(xmlSerializableWriter); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownXmlType, DataContract.GetClrTypeFullName(obj.GetType())))); } } xmlSerializableWriter.EndWrite(); } [MethodImpl(MethodImplOptions.NoInlining)] internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context) { obj.GetObjectData(serInfo, context); } public void WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) { Type objType = obj.GetType(); var serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter /*!UnsafeTypeForwardingEnabled is always false*/); GetObjectData(obj, serInfo, GetStreamingContext()); if (!UnsafeTypeForwardingEnabled && serInfo.AssemblyName == Globals.MscorlibAssemblyName) { // Throw if a malicious type tries to set its assembly name to "0" to get deserialized in mscorlib throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ISerializableAssemblyNameSetToZero, DataContract.GetClrTypeFullName(obj.GetType())))); } WriteSerializationInfo(xmlWriter, objType, serInfo); } internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, SerializationInfo serInfo) { if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName) { if (DataContractResolver != null) { XmlDictionaryString typeName, typeNs; if (ResolveType(serInfo.ObjectType, objType, out typeName, out typeNs)) { xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, typeName, typeNs); } } else { string typeName, typeNs; DataContract.GetDefaultStableName(serInfo.FullTypeName, out typeName, out typeNs); xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(typeName), DataContract.GetClrTypeString(typeNs)); } } WriteClrTypeInfo(xmlWriter, objType, serInfo); IncrementItemCount(serInfo.MemberCount); foreach (SerializationEntry serEntry in serInfo) { XmlDictionaryString name = DataContract.GetClrTypeString(DataContract.EncodeLocalName(serEntry.Name)); xmlWriter.WriteStartElement(name, DictionaryGlobals.EmptyString); object obj = serEntry.Value; if (obj == null) { WriteNull(xmlWriter); } else { InternalSerializeReference(xmlWriter, obj, false /*isDeclaredType*/, false /*writeXsiType*/, -1, Globals.TypeOfObject.TypeHandle); } xmlWriter.WriteEndElement(); } } protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { dataContract.WriteXmlValue(xmlWriter, obj, this); } protected virtual void WriteNull(XmlWriterDelegator xmlWriter) { XmlObjectSerializer.WriteNull(xmlWriter); } private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType) { XmlDictionaryString typeName, typeNamespace; if (ResolveType(objectType, declaredType, out typeName, out typeNamespace)) { WriteTypeInfo(writer, typeName, typeNamespace); } } private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } if (typeName == null) { if (typeNamespace == null) { return false; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } } if (typeNamespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } return true; } protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if (!XmlObjectSerializer.IsContractDeclared(contract, declaredContract)) { if (DataContractResolver == null) { WriteTypeInfo(writer, contract.Name, contract.Namespace); return true; } else { WriteResolvedTypeInfo(writer, contract.OriginalUnderlyingType, declaredContract.OriginalUnderlyingType); return false; } } return false; } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex) { if (IgnoreExtensionDataObject || extensionData == null) return; IList<ExtensionDataMember> members = extensionData.Members; if (members != null) { for (int i = 0; i < extensionData.Members.Count; i++) { ExtensionDataMember member = extensionData.Members[i]; if (member.MemberIndex == memberIndex) { WriteExtensionDataMember(xmlWriter, member); } } } } private void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDataMember member) { xmlWriter.WriteStartElement(member.Name, member.Namespace); IDataNode dataNode = member.Value; WriteExtensionDataValue(xmlWriter, dataNode); xmlWriter.WriteEndElement(); } internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode) { if (dataNode.DataContractName != null) WriteTypeInfo(xmlWriter, dataNode.DataContractName, dataNode.DataContractNamespace); WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName); } internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode dataNode) { IncrementItemCount(1); if (dataNode == null) { WriteNull(xmlWriter); return; } if (dataNode.PreservesReferences && OnHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/)) return; Type dataType = dataNode.DataType; if (dataType == Globals.TypeOfClassDataNode) WriteExtensionClassData(xmlWriter, (ClassDataNode)dataNode); else if (dataType == Globals.TypeOfCollectionDataNode) WriteExtensionCollectionData(xmlWriter, (CollectionDataNode)dataNode); else if (dataType == Globals.TypeOfXmlDataNode) WriteExtensionXmlData(xmlWriter, (XmlDataNode)dataNode); else if (dataType == Globals.TypeOfISerializableDataNode) WriteExtensionISerializableData(xmlWriter, (ISerializableDataNode)dataNode); else { WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataType == Globals.TypeOfObject) { // NOTE: serialize value in DataNode<object> since it may contain non-primitive // deserialized object (ex. empty class) object o = dataNode.Value; if (o != null) InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, o.GetType().TypeHandle); } else xmlWriter.WriteExtensionData(dataNode); } if (dataNode.PreservesReferences) OnEndHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/); } internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode) { object o = dataNode.Value; if (o == null) return false; Type declaredType = (dataNode.DataContractName == null) ? o.GetType() : Globals.TypeOfObject; InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, declaredType.TypeHandle); return true; } private void WriteExtensionClassData(XmlWriterDelegator xmlWriter, ClassDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList<ExtensionDataMember> members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { WriteExtensionDataMember(xmlWriter, members[i]); } } } } private void WriteExtensionCollectionData(XmlWriterDelegator xmlWriter, CollectionDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); WriteArraySize(xmlWriter, dataNode.Size); IList<IDataNode> items = dataNode.Items; if (items != null) { for (int i = 0; i < items.Count; i++) { xmlWriter.WriteStartElement(dataNode.ItemName, dataNode.ItemNamespace); WriteExtensionDataValue(xmlWriter, items[i]); xmlWriter.WriteEndElement(); } } } } private void WriteExtensionISerializableData(XmlWriterDelegator xmlWriter, ISerializableDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataNode.FactoryTypeName != null) xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace); IList<ISerializableDataMember> members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { ISerializableDataMember member = members[i]; xmlWriter.WriteStartElement(member.Name, String.Empty); WriteExtensionDataValue(xmlWriter, member.Value); xmlWriter.WriteEndElement(); } } } } private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { IList<XmlAttribute> xmlAttributes = dataNode.XmlAttributes; if (xmlAttributes != null) { foreach (XmlAttribute attribute in xmlAttributes) attribute.WriteTo(xmlWriter.Writer); } WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList<XmlNode> xmlChildNodes = dataNode.XmlChildNodes; if (xmlChildNodes != null) { foreach (XmlNode node in xmlChildNodes) node.WriteTo(xmlWriter.Writer); } } } } }
//--------------------------------------------------------------------- // <copyright file="ODataAtomWriter.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core.Atom { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.IO; using System.Text; #if ODATALIB_ASYNC using System.Threading.Tasks; #endif using System.Xml; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Library; using Microsoft.OData.Core.Metadata; #endregion Namespaces /// <summary> /// OData writer for the ATOM format. /// </summary> internal sealed class ODataAtomWriter : ODataWriterCore { /// <summary>Value for the atom:updated element.</summary> /// <remarks> /// The writer will use the same default value for the atom:updated element in a given payload. While there is no requirement for this, /// it saves us from re-querying the system time and converting it to string every time we write an item. /// </remarks> private readonly string updatedTime = ODataAtomConvert.ToAtomString(DateTimeOffset.UtcNow); /// <summary>The output context to write to.</summary> private readonly ODataAtomOutputContext atomOutputContext; /// <summary>The serializer to write payload with.</summary> private readonly ODataAtomEntryAndFeedSerializer atomEntryAndFeedSerializer; /// <summary> /// Constructor creating an OData writer using the ATOM format. /// </summary> /// <param name="atomOutputContext">The output context to write to.</param> /// <param name="navigationSource">The navigation source we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <param name="writingFeed">True if the writer is created for writing a feed; false when it is created for writing an entry.</param> internal ODataAtomWriter( ODataAtomOutputContext atomOutputContext, IEdmNavigationSource navigationSource, IEdmEntityType entityType, bool writingFeed) : base(atomOutputContext, navigationSource, entityType, writingFeed) { Debug.Assert(atomOutputContext != null, "atomOutputContext != null"); this.atomOutputContext = atomOutputContext; this.atomEntryAndFeedSerializer = new ODataAtomEntryAndFeedSerializer(this.atomOutputContext); } /// <summary> /// Enumeration of ATOM element flags, used to keep track of which elements were already written. /// </summary> private enum AtomElement { /// <summary>The atom:id element.</summary> Id = 0x1, /// <summary>The atom:link with rel='self'.</summary> ReadLink = 0x2, /// <summary>The atom:link with rel='edit'.</summary> EditLink = 0x4, } /// <summary> /// Returns the current AtomEntryScope. /// </summary> private AtomEntryScope CurrentEntryScope { get { AtomEntryScope currentAtomEntryScope = this.CurrentScope as AtomEntryScope; Debug.Assert(currentAtomEntryScope != null, "Asking for AtomEntryScope when the current scope is not an AtomEntryScope."); return currentAtomEntryScope; } } /// <summary> /// Returns the current AtomFeedScope. /// </summary> private AtomFeedScope CurrentFeedScope { get { AtomFeedScope currentAtomFeedScope = this.CurrentScope as AtomFeedScope; Debug.Assert(currentAtomFeedScope != null, "Asking for AtomFeedScope when the current scope is not an AtomFeedScope."); return currentAtomFeedScope; } } /// <summary> /// Check if the object has been disposed; called from all public API methods. Throws an ObjectDisposedException if the object /// has already been disposed. /// </summary> protected override void VerifyNotDisposed() { this.atomOutputContext.VerifyNotDisposed(); } /// <summary> /// Flush the output. /// </summary> protected override void FlushSynchronously() { this.atomOutputContext.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Flush the output. /// </summary> /// <returns>Task representing the pending flush operation.</returns> protected override Task FlushAsynchronously() { return this.atomOutputContext.FlushAsync(); } #endif /// <summary> /// Start writing an OData payload. /// </summary> protected override void StartPayload() { this.atomEntryAndFeedSerializer.WritePayloadStart(); } /// <summary> /// Finish writing an OData payload. /// </summary> protected override void EndPayload() { this.atomEntryAndFeedSerializer.WritePayloadEnd(); } /// <summary> /// Start writing an entry. /// </summary> /// <param name="entry">The entry to write.</param> protected override void StartEntry(ODataEntry entry) { this.CheckAndWriteParentNavigationLinkStartForInlineElement(); Debug.Assert( this.ParentNavigationLink == null || !this.ParentNavigationLink.IsCollection.Value, "We should have already verified that the IsCollection matches the actual content of the link (feed/entry)."); if (entry == null) { Debug.Assert(this.ParentNavigationLink != null, "When entry == null, it has to be an expanded single entry navigation."); // this is a null expanded single entry and it is null, an empty <m:inline /> will be written. return; } // <entry> this.atomOutputContext.XmlWriter.WriteStartElement(AtomConstants.AtomNamespacePrefix, AtomConstants.AtomEntryElementName, AtomConstants.AtomNamespace); if (this.IsTopLevel) { this.atomEntryAndFeedSerializer.WriteBaseUriAndDefaultNamespaceAttributes(); // Write metadata:context this.atomEntryAndFeedSerializer.TryWriteEntryContextUri(this.CurrentEntryScope.GetOrCreateTypeContext(this.atomOutputContext.Model, this.atomOutputContext.WritingResponse)); } string etag = entry.ETag; if (etag != null) { // TODO, ckerer: if this is a top-level entry also put the ETag into the headers. ODataAtomWriterUtils.WriteETag(this.atomOutputContext.XmlWriter, etag); } AtomEntryScope currentEntryScope = this.CurrentEntryScope; AtomEntryMetadata entryMetadata = entry.Atom(); // Write the id if it's available here. // If it's not available here we will try to write it at the end of the entry again. Uri entryId = entry.Id; bool isTransient = entry.IsTransient; if (entryId != null) { this.atomEntryAndFeedSerializer.WriteEntryId(entryId, isTransient); currentEntryScope.SetWrittenElement(AtomElement.Id); } // <category term="type" scheme="odatascheme"/> // If no type information is provided, don't include the category element for type at all // NOTE: the validation of the type name is done by the core writer. string typeName = this.atomOutputContext.TypeNameOracle.GetEntryTypeNameForWriting(entry); this.atomEntryAndFeedSerializer.WriteEntryTypeName(typeName, entryMetadata); // Write the edit link if it's available here. // If it's not available here we will try to write it at the end of the entry again. Uri editLink = entry.EditLink; if (editLink != null) { this.atomEntryAndFeedSerializer.WriteEntryEditLink(editLink, entryMetadata); currentEntryScope.SetWrittenElement(AtomElement.EditLink); } // Write the self link if it's available here. // If it's not available here we will try to write it at the end of the entry again. // If readlink is identical to editlink, don't write readlink. Uri readLink = entry.ReadLink; if (readLink != null) { if (readLink != editLink) { this.atomEntryAndFeedSerializer.WriteEntryReadLink(readLink, entryMetadata); } currentEntryScope.SetWrittenElement(AtomElement.ReadLink); } this.WriteInstanceAnnotations(entry.InstanceAnnotations, currentEntryScope.InstanceAnnotationWriteTracker); } /// <summary> /// Finish writing an entry. /// </summary> /// <param name="entry">The entry to write.</param> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "The coupling is intentional here.")] protected override void EndEntry(ODataEntry entry) { Debug.Assert( this.ParentNavigationLink == null || !this.ParentNavigationLink.IsCollection.Value, "We should have already verified that the IsCollection matches the actual content of the link (feed/entry)."); if (entry == null) { Debug.Assert(this.ParentNavigationLink != null, "When entry == null, it has to be an expanded single entry navigation."); // this is a null expanded single entry and it is null, an empty <m:inline /> will be written. this.CheckAndWriteParentNavigationLinkEndForInlineElement(); return; } IEdmEntityType entryType = this.EntryEntityType; // Initialize the property value cache and cache the entry properties. EntryPropertiesValueCache propertyValueCache = new EntryPropertiesValueCache(entry); // Get the projected properties annotation AtomEntryScope currentEntryScope = this.CurrentEntryScope; ProjectedPropertiesAnnotation projectedProperties = GetProjectedPropertiesAnnotation(currentEntryScope); AtomEntryMetadata entryMetadata = entry.Atom(); if (!currentEntryScope.IsElementWritten(AtomElement.Id)) { // NOTE: We write even null id, in that case we generate an empty atom:id element. bool isTransient = entry.IsTransient; this.atomEntryAndFeedSerializer.WriteEntryId(entry.Id, isTransient); } Uri editLink = entry.EditLink; if (editLink != null && !currentEntryScope.IsElementWritten(AtomElement.EditLink)) { this.atomEntryAndFeedSerializer.WriteEntryEditLink(editLink, entryMetadata); } Uri readLink = entry.ReadLink; if (readLink != null && readLink != editLink && !currentEntryScope.IsElementWritten(AtomElement.ReadLink)) { this.atomEntryAndFeedSerializer.WriteEntryReadLink(readLink, entryMetadata); } // write entry metadata this.atomEntryAndFeedSerializer.WriteEntryMetadata(entryMetadata, this.updatedTime); // stream properties IEnumerable<ODataProperty> streamProperties = propertyValueCache.EntryStreamProperties; if (streamProperties != null) { foreach (ODataProperty streamProperty in streamProperties) { this.atomEntryAndFeedSerializer.WriteStreamProperty( streamProperty, entryType, this.DuplicatePropertyNamesChecker, projectedProperties); } } // actions IEnumerable<ODataAction> actions = entry.Actions; if (actions != null) { foreach (ODataAction action in actions) { ValidationUtils.ValidateOperationNotNull(action, true); this.atomEntryAndFeedSerializer.WriteOperation(action); } } // functions IEnumerable<ODataFunction> functions = entry.Functions; if (functions != null) { foreach (ODataFunction function in functions) { ValidationUtils.ValidateOperationNotNull(function, false); this.atomEntryAndFeedSerializer.WriteOperation(function); } } // write the content this.WriteEntryContent( entry, entryType, propertyValueCache, projectedProperties); this.WriteInstanceAnnotations(entry.InstanceAnnotations, currentEntryScope.InstanceAnnotationWriteTracker); // </entry> this.atomOutputContext.XmlWriter.WriteEndElement(); this.CheckAndWriteParentNavigationLinkEndForInlineElement(); } /// <summary> /// Start writing a feed. /// </summary> /// <param name="feed">The feed to write.</param> protected override void StartFeed(ODataFeed feed) { Debug.Assert(feed != null, "feed != null"); Debug.Assert( this.ParentNavigationLink == null || !this.ParentNavigationLink.IsCollection.HasValue || this.ParentNavigationLink.IsCollection.Value, "We should have already verified that the IsCollection matches the actual content of the link (feed/entry)."); // Verify non-empty ID // We require non-null, non-empty IDs on feeds since it is required by ATOM. if (feed.Id == null) { throw new ODataException(OData.Core.Strings.ODataAtomWriter_FeedsMustHaveNonEmptyId); } this.CheckAndWriteParentNavigationLinkStartForInlineElement(); // <atom:feed> this.atomOutputContext.XmlWriter.WriteStartElement(AtomConstants.AtomNamespacePrefix, AtomConstants.AtomFeedElementName, AtomConstants.AtomNamespace); if (this.IsTopLevel) { this.atomEntryAndFeedSerializer.WriteBaseUriAndDefaultNamespaceAttributes(); // metadata:context this.atomEntryAndFeedSerializer.TryWriteFeedContextUri(this.CurrentFeedScope.GetOrCreateTypeContext(this.atomOutputContext.Model, this.atomOutputContext.WritingResponse)); if (feed.Count.HasValue) { this.atomEntryAndFeedSerializer.WriteCount(feed.Count.Value); } } bool authorWritten; this.atomEntryAndFeedSerializer.WriteFeedMetadata(feed, this.updatedTime, out authorWritten); this.CurrentFeedScope.AuthorWritten = authorWritten; this.WriteFeedInstanceAnnotations(feed, this.CurrentFeedScope); } /// <summary> /// Finish writing a feed. /// </summary> /// <param name="feed">The feed to write.</param> protected override void EndFeed(ODataFeed feed) { Debug.Assert(feed != null, "feed != null"); Debug.Assert( this.ParentNavigationLink == null || this.ParentNavigationLink.IsCollection.Value, "We should have already verified that the IsCollection matches the actual content of the link (feed/entry)."); AtomFeedScope currentFeedScope = this.CurrentFeedScope; if (!currentFeedScope.AuthorWritten && currentFeedScope.EntryCount == 0) { // Write an empty author if there were no entries, since the feed must have an author if the entries don't have one as per ATOM spec this.atomEntryAndFeedSerializer.WriteFeedDefaultAuthor(); } this.WriteFeedInstanceAnnotations(feed, currentFeedScope); this.atomEntryAndFeedSerializer.WriteFeedNextPageLink(feed); // Write delta link only in case of writing response for a top level feed. if (this.IsTopLevel) { if (this.atomOutputContext.WritingResponse) { this.atomEntryAndFeedSerializer.WriteFeedDeltaLink(feed); } } else { this.ValidateNoDeltaLinkForExpandedFeed(feed); } // </atom:feed> this.atomOutputContext.XmlWriter.WriteEndElement(); this.CheckAndWriteParentNavigationLinkEndForInlineElement(); } /// <summary> /// Start writing a navigation link. /// </summary> /// <param name="navigationLink">The navigation link to write.</param> protected override void WriteDeferredNavigationLink(ODataNavigationLink navigationLink) { Debug.Assert(navigationLink != null, "navigationLink != null"); Debug.Assert(this.atomOutputContext.WritingResponse, "Deferred links are only supported in response, we should have verified this already."); this.WriteNavigationLinkStart(navigationLink, null); this.WriteNavigationLinkEnd(); } /// <summary> /// Start writing a navigation link with content. /// </summary> /// <param name="navigationLink">The navigation link to write.</param> protected override void StartNavigationLinkWithContent(ODataNavigationLink navigationLink) { Debug.Assert(navigationLink != null, "navigationLink != null"); // In requests, a navigation link can have multiple items in its content (in the OM view), either entity reference links or expanded entry/feed. // For each of these we need to write a separate atom:link element. So we can't write the start of the atom:link element here // instead we postpone writing it till the first item in the content. // In response, only one item can occur, but for simplicity we will keep the behavior the same as for request and thus postpone writing the atom:link // start element as well. // Note that the writer core guarantees that this method (and the matching EndNavigationLinkWithContent) is only called for navigation links // which actually have some content. The only case where navigation link doesn't have a content is in response, in which case this method won't // be called, instead the WriteDeferredNavigationLink is called. } /// <summary> /// Finish writing a navigation link with content. /// </summary> /// <param name="navigationLink">The navigation link to write.</param> protected override void EndNavigationLinkWithContent(ODataNavigationLink navigationLink) { Debug.Assert(navigationLink != null, "navigationLink != null"); // We do not write the end element for atom:link here, since we need to write it for each item in the content separately. // See the detailed description in the StartNavigationLinkWithContent for details. } /// <summary> /// Write an entity reference link. /// </summary> /// <param name="parentNavigationLink">The parent navigation link which is being written around the entity reference link.</param> /// <param name="entityReferenceLink">The entity reference link to write.</param> protected override void WriteEntityReferenceInNavigationLinkContent(ODataNavigationLink parentNavigationLink, ODataEntityReferenceLink entityReferenceLink) { Debug.Assert(parentNavigationLink != null, "parentNavigationLink != null"); Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null"); Debug.Assert(entityReferenceLink.Url != null, "We should have already verifies that the Url specified on the entity reference link is not null."); this.WriteNavigationLinkStart(parentNavigationLink, entityReferenceLink.Url); this.WriteNavigationLinkEnd(); } /// <summary> /// Create a new feed scope. /// </summary> /// <param name="feed">The feed for the new scope.</param> /// <param name="navigationSource">The navigation source we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <param name="skipWriting">true if the content of the scope to create should not be written.</param> /// <param name="selectedProperties">The selected properties of this scope.</param> /// <param name="odataUri">The ODataUri info of this scope.</param> /// <returns>The newly create scope.</returns> protected override FeedScope CreateFeedScope(ODataFeed feed, IEdmNavigationSource navigationSource, IEdmEntityType entityType, bool skipWriting, SelectedPropertiesNode selectedProperties, ODataUri odataUri) { return new AtomFeedScope(feed, navigationSource, entityType, skipWriting, selectedProperties, odataUri); } /// <summary> /// Create a new entry scope. /// </summary> /// <param name="entry">The entry for the new scope.</param> /// <param name="navigationSource">The navigation source we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <param name="skipWriting">true if the content of the scope to create should not be written.</param> /// <param name="selectedProperties">The selected properties of this scope.</param> /// <param name="odataUri">The ODataUri info of this scope.</param> /// <returns>The newly create scope.</returns> protected override EntryScope CreateEntryScope(ODataEntry entry, IEdmNavigationSource navigationSource, IEdmEntityType entityType, bool skipWriting, SelectedPropertiesNode selectedProperties, ODataUri odataUri) { return new AtomEntryScope(entry, this.GetEntrySerializationInfo(entry), navigationSource, entityType, skipWriting, this.atomOutputContext.WritingResponse, this.atomOutputContext.MessageWriterSettings.WriterBehavior, selectedProperties, odataUri); } /// <summary> /// Writes the collection of <see cref="ODataInstanceAnnotation"/> to the ATOM payload. /// </summary> /// <param name="instanceAnnotations">The collection of <see cref="ODataInstanceAnnotation"/> to write.</param> /// <param name="tracker">Helper class to track if an annotation has been writen.</param> private void WriteInstanceAnnotations(IEnumerable<ODataInstanceAnnotation> instanceAnnotations, InstanceAnnotationWriteTracker tracker) { IEnumerable<AtomInstanceAnnotation> atomInstanceAnnotations = instanceAnnotations.Select(instanceAnnotation => AtomInstanceAnnotation.CreateFrom(instanceAnnotation, /*target*/ null)); this.atomEntryAndFeedSerializer.WriteInstanceAnnotations(atomInstanceAnnotations, tracker); } /// <summary> /// Writes the collection of <see cref="ODataInstanceAnnotation"/> for the given <paramref name="feed"/> to the ATOM payload. /// </summary> /// <param name="feed">The feed to write the <see cref="ODataInstanceAnnotation"/> for.</param> /// <param name="currentFeedScope">The current feed scope.</param> private void WriteFeedInstanceAnnotations(ODataFeed feed, AtomFeedScope currentFeedScope) { if (this.IsTopLevel) { this.WriteInstanceAnnotations(feed.InstanceAnnotations, currentFeedScope.InstanceAnnotationWriteTracker); } else { if (feed.InstanceAnnotations.Count > 0) { throw new ODataException(OData.Core.Strings.ODataJsonLightWriter_InstanceAnnotationNotSupportedOnExpandedFeed); } } } /// <summary> /// Write the content of the given entry. /// </summary> /// <param name="entry">The entry for which to write properties.</param> /// <param name="entryType">The <see cref="IEdmEntityType"/> of the entry (or null if not metadata is available).</param> /// <param name="propertiesValueCache">The cache of properties.</param> /// <param name="projectedProperties">Set of projected properties, or null if all properties should be written.</param> private void WriteEntryContent( ODataEntry entry, IEdmEntityType entryType, EntryPropertiesValueCache propertiesValueCache, ProjectedPropertiesAnnotation projectedProperties) { Debug.Assert(entry != null, "entry != null"); Debug.Assert(propertiesValueCache != null, "propertiesValueCache != null"); ODataStreamReferenceValue mediaResource = entry.MediaResource; if (mediaResource == null) { // <content type="application/xml"> this.atomOutputContext.XmlWriter.WriteStartElement( AtomConstants.AtomNamespacePrefix, AtomConstants.AtomContentElementName, AtomConstants.AtomNamespace); this.atomOutputContext.XmlWriter.WriteAttributeString( AtomConstants.AtomTypeAttributeName, MimeConstants.MimeApplicationXml); this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero(); this.atomEntryAndFeedSerializer.WriteProperties( entryType, propertiesValueCache.EntryProperties, false /* isWritingCollection */, this.atomEntryAndFeedSerializer.WriteEntryPropertiesStart, this.atomEntryAndFeedSerializer.WriteEntryPropertiesEnd, this.DuplicatePropertyNamesChecker, projectedProperties); this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero(); // </content> this.atomOutputContext.XmlWriter.WriteEndElement(); } else { WriterValidationUtils.ValidateStreamReferenceValue(mediaResource, true); this.atomEntryAndFeedSerializer.WriteEntryMediaEditLink(mediaResource); if (mediaResource.ReadLink != null) { // <content type="type" src="src"> this.atomOutputContext.XmlWriter.WriteStartElement( AtomConstants.AtomNamespacePrefix, AtomConstants.AtomContentElementName, AtomConstants.AtomNamespace); Debug.Assert(!string.IsNullOrEmpty(mediaResource.ContentType), "The default stream content type should have been validated by now. If we have a read link we must have a non-empty content type as well."); this.atomOutputContext.XmlWriter.WriteAttributeString( AtomConstants.AtomTypeAttributeName, mediaResource.ContentType); this.atomOutputContext.XmlWriter.WriteAttributeString( AtomConstants.MediaLinkEntryContentSourceAttributeName, this.atomEntryAndFeedSerializer.UriToUrlAttributeValue(mediaResource.ReadLink)); // </content> this.atomOutputContext.XmlWriter.WriteEndElement(); } this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero(); this.atomEntryAndFeedSerializer.WriteProperties( entryType, propertiesValueCache.EntryProperties, false /* isWritingCollection */, this.atomEntryAndFeedSerializer.WriteEntryPropertiesStart, this.atomEntryAndFeedSerializer.WriteEntryPropertiesEnd, this.DuplicatePropertyNamesChecker, projectedProperties); this.atomEntryAndFeedSerializer.AssertRecursionDepthIsZero(); } } /// <summary> /// Writes the navigation link start atom:link element including the m:inline element if there's a parent navigation link. /// </summary> private void CheckAndWriteParentNavigationLinkStartForInlineElement() { Debug.Assert(this.State == WriterState.Entry || this.State == WriterState.Feed, "Only entry or feed can be written into a link with inline."); ODataNavigationLink parentNavigationLink = this.ParentNavigationLink; if (parentNavigationLink != null) { // We postponed writing the surrounding atom:link and m:inline until now since in request a single navigation link can have // multiple items in its content, each of which is written as a standalone atom:link. Thus the StartNavigationLinkWithContent is only called // once, but we may need to write multiple atom:link elements. // write the start element of the link this.WriteNavigationLinkStart(parentNavigationLink, null); // <m:inline> this.atomOutputContext.XmlWriter.WriteStartElement( AtomConstants.ODataMetadataNamespacePrefix, AtomConstants.ODataInlineElementName, AtomConstants.ODataMetadataNamespace); } } /// <summary> /// Writes the navigation link end m:inline and end atom:link elements if there's a parent navigation link. /// </summary> private void CheckAndWriteParentNavigationLinkEndForInlineElement() { Debug.Assert(this.State == WriterState.Entry || this.State == WriterState.Feed, "Only entry or feed can be written into a link with inline."); ODataNavigationLink parentNavigationLink = this.ParentNavigationLink; if (parentNavigationLink != null) { // We postponed writing the surrounding atom:link and m:inline until now since in request a single navigation link can have // multiple items in its content, each of which is written as a standalone atom:link. Thus the EndNavigationLinkWithContent is only called // once, but we may need to write multiple atom:link elements. // </m:inline> this.atomOutputContext.XmlWriter.WriteEndElement(); // </atom:link> this.WriteNavigationLinkEnd(); } } /// <summary> /// Writes the navigation link's start element and atom metadata. /// </summary> /// <param name="navigationLink">The navigation link to write.</param> /// <param name="navigationLinkUrlOverride">Url to use for the navigation link. If this is specified the Url property on the <paramref name="navigationLink"/> /// will be ignored. If this parameter is null, the Url from the navigation link is used.</param> private void WriteNavigationLinkStart(ODataNavigationLink navigationLink, Uri navigationLinkUrlOverride) { WriterValidationUtils.ValidateNavigationLinkHasCardinality(navigationLink); WriterValidationUtils.ValidateNavigationLinkUrlPresent(navigationLink); this.atomEntryAndFeedSerializer.WriteNavigationLinkStart(navigationLink, navigationLinkUrlOverride); } /// <summary> /// Writes custom extensions and the end element for a navigation link /// </summary> private void WriteNavigationLinkEnd() { // </atom:link> this.atomOutputContext.XmlWriter.WriteEndElement(); } /// <summary> /// A scope for an feed. /// </summary> private sealed class AtomFeedScope : FeedScope { /// <summary>true if the author element was already written, false otherwise.</summary> private bool authorWritten; /// <summary> /// Constructor to create a new feed scope. /// </summary> /// <param name="feed">The feed for the new scope.</param> /// <param name="navigationSource">The navigation source we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <param name="skipWriting">true if the content of the scope to create should not be written.</param> /// <param name="selectedProperties">The selected properties of this scope.</param> /// <param name="odataUri">The ODataUri info of this scope.</param> internal AtomFeedScope(ODataFeed feed, IEdmNavigationSource navigationSource, IEdmEntityType entityType, bool skipWriting, SelectedPropertiesNode selectedProperties, ODataUri odataUri) : base(feed, navigationSource, entityType, skipWriting, selectedProperties, odataUri) { } /// <summary> /// true if the author element was already written, false otherwise. /// </summary> internal bool AuthorWritten { get { return this.authorWritten; } set { this.authorWritten = value; } } } /// <summary> /// A scope for an entry in ATOM writer. /// </summary> private sealed class AtomEntryScope : EntryScope { /// <summary>Bit field of the ATOM elements written so far.</summary> private int alreadyWrittenElements; /// <summary> /// Constructor to create a new entry scope. /// </summary> /// <param name="entry">The entry for the new scope.</param> /// <param name="serializationInfo">The serialization info for the current entry.</param> /// <param name="navigationSource">The navigation source we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <param name="skipWriting">true if the content of the scope to create should not be written.</param> /// <param name="writingResponse">true if we are writing a response, false if it's a request.</param> /// <param name="writerBehavior">The <see cref="ODataWriterBehavior"/> instance controlling the behavior of the writer.</param> /// <param name="selectedProperties">The selected properties of this scope.</param> /// <param name="odataUri">The ODataUri info of this scope.</param> internal AtomEntryScope(ODataEntry entry, ODataFeedAndEntrySerializationInfo serializationInfo, IEdmNavigationSource navigationSource, IEdmEntityType entityType, bool skipWriting, bool writingResponse, ODataWriterBehavior writerBehavior, SelectedPropertiesNode selectedProperties, ODataUri odataUri) : base(entry, serializationInfo, navigationSource, entityType, skipWriting, writingResponse, writerBehavior, selectedProperties, odataUri) { } /// <summary> /// Marks the <paramref name="atomElement"/> as written in this entry scope. /// </summary> /// <param name="atomElement">The ATOM element which was written.</param> internal void SetWrittenElement(AtomElement atomElement) { Debug.Assert(!this.IsElementWritten(atomElement), "Can't write the same element twice."); this.alreadyWrittenElements |= (int)atomElement; } /// <summary> /// Determines if the <paramref name="atomElement"/> was already written for this entry scope. /// </summary> /// <param name="atomElement">The ATOM element to test for.</param> /// <returns>true if the <paramref name="atomElement"/> was already written for this entry scope; false otherwise.</returns> internal bool IsElementWritten(AtomElement atomElement) { return (this.alreadyWrittenElements & (int)atomElement) == (int)atomElement; } } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Tencent.Mapsdk.Raster.Model { // Metadata.xml XPath class reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']" [global::Android.Runtime.Register ("com/tencent/mapsdk/raster/model/CircleOptions", DoNotGenerateAcw=true)] public sealed partial class CircleOptions : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/tencent/mapsdk/raster/model/CircleOptions", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (CircleOptions); } } internal CircleOptions (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/constructor[@name='CircleOptions' and count(parameter)=0]" [Register (".ctor", "()V", "")] public CircleOptions () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (CircleOptions)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } static IntPtr id_getCenter; public global::Com.Tencent.Mapsdk.Raster.Model.LatLng Center { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='getCenter' and count(parameter)=0]" [Register ("getCenter", "()Lcom/tencent/mapsdk/raster/model/LatLng;", "GetGetCenterHandler")] get { if (id_getCenter == IntPtr.Zero) id_getCenter = JNIEnv.GetMethodID (class_ref, "getCenter", "()Lcom/tencent/mapsdk/raster/model/LatLng;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (JNIEnv.CallObjectMethod (Handle, id_getCenter), JniHandleOwnership.TransferLocalRef); } } static IntPtr id_getFillColor; public int FillColor { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='getFillColor' and count(parameter)=0]" [Register ("getFillColor", "()I", "GetGetFillColorHandler")] get { if (id_getFillColor == IntPtr.Zero) id_getFillColor = JNIEnv.GetMethodID (class_ref, "getFillColor", "()I"); return JNIEnv.CallIntMethod (Handle, id_getFillColor); } } static IntPtr id_isVisible; public bool IsVisible { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='isVisible' and count(parameter)=0]" [Register ("isVisible", "()Z", "GetIsVisibleHandler")] get { if (id_isVisible == IntPtr.Zero) id_isVisible = JNIEnv.GetMethodID (class_ref, "isVisible", "()Z"); return JNIEnv.CallBooleanMethod (Handle, id_isVisible); } } static IntPtr id_getRadius; public double Radius { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='getRadius' and count(parameter)=0]" [Register ("getRadius", "()D", "GetGetRadiusHandler")] get { if (id_getRadius == IntPtr.Zero) id_getRadius = JNIEnv.GetMethodID (class_ref, "getRadius", "()D"); return JNIEnv.CallDoubleMethod (Handle, id_getRadius); } } static IntPtr id_getStrokeColor; public int StrokeColor { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='getStrokeColor' and count(parameter)=0]" [Register ("getStrokeColor", "()I", "GetGetStrokeColorHandler")] get { if (id_getStrokeColor == IntPtr.Zero) id_getStrokeColor = JNIEnv.GetMethodID (class_ref, "getStrokeColor", "()I"); return JNIEnv.CallIntMethod (Handle, id_getStrokeColor); } } static IntPtr id_getStrokeWidth; public float StrokeWidth { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='getStrokeWidth' and count(parameter)=0]" [Register ("getStrokeWidth", "()F", "GetGetStrokeWidthHandler")] get { if (id_getStrokeWidth == IntPtr.Zero) id_getStrokeWidth = JNIEnv.GetMethodID (class_ref, "getStrokeWidth", "()F"); return JNIEnv.CallFloatMethod (Handle, id_getStrokeWidth); } } static IntPtr id_getZIndex; public float ZIndex { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='getZIndex' and count(parameter)=0]" [Register ("getZIndex", "()F", "GetGetZIndexHandler")] get { if (id_getZIndex == IntPtr.Zero) id_getZIndex = JNIEnv.GetMethodID (class_ref, "getZIndex", "()F"); return JNIEnv.CallFloatMethod (Handle, id_getZIndex); } } static IntPtr id_center_Lcom_tencent_mapsdk_raster_model_LatLng_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='center' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLng']]" [Register ("center", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Lcom/tencent/mapsdk/raster/model/CircleOptions;", "")] public global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions InvokeCenter (global::Com.Tencent.Mapsdk.Raster.Model.LatLng p0) { if (id_center_Lcom_tencent_mapsdk_raster_model_LatLng_ == IntPtr.Zero) id_center_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNIEnv.GetMethodID (class_ref, "center", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Lcom/tencent/mapsdk/raster/model/CircleOptions;"); global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions __ret = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions> (JNIEnv.CallObjectMethod (Handle, id_center_Lcom_tencent_mapsdk_raster_model_LatLng_, new JValue (p0)), JniHandleOwnership.TransferLocalRef); return __ret; } static IntPtr id_describeContents; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='describeContents' and count(parameter)=0]" [Register ("describeContents", "()I", "")] public int DescribeContents () { if (id_describeContents == IntPtr.Zero) id_describeContents = JNIEnv.GetMethodID (class_ref, "describeContents", "()I"); return JNIEnv.CallIntMethod (Handle, id_describeContents); } static IntPtr id_fillColor_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='fillColor' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("fillColor", "(I)Lcom/tencent/mapsdk/raster/model/CircleOptions;", "")] public global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions InvokeFillColor (int p0) { if (id_fillColor_I == IntPtr.Zero) id_fillColor_I = JNIEnv.GetMethodID (class_ref, "fillColor", "(I)Lcom/tencent/mapsdk/raster/model/CircleOptions;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions> (JNIEnv.CallObjectMethod (Handle, id_fillColor_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_radius_D; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='radius' and count(parameter)=1 and parameter[1][@type='double']]" [Register ("radius", "(D)Lcom/tencent/mapsdk/raster/model/CircleOptions;", "")] public global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions InvokeRadius (double p0) { if (id_radius_D == IntPtr.Zero) id_radius_D = JNIEnv.GetMethodID (class_ref, "radius", "(D)Lcom/tencent/mapsdk/raster/model/CircleOptions;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions> (JNIEnv.CallObjectMethod (Handle, id_radius_D, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_strokeColor_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='strokeColor' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("strokeColor", "(I)Lcom/tencent/mapsdk/raster/model/CircleOptions;", "")] public global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions InvokeStrokeColor (int p0) { if (id_strokeColor_I == IntPtr.Zero) id_strokeColor_I = JNIEnv.GetMethodID (class_ref, "strokeColor", "(I)Lcom/tencent/mapsdk/raster/model/CircleOptions;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions> (JNIEnv.CallObjectMethod (Handle, id_strokeColor_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_strokeWidth_F; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='strokeWidth' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("strokeWidth", "(F)Lcom/tencent/mapsdk/raster/model/CircleOptions;", "")] public global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions InvokeStrokeWidth (float p0) { if (id_strokeWidth_F == IntPtr.Zero) id_strokeWidth_F = JNIEnv.GetMethodID (class_ref, "strokeWidth", "(F)Lcom/tencent/mapsdk/raster/model/CircleOptions;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions> (JNIEnv.CallObjectMethod (Handle, id_strokeWidth_F, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_visible_Z; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='visible' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("visible", "(Z)Lcom/tencent/mapsdk/raster/model/CircleOptions;", "")] public global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions Visible (bool p0) { if (id_visible_Z == IntPtr.Zero) id_visible_Z = JNIEnv.GetMethodID (class_ref, "visible", "(Z)Lcom/tencent/mapsdk/raster/model/CircleOptions;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions> (JNIEnv.CallObjectMethod (Handle, id_visible_Z, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_writeToParcel_Landroid_os_Parcel_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='writeToParcel' and count(parameter)=2 and parameter[1][@type='android.os.Parcel'] and parameter[2][@type='int']]" [Register ("writeToParcel", "(Landroid/os/Parcel;I)V", "")] public void WriteToParcel (global::Android.OS.Parcel p0, int p1) { if (id_writeToParcel_Landroid_os_Parcel_I == IntPtr.Zero) id_writeToParcel_Landroid_os_Parcel_I = JNIEnv.GetMethodID (class_ref, "writeToParcel", "(Landroid/os/Parcel;I)V"); JNIEnv.CallVoidMethod (Handle, id_writeToParcel_Landroid_os_Parcel_I, new JValue (p0), new JValue (p1)); } static IntPtr id_zIndex_F; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='CircleOptions']/method[@name='zIndex' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("zIndex", "(F)Lcom/tencent/mapsdk/raster/model/CircleOptions;", "")] public global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions InvokeZIndex (float p0) { if (id_zIndex_F == IntPtr.Zero) id_zIndex_F = JNIEnv.GetMethodID (class_ref, "zIndex", "(F)Lcom/tencent/mapsdk/raster/model/CircleOptions;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.CircleOptions> (JNIEnv.CallObjectMethod (Handle, id_zIndex_F, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/group_service.proto // Original file comments: // Copyright 2016 Google 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. // #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.Cloud.Monitoring.V3 { /// <summary> /// The Group API lets you inspect and manage your /// [groups](google.monitoring.v3.Group). /// /// A group is a named filter that is used to identify /// a collection of monitored resources. Groups are typically used to /// mirror the physical and/or logical topology of the environment. /// Because group membership is computed dynamically, monitored /// resources that are started in the future are automatically placed /// in matching groups. By using a group to name monitored resources in, /// for example, an alert policy, the target of that alert policy is /// updated automatically as monitored resources are added and removed /// from the infrastructure. /// </summary> public static partial class GroupService { static readonly string __ServiceName = "google.monitoring.v3.GroupService"; static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListGroupsRequest> __Marshaller_ListGroupsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListGroupsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListGroupsResponse> __Marshaller_ListGroupsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListGroupsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetGroupRequest> __Marshaller_GetGroupRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetGroupRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.Group> __Marshaller_Group = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.Group.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateGroupRequest> __Marshaller_CreateGroupRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateGroupRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateGroupRequest> __Marshaller_UpdateGroupRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.UpdateGroupRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteGroupRequest> __Marshaller_DeleteGroupRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteGroupRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest> __Marshaller_ListGroupMembersRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse> __Marshaller_ListGroupMembersResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListGroupsRequest, global::Google.Cloud.Monitoring.V3.ListGroupsResponse> __Method_ListGroups = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListGroupsRequest, global::Google.Cloud.Monitoring.V3.ListGroupsResponse>( grpc::MethodType.Unary, __ServiceName, "ListGroups", __Marshaller_ListGroupsRequest, __Marshaller_ListGroupsResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetGroupRequest, global::Google.Cloud.Monitoring.V3.Group> __Method_GetGroup = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetGroupRequest, global::Google.Cloud.Monitoring.V3.Group>( grpc::MethodType.Unary, __ServiceName, "GetGroup", __Marshaller_GetGroupRequest, __Marshaller_Group); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateGroupRequest, global::Google.Cloud.Monitoring.V3.Group> __Method_CreateGroup = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateGroupRequest, global::Google.Cloud.Monitoring.V3.Group>( grpc::MethodType.Unary, __ServiceName, "CreateGroup", __Marshaller_CreateGroupRequest, __Marshaller_Group); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateGroupRequest, global::Google.Cloud.Monitoring.V3.Group> __Method_UpdateGroup = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateGroupRequest, global::Google.Cloud.Monitoring.V3.Group>( grpc::MethodType.Unary, __ServiceName, "UpdateGroup", __Marshaller_UpdateGroupRequest, __Marshaller_Group); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteGroupRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteGroup = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteGroupRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteGroup", __Marshaller_DeleteGroupRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest, global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse> __Method_ListGroupMembers = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest, global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse>( grpc::MethodType.Unary, __ServiceName, "ListGroupMembers", __Marshaller_ListGroupMembersRequest, __Marshaller_ListGroupMembersResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of GroupService</summary> public abstract partial class GroupServiceBase { /// <summary> /// Lists the existing groups. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListGroupsResponse> ListGroups(global::Google.Cloud.Monitoring.V3.ListGroupsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets a single group. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Group> GetGroup(global::Google.Cloud.Monitoring.V3.GetGroupRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates a new group. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Group> CreateGroup(global::Google.Cloud.Monitoring.V3.CreateGroupRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Group> UpdateGroup(global::Google.Cloud.Monitoring.V3.UpdateGroupRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteGroup(global::Google.Cloud.Monitoring.V3.DeleteGroupRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse> ListGroupMembers(global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for GroupService</summary> public partial class GroupServiceClient : grpc::ClientBase<GroupServiceClient> { /// <summary>Creates a new client for GroupService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public GroupServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for GroupService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public GroupServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected GroupServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected GroupServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists the existing groups. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListGroupsResponse ListGroups(global::Google.Cloud.Monitoring.V3.ListGroupsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListGroups(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the existing groups. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListGroupsResponse ListGroups(global::Google.Cloud.Monitoring.V3.ListGroupsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListGroups, null, options, request); } /// <summary> /// Lists the existing groups. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListGroupsResponse> ListGroupsAsync(global::Google.Cloud.Monitoring.V3.ListGroupsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListGroupsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the existing groups. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListGroupsResponse> ListGroupsAsync(global::Google.Cloud.Monitoring.V3.ListGroupsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListGroups, null, options, request); } /// <summary> /// Gets a single group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Group GetGroup(global::Google.Cloud.Monitoring.V3.GetGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetGroup(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Group GetGroup(global::Google.Cloud.Monitoring.V3.GetGroupRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetGroup, null, options, request); } /// <summary> /// Gets a single group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Group> GetGroupAsync(global::Google.Cloud.Monitoring.V3.GetGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetGroupAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Group> GetGroupAsync(global::Google.Cloud.Monitoring.V3.GetGroupRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetGroup, null, options, request); } /// <summary> /// Creates a new group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Group CreateGroup(global::Google.Cloud.Monitoring.V3.CreateGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateGroup(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Group CreateGroup(global::Google.Cloud.Monitoring.V3.CreateGroupRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateGroup, null, options, request); } /// <summary> /// Creates a new group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Group> CreateGroupAsync(global::Google.Cloud.Monitoring.V3.CreateGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateGroupAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Group> CreateGroupAsync(global::Google.Cloud.Monitoring.V3.CreateGroupRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateGroup, null, options, request); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Group UpdateGroup(global::Google.Cloud.Monitoring.V3.UpdateGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateGroup(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Group UpdateGroup(global::Google.Cloud.Monitoring.V3.UpdateGroupRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateGroup, null, options, request); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Group> UpdateGroupAsync(global::Google.Cloud.Monitoring.V3.UpdateGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateGroupAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Group> UpdateGroupAsync(global::Google.Cloud.Monitoring.V3.UpdateGroupRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateGroup, null, options, request); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteGroup(global::Google.Cloud.Monitoring.V3.DeleteGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteGroup(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteGroup(global::Google.Cloud.Monitoring.V3.DeleteGroupRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteGroup, null, options, request); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteGroupAsync(global::Google.Cloud.Monitoring.V3.DeleteGroupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteGroupAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteGroupAsync(global::Google.Cloud.Monitoring.V3.DeleteGroupRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteGroup, null, options, request); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse ListGroupMembers(global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListGroupMembers(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse ListGroupMembers(global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListGroupMembers, null, options, request); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse> ListGroupMembersAsync(global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListGroupMembersAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse> ListGroupMembersAsync(global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListGroupMembers, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override GroupServiceClient NewInstance(ClientBaseConfiguration configuration) { return new GroupServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(GroupServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListGroups, serviceImpl.ListGroups) .AddMethod(__Method_GetGroup, serviceImpl.GetGroup) .AddMethod(__Method_CreateGroup, serviceImpl.CreateGroup) .AddMethod(__Method_UpdateGroup, serviceImpl.UpdateGroup) .AddMethod(__Method_DeleteGroup, serviceImpl.DeleteGroup) .AddMethod(__Method_ListGroupMembers, serviceImpl.ListGroupMembers).Build(); } } } #endregion
#region Copyright Notice // Copyright 2011-2013 Eleftherios Aslanoglou // // 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 #region Using Directives using System.Collections.Generic; using System.ComponentModel; #endregion namespace NBA_2K13_Roster_Editor.Data.Jerseys { internal class JerseyEntry : INotifyPropertyChanged { public static readonly Dictionary<string, string> JerseyNames = new Dictionary<string, string> { {"Practice", "47CA3480"}, {"Home", "BF4718D0"}, {"Away", "A2B39EF0"}, {"Alternate", "CCBB71E8"}, {"BackInBlack", "AC59B740"}, {"Cavfanatic", "3C9CA188"}, {"Christmas", "A2F5D7D8"}, {"LatinNights", "49F9B0A0"}, {"MardiGras", "51F9A520"}, {"MilitaryNight", "EBDF3AD8"}, {"NBAGreen", "EFDEB770"}, {"Racing", "BE62D5B0"}, {"RipCity", "2351B428"}, {"StPatricks", "CD16A528"}, {"WhiteHot", "F3992170"}, {"ClassicHomeI", "3871FBA0"}, {"ClassicAwayI", "C4BFEE20"}, {"ClassAwayIAlt", "43963E40"}, {"ClassicHomeII", "5EF2F550"}, {"ClassicAwayII", "0703A720"}, {"ClassicAwayIIAlt", "1B04E3B0"}, {"ClassicHomeIII", "54CB88C0"}, {"ClassicAwayIII", "D9B11D28"}, {"ClassicAwayIIIAtl", "7A908530"}, {"ClassicHomeIV", "537E3460"}, {"ClassicAwayIV", "0A8F6610"}, {"ClassicAwayIVAlt", "247053D8"}, {"ClassicHomeV", "35FD3A90"}, {"ClassicAwayV", "C9332F10"}, {"ClassicAwayVAlt", "7CE28E28"}, {"ClassicHomeVI", "CF935678"}, {"ClassicAwayVI", "96620408"}, {"ClassicAwayVIAlt", "E8B072E8"}, {"ClassicHomeVII", "BC9E47D8"}, {"ClassicAwayVII", "31E4D230"}, {"j2012", "3B5EC208"}, {"j2013", "0121C8D0"}, {"Unknown1", "43E04D18"}, {"j1990", "4A5A2B80"}, {"j1991", "5C385408"}, {"NBA2K13", "1BA16098"}, {"j1992", "B341BC50"}, {"j1986", "1DB2C458"}, {"j1995", "882F9C28"}, {"j1996", "125C4998"}, {"j1998", "9B637C18"}, {"j1965", "D8D25368"}, {"j1971", "032B1688"}, {"j1972", "9958C338"}, {"j1985", "87C111E8"}, {"Unknown2", "1764A778"}, {"j1989", "20717B80"}, {"Rookies", "307D6468"}, {"Custom1", "307D646D"}, {"Custom2", "307D646E"}, {"Custom3", "307D646F"}, {"j1993", "3633B018"}, {"j2002", "589A1B50"}, {"j1977", "BD373AB8"}, {"j2001", "C2E9CEE0"}, {"j1987", "EDCAF5F8"}, {"j1994", "F2AC2AD8"}, {"CAT", "00000000"}, }; // This makes sure jersey names show up in-game after a change #region Name Display public enum NameDisplay : ushort { PHI_PracticeHome = 0, PHI_PracticeAway = 0, CHA_PracticeHome = 184, CHA_PracticeAway = 184, MIL_PracticeHome = 360, MIL_PracticeAway = 360, CHI_PracticeHome = 520, CHI_PracticeAway = 520, CLE_PracticeHome = 712, CLE_PracticeAway = 712, BOS_PracticeHome = 880, BOS_PracticeAway = 880, LAC_PracticeHome = 1176, LAC_PracticeAway = 1176, MEM_PracticeHome = 1392, MEM_PracticeAway = 1392, ATL_PracticeHome = 1584, ATL_PracticeAway = 1584, MIA_PracticeHome = 1736, MIA_PracticeAway = 1736, NOH_PracticeHome = 1904, NOH_PracticeAway = 1904, UTA_PracticeHome = 2112, UTA_PracticeAway = 2112, SAC_PracticeHome = 2264, SAC_PracticeAway = 2264, NYK_PracticeHome = 2432, NYK_PracticeAway = 2432, LAL_PracticeHome = 2688, LAL_PracticeAway = 2688, ORL_PracticeHome = 2808, ORL_PracticeAway = 2808, DAL_PracticeHome = 3000, DAL_PracticeAway = 3000, BKN_PracticeHome = 3144, BKN_PracticeAway = 3144, DEN_PracticeHome = 3312, DEN_PracticeAway = 3312, IND_PracticeHome = 3560, IND_PracticeAway = 3560, DET_PracticeHome = 3808, DET_PracticeAway = 3808, TOR_PracticeHome = 4000, TOR_PracticeAway = 4000, HOU_PracticeHome = 4192, HOU_PracticeAway = 4192, SAS_PracticeHome = 4368, SAS_PracticeAway = 4368, PHX_PracticeHome = 4520, PHX_PracticeAway = 4520, OKC_PracticeHome = 4688, OKC_PracticeAway = 4688, MIN_PracticeHome = 5032, MIN_PracticeAway = 5032, POR_PracticeHome = 5312, POR_PracticeAway = 5312, GSW_PracticeHome = 5616, GSW_PracticeAway = 5616, WAS_PracticeHome = 5816, WAS_PracticeAway = 5816, PHI_Home = 4, PHI_Away = 6, PHI_Alternate = 0, PHI_ClassicAwayI = 1, PHI_ClassicHomeII = 0, PHI_ClassicAwayIII = 5, PHI_ClassicAwayIV = 5, PHI_ClassicAwayV = 2, PHI_ClassicHomeVI = 6, PHI_ClassicAwayVI = 0, PHI_ClassicAwayVIAlt = 3, PHI_ClassicHomeVII = 2, PHI_ClassicAwayVII = 6, CHA_Home = 188, CHA_Away = 190, CHA_Racing = 187, CHA_NBAGreen = 188, CHA_ClassicHomeI = 183, CHA_ClassicAwayI = 185, CHA_ClassAwayIAlt = 183, CHA_ClassicHomeII = 184, MIL_Home = 364, MIL_Away = 366, MIL_Alternate = 360, MIL_ClassicHomeI = 359, MIL_ClassicAwayI = 361, MIL_ClassicHomeII = 360, MIL_ClassicAwayII = 366, MIL_ClassicHomeIII = 361, MIL_ClassicAwayIV = 365, CHI_Home = 524, CHI_Away = 526, CHI_Alternate = 520, CHI_LatinNights = 523, CHI_StPatricks = 520, CHI_NBAGreen = 524, CHI_ClassicAwayI = 521, CHI_ClassicAwayII = 526, CHI_Christmas = 520, CLE_Home = 716, CLE_Away = 718, CLE_Alternate = 712, CLE_Cavfanatic = 717, CLE_ClassicHomeI = 711, CLE_ClassicAwayI = 713, CLE_ClassicHomeII = 712, CLE_ClassicAwayII = 718, CLE_ClassicHomeIII = 713, CLE_ClassicAwayIII = 717, CLE_ClassicHomeIV = 711, CLE_ClassicAwayIV = 717, CLE_ClassicAwayIVAlt = 712, CLE_ClassicHomeV = 712, CLE_ClassicAwayV = 714, CLE_ClassicAwayVAlt = 717, BOS_Home = 884, BOS_Away = 886, BOS_Alternate = 880, BOS_StPatricks = 880, BOS_ClassicHomeI = 879, BOS_Christmas = 880, LAC_Home = 1180, LAC_Away = 1182, LAC_Alternate = 1176, LAC_ClassicAwayI = 1177, LAC_ClassicHomeII = 1176, LAC_ClassicAwayII = 1182, LAC_ClassicAwayIIAlt = 1182, LAC_ClassicAwayIII = 1181, LAC_Christmas = 1176, MEM_Home = 1396, MEM_Away = 1398, MEM_Alternate = 1392, MEM_ClassicHomeI = 1391, MEM_ClassicAwayI = 1393, MEM_ClassicAwayII = 1398, ATL_Home = 1588, ATL_Away = 1590, ATL_Alternate = 1584, ATL_ClassicHomeI = 1583, ATL_ClassicAwayI = 1585, ATL_ClassicHomeII = 1584, ATL_ClassicAwayII = 1590, ATL_ClassicHomeIII = 1585, ATL_ClassicAwayIII = 1589, ATL_ClassicAwayIIIAtl = 1589, ATL_ClassicAwayIV = 1589, MIA_Home = 1740, MIA_Away = 1742, MIA_Alternate = 1736, MIA_WhiteHot = 1742, MIA_BackInBlack = 1738, MIA_LatinNights = 1739, MIA_ClassicHomeI = 1735, MIA_ClassicAwayI = 1737, MIA_ClassAwayIAlt = 1735, MIA_ClassicHomeII = 1736, MIA_Christmas = 1736, NOH_Home = 1908, NOH_Away = 1910, NOH_Alternate = 1904, NOH_MardiGras = 1906, NOH_ClassicHomeI = 1903, NOH_ClassicAwayI = 1905, NOH_ClassAwayIAlt = 1903, NOH_ClassicHomeII = 1904, NOH_ClassicAwayII = 1910, NOH_ClassicHomeIII = 1905, NOH_ClassicAwayIII = 1909, NOH_ClassicAwayIIIAtl = 1909, UTA_Home = 2116, UTA_Away = 2118, UTA_Alternate = 2112, UTA_ClassicHomeI = 2111, UTA_ClassicAwayI = 2113, UTA_ClassicHomeII = 2112, UTA_ClassicAwayII = 2118, UTA_ClassicAwayIII = 2117, UTA_ClassicHomeIV = 2111, UTA_ClassicAwayIV = 2117, UTA_ClassicAwayIVAlt = 2112, SAC_Home = 2268, SAC_Away = 2270, SAC_Alternate = 2264, SAC_ClassicAwayI = 2265, SAC_ClassicHomeII = 2264, SAC_ClassicAwayII = 2270, SAC_ClassicHomeIII = 2265, SAC_ClassicAwayIII = 2269, SAC_ClassicAwayIIIAtl = 2269, SAC_ClassicHomeIV = 2263, SAC_ClassicAwayV = 2266, NYK_Home = 2436, NYK_Away = 2438, NYK_LatinNights = 2435, NYK_StPatricks = 2432, NYK_ClassicHomeI = 2431, NYK_ClassicAwayI = 2433, NYK_ClassicHomeII = 2432, NYK_ClassicAwayII = 2438, NYK_ClassicAwayIII = 2437, NYK_Christmas = 2432, LAL_Home = 2692, LAL_Alternate = 2688, LAL_Away = 2694, LAL_LatinNights = 2691, LAL_ClassicHomeI = 2687, LAL_ClassicAwayI = 2689, LAL_ClassicHomeII = 2688, LAL_ClassicAwayII = 2694, LAL_ClassicHomeIII = 2689, LAL_ClassicAwayIII = 2693, LAL_ClassicHomeIV = 2687, LAL_Christmas = 2688, ORL_Home = 2812, ORL_Away = 2814, ORL_Alternate = 2808, ORL_LatinNights = 2811, ORL_ClassicHomeI = 2807, ORL_ClassicAwayI = 2809, ORL_ClassAwayIAlt = 2807, ORL_ClassicHomeII = 2808, ORL_ClassicAwayII = 2814, DAL_Home = 3004, DAL_Away = 3006, DAL_Alternate = 3000, DAL_LatinNights = 3003, DAL_ClassicHomeI = 2999, DAL_ClassicAwayI = 3001, BKN_Home = 3148, BKN_Away = 3150, BKN_ClassicAwayI = 3145, BKN_ClassicHomeII = 3144, BKN_ClassicAwayII = 3150, BKN_Christmas = 3144, DEN_Home = 3316, DEN_Away = 3318, DEN_Alternate = 3312, DEN_NBAGreen = 3316, DEN_ClassicHomeI = 3311, DEN_ClassicAwayI = 3313, DEN_ClassicHomeII = 3312, DEN_ClassicHomeIII = 3313, DEN_Christmas = 3312, IND_Home = 3564, IND_Away = 3566, IND_Alternate = 3560, IND_ClassicAwayI = 3561, IND_ClassicHomeII = 3560, IND_ClassicAwayII = 3566, IND_ClassicAwayIIAlt = 3566, IND_ClassicHomeIII = 3561, IND_ClassicAwayIV = 3565, DET_Home = 3812, DET_Away = 3814, DET_Alternate = 3808, DET_ClassicHomeI = 3807, DET_ClassicAwayI = 3809, DET_ClassicHomeII = 3808, DET_ClassicAwayII = 3814, DET_ClassicHomeIII = 3809, TOR_Home = 4004, TOR_Away = 4006, TOR_Alternate = 4000, TOR_MilitaryNight = 4005, TOR_StPatricks = 4000, TOR_ClassicHomeI = 3999, TOR_ClassicAwayI = 4001, TOR_ClassicHomeII = 4000, HOU_Home = 4196, HOU_Away = 4198, HOU_Alternate = 4192, HOU_LatinNights = 4195, HOU_ClassicHomeI = 4191, HOU_ClassicAwayI = 4193, HOU_ClassicHomeII = 4192, HOU_ClassicAwayII = 4198, HOU_Christmas = 4192, SAS_Home = 4372, SAS_Away = 4374, SAS_Alternate = 4368, SAS_LatinNights = 4371, SAS_ClassicHomeI = 4367, SAS_ClassicHomeII = 4368, PHX_Home = 4524, PHX_Away = 4526, PHX_Alternate = 4520, PHX_LatinNights = 4523, PHX_ClassicHomeI = 4519, PHX_ClassicAwayI = 4521, PHX_ClassicAwayII = 4526, OKC_Home = 4692, OKC_Away = 4694, OKC_Alternate = 4688, OKC_Christmas = 4688, MIN_Home = 5036, MIN_Away = 5038, MIN_Alternate = 5032, MIN_ClassicHomeI = 5031, MIN_ClassicAwayI = 5033, MIN_ClassicHomeII = 5032, MIN_ClassicAwayII = 5038, MIN_ClassicAwayIIAlt = 5038, MIN_ClassicHomeIII = 5033, POR_Home = 5316, POR_Away = 5318, POR_Alternate = 5312, POR_RipCity = 5315, POR_ClassicHomeI = 5311, POR_ClassicAwayI = 5313, POR_ClassicHomeII = 5312, POR_ClassicAwayII = 5318, GSW_Home = 5620, GSW_Away = 5622, GSW_ClassicHomeI = 5615, GSW_ClassicAwayI = 5617, GSW_ClassicHomeII = 5616, GSW_ClassicHomeIII = 5617, GSW_ClassicAwayIII = 5621, GSW_ClassicHomeIV = 5615, GSW_ClassicAwayIV = 5621, GSW_ClassicAwayIVAlt = 5616, GSW_ClassicHomeV = 5616, WAS_Home = 5820, WAS_Away = 5822, WAS_ClassicHomeI = 5815, WAS_ClassicAwayI = 5817, WAS_ClassicHomeII = 5816, WAS_ClassicHomeIII = 5817, WAS_ClassicHomeIV = 5815, WAS_ClassicAwayIV = 5821, WAS_ClassicAwayIVAlt = 5816, }; #endregion #region Name Display Default public enum NameDisplayDefault : ushort { PHI_PracticeHome = 0, PHI_PracticeAway = 0, CHA_PracticeHome = 184, CHA_PracticeAway = 184, MIL_PracticeHome = 360, MIL_PracticeAway = 360, CHI_PracticeHome = 520, CHI_PracticeAway = 520, CLE_PracticeHome = 712, CLE_PracticeAway = 712, BOS_PracticeHome = 880, BOS_PracticeAway = 880, LAC_PracticeHome = 1176, LAC_PracticeAway = 1176, MEM_PracticeHome = 1392, MEM_PracticeAway = 1392, ATL_PracticeHome = 1584, ATL_PracticeAway = 1584, MIA_PracticeHome = 1736, MIA_PracticeAway = 1736, NOH_PracticeHome = 1904, NOH_PracticeAway = 1904, UTA_PracticeHome = 2112, UTA_PracticeAway = 2112, SAC_PracticeHome = 2264, SAC_PracticeAway = 2264, NYK_PracticeHome = 2432, NYK_PracticeAway = 2432, LAL_PracticeHome = 2688, LAL_PracticeAway = 2688, ORL_PracticeHome = 2808, ORL_PracticeAway = 2808, DAL_PracticeHome = 3000, DAL_PracticeAway = 3000, BKN_PracticeHome = 3144, BKN_PracticeAway = 3144, DEN_PracticeHome = 3312, DEN_PracticeAway = 3312, IND_PracticeHome = 3560, IND_PracticeAway = 3560, DET_PracticeHome = 3808, DET_PracticeAway = 3808, TOR_PracticeHome = 4000, TOR_PracticeAway = 4000, HOU_PracticeHome = 4192, HOU_PracticeAway = 4192, SAS_PracticeHome = 4368, SAS_PracticeAway = 4368, PHX_PracticeHome = 4520, PHX_PracticeAway = 4520, OKC_PracticeHome = 4688, OKC_PracticeAway = 4688, MIN_PracticeHome = 5000, MIN_PracticeAway = 5000, POR_PracticeHome = 5280, POR_PracticeAway = 5280, GSW_PracticeHome = 5584, GSW_PracticeAway = 5584, WAS_PracticeHome = 5784, WAS_PracticeAway = 5784, PHI_Home = 4, PHI_Away = 6, PHI_Alternate = 0, PHI_ClassicAwayI = 1, PHI_ClassicHomeII = 0, PHI_ClassicAwayIII = 5, PHI_ClassicAwayIV = 5, PHI_ClassicAwayV = 2, PHI_ClassicHomeVI = 6, PHI_ClassicAwayVI = 0, PHI_ClassicAwayVIAlt = 3, PHI_ClassicHomeVII = 2, PHI_ClassicAwayVII = 6, CHA_Home = 188, CHA_Away = 190, CHA_Racing = 187, CHA_NBAGreen = 188, CHA_ClassicHomeI = 183, CHA_ClassicAwayI = 185, CHA_ClassAwayIAlt = 183, CHA_ClassicHomeII = 184, MIL_Home = 364, MIL_Away = 366, MIL_Alternate = 360, MIL_ClassicHomeI = 359, MIL_ClassicAwayI = 361, MIL_ClassicHomeII = 360, MIL_ClassicAwayII = 366, MIL_ClassicHomeIII = 361, MIL_ClassicAwayIV = 365, CHI_Home = 524, CHI_Away = 526, CHI_Alternate = 520, CHI_LatinNights = 523, CHI_StPatricks = 520, CHI_NBAGreen = 524, CHI_ClassicAwayI = 521, CHI_ClassicAwayII = 526, CHI_Christmas = 520, CLE_Home = 716, CLE_Away = 718, CLE_Alternate = 712, CLE_Cavfanatic = 717, CLE_ClassicHomeI = 711, CLE_ClassicAwayI = 713, CLE_ClassicHomeII = 712, CLE_ClassicAwayII = 718, CLE_ClassicHomeIII = 713, CLE_ClassicAwayIII = 717, CLE_ClassicHomeIV = 711, CLE_ClassicAwayIV = 717, CLE_ClassicAwayIVAlt = 712, CLE_ClassicHomeV = 712, CLE_ClassicAwayV = 714, CLE_ClassicAwayVAlt = 717, BOS_Home = 884, BOS_Away = 886, BOS_Alternate = 880, BOS_StPatricks = 880, BOS_ClassicHomeI = 879, BOS_Christmas = 880, LAC_Home = 1180, LAC_Away = 1182, LAC_Alternate = 1176, LAC_ClassicAwayI = 1177, LAC_ClassicHomeII = 1176, LAC_ClassicAwayII = 1182, LAC_ClassicAwayIIAlt = 1182, LAC_ClassicAwayIII = 1181, LAC_Christmas = 1176, MEM_Home = 1396, MEM_Away = 1398, MEM_Alternate = 1392, MEM_ClassicHomeI = 1391, MEM_ClassicAwayI = 1393, MEM_ClassicAwayII = 1398, ATL_Home = 1588, ATL_Away = 1590, ATL_Alternate = 1584, ATL_ClassicHomeI = 1583, ATL_ClassicAwayI = 1585, ATL_ClassicHomeII = 1584, ATL_ClassicAwayII = 1590, ATL_ClassicHomeIII = 1585, ATL_ClassicAwayIII = 1589, ATL_ClassicAwayIIIAtl = 1589, ATL_ClassicAwayIV = 1589, MIA_Home = 1740, MIA_Away = 1742, MIA_Alternate = 1736, MIA_WhiteHot = 1742, MIA_BackInBlack = 1738, MIA_LatinNights = 1739, MIA_ClassicHomeI = 1735, MIA_ClassicAwayI = 1737, MIA_ClassAwayIAlt = 1735, MIA_ClassicHomeII = 1736, MIA_Christmas = 1736, NOH_Home = 1908, NOH_Away = 1910, NOH_Alternate = 1904, NOH_MardiGras = 1906, NOH_ClassicHomeI = 1903, NOH_ClassicAwayI = 1905, NOH_ClassAwayIAlt = 1903, NOH_ClassicHomeII = 1904, NOH_ClassicAwayII = 1910, NOH_ClassicHomeIII = 1905, NOH_ClassicAwayIII = 1909, NOH_ClassicAwayIIIAtl = 1909, UTA_Home = 2116, UTA_Away = 2118, UTA_Alternate = 2112, UTA_ClassicHomeI = 2111, UTA_ClassicAwayI = 2113, UTA_ClassicHomeII = 2112, UTA_ClassicAwayII = 2118, UTA_ClassicAwayIII = 2117, UTA_ClassicHomeIV = 2111, UTA_ClassicAwayIV = 2117, UTA_ClassicAwayIVAlt = 2112, SAC_Home = 2268, SAC_Away = 2270, SAC_Alternate = 2264, SAC_ClassicAwayI = 2265, SAC_ClassicHomeII = 2264, SAC_ClassicAwayII = 2270, SAC_ClassicHomeIII = 2265, SAC_ClassicAwayIII = 2269, SAC_ClassicAwayIIIAtl = 2269, SAC_ClassicHomeIV = 2263, SAC_ClassicAwayV = 2266, NYK_Home = 2436, NYK_Away = 2438, NYK_LatinNights = 2435, NYK_StPatricks = 2432, NYK_ClassicHomeI = 2431, NYK_ClassicAwayI = 2433, NYK_ClassicHomeII = 2432, NYK_ClassicAwayII = 2438, NYK_ClassicAwayIII = 2437, NYK_Christmas = 2432, LAL_Home = 2692, LAL_Alternate = 2688, LAL_Away = 2694, LAL_LatinNights = 2691, LAL_ClassicHomeI = 2687, LAL_ClassicAwayI = 2689, LAL_ClassicHomeII = 2688, LAL_ClassicAwayII = 2694, LAL_ClassicHomeIII = 2689, LAL_ClassicAwayIII = 2693, LAL_ClassicHomeIV = 2687, LAL_Christmas = 2688, ORL_Home = 2812, ORL_Away = 2814, ORL_Alternate = 2808, ORL_LatinNights = 2811, ORL_ClassicHomeI = 2807, ORL_ClassicAwayI = 2809, ORL_ClassAwayIAlt = 2807, ORL_ClassicHomeII = 2808, ORL_ClassicAwayII = 2814, DAL_Home = 3004, DAL_Away = 3006, DAL_Alternate = 3000, DAL_LatinNights = 3003, DAL_ClassicHomeI = 2999, DAL_ClassicAwayI = 3001, BKN_Home = 3148, BKN_Away = 3150, BKN_ClassicAwayI = 3145, BKN_ClassicHomeII = 3144, BKN_ClassicAwayII = 3150, BKN_Christmas = 3144, DEN_Home = 3316, DEN_Away = 3318, DEN_Alternate = 3312, DEN_NBAGreen = 3316, DEN_ClassicHomeI = 3311, DEN_ClassicAwayI = 3313, DEN_ClassicHomeII = 3312, DEN_ClassicHomeIII = 3313, DEN_Christmas = 3312, IND_Home = 3564, IND_Away = 3566, IND_Alternate = 3560, IND_ClassicAwayI = 3561, IND_ClassicHomeII = 3560, IND_ClassicAwayII = 3566, IND_ClassicAwayIIAlt = 3566, IND_ClassicHomeIII = 3561, IND_ClassicAwayIV = 3565, DET_Home = 3812, DET_Away = 3814, DET_Alternate = 3808, DET_ClassicHomeI = 3807, DET_ClassicAwayI = 3809, DET_ClassicHomeII = 3808, DET_ClassicAwayII = 3814, DET_ClassicHomeIII = 3809, TOR_Home = 4004, TOR_Away = 4006, TOR_Alternate = 4000, TOR_MilitaryNight = 4005, TOR_StPatricks = 4000, TOR_ClassicHomeI = 3999, TOR_ClassicAwayI = 4001, TOR_ClassicHomeII = 4000, HOU_Home = 4196, HOU_Away = 4198, HOU_Alternate = 4192, HOU_LatinNights = 4195, HOU_ClassicHomeI = 4191, HOU_ClassicAwayI = 4193, HOU_ClassicHomeII = 4192, HOU_ClassicAwayII = 4198, HOU_Christmas = 4192, SAS_Home = 4372, SAS_Away = 4374, SAS_Alternate = 4368, SAS_LatinNights = 4371, SAS_ClassicHomeI = 4367, SAS_ClassicHomeII = 4368, PHX_Home = 4524, PHX_Away = 4526, PHX_Alternate = 4520, PHX_LatinNights = 4523, PHX_ClassicHomeI = 4519, PHX_ClassicAwayI = 4521, PHX_ClassicAwayII = 4526, OKC_Home = 4692, OKC_Away = 4694, OKC_Alternate = 4688, OKC_Christmas = 4688, MIN_Home = 5004, MIN_Away = 5006, MIN_Alternate = 5000, MIN_ClassicHomeI = 4999, MIN_ClassicAwayI = 5001, MIN_ClassicHomeII = 5000, MIN_ClassicAwayII = 5006, MIN_ClassicAwayIIAlt = 5006, MIN_ClassicHomeIII = 5001, POR_Home = 5284, POR_Away = 5286, POR_Alternate = 5280, POR_RipCity = 5283, POR_ClassicHomeI = 5279, POR_ClassicAwayI = 5281, POR_ClassicHomeII = 5280, POR_ClassicAwayII = 5286, GSW_Home = 5588, GSW_Away = 5590, GSW_ClassicHomeI = 5583, GSW_ClassicAwayI = 5585, GSW_ClassicHomeII = 5584, GSW_ClassicHomeIII = 5585, GSW_ClassicAwayIII = 5589, GSW_ClassicHomeIV = 5583, GSW_ClassicAwayIV = 5589, GSW_ClassicAwayIVAlt = 5584, GSW_ClassicHomeV = 5584, WAS_Home = 5788, WAS_Away = 5790, WAS_ClassicHomeI = 5783, WAS_ClassicAwayI = 5785, WAS_ClassicHomeII = 5784, WAS_ClassicHomeIII = 5785, WAS_ClassicHomeIV = 5783, WAS_ClassicAwayIV = 5789, WAS_ClassicAwayIVAlt = 5784, }; #endregion private JerseyType _gid; private int _id; private JerseyName _name; private JerseyArt _art; private NeckType _neck; private SockColor _sockClr; private string _teamColor1; private string _teamColor2; private string _teamColor3; private string _teamColor4; private string _teamColor5; private string _teamColor6; public int ID { get { return _id; } set { _id = value; OnPropertyChanged("ID"); } } public JerseyType GID { get { return _gid; } set { _gid = value; OnPropertyChanged("GID"); } } public NeckType Neck { get { return _neck; } set { _neck = value; OnPropertyChanged("Neck"); } } public SockColor SockClr { get { return _sockClr; } set { _sockClr = value; OnPropertyChanged("SockClr"); } } public string TeamColor1 { get { return _teamColor1; } set { _teamColor1 = value; OnPropertyChanged("TeamColor1"); } } public string TeamColor2 { get { return _teamColor2; } set { _teamColor2 = value; OnPropertyChanged("TeamColor2"); } } public string TeamColor3 { get { return _teamColor3; } set { _teamColor3 = value; OnPropertyChanged("TeamColor3"); } } public string TeamColor4 { get { return _teamColor4; } set { _teamColor4 = value; OnPropertyChanged("TeamColor4"); } } public string TeamColor5 { get { return _teamColor5; } set { _teamColor5 = value; OnPropertyChanged("TeamColor5"); } } public string TeamColor6 { get { return _teamColor6; } set { _teamColor6 = value; OnPropertyChanged("TeamColor6"); } } public JerseyName Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public JerseyArt Art { get { return _art; } set { _art = value; OnPropertyChanged("Art"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // 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 System.Collections.Generic; using System.Linq; namespace NLog.Layouts { using System; using System.Collections.ObjectModel; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Represents a string with embedded placeholders that can render contextual information. /// </summary> /// <remarks> /// This layout is not meant to be used explicitly. Instead you can just use a string containing layout /// renderers everywhere the layout is required. /// </remarks> [Layout("SimpleLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class SimpleLayout : Layout, IUsesStackTrace { private const int MaxInitialRenderBufferLength = 16384; private int maxRenderedLength; private string fixedText; private string layoutText; private ConfigurationItemFactory configurationItemFactory; /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> public SimpleLayout() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> /// <param name="txt">The layout string to parse.</param> public SimpleLayout(string txt) : this(txt, ConfigurationItemFactory.Default) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> public SimpleLayout(string txt, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.Text = txt; } internal SimpleLayout(LayoutRenderer[] renderers, string text, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.SetRenderers(renderers, text); } /// <summary> /// Original text before compile to Layout renderes /// </summary> public string OriginalText { get; private set; } /// <summary> /// Gets or sets the layout text. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Text { get { return this.layoutText; } set { OriginalText = value; LayoutRenderer[] renderers; string txt; renderers = LayoutParser.CompileLayout( this.configurationItemFactory, new SimpleStringReader(value), false, out txt); this.SetRenderers(renderers, txt); } } /// <summary> /// Is the message fixed? (no Layout renderers used) /// </summary> public bool IsFixedText { get { return this.fixedText != null; } } /// <summary> /// Get the fixed text. Only set when <see cref="IsFixedText"/> is <c>true</c> /// </summary> public string FixedText { get { return fixedText; } } /// <summary> /// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout. /// </summary> public ReadOnlyCollection<LayoutRenderer> Renderers { get; private set; } /// <summary> /// Gets the level of stack trace information required for rendering. /// </summary> /// <remarks>Calculated when setting <see cref="Renderers"/>.</remarks> public StackTraceUsage StackTraceUsage { get; private set; } /// <summary> /// Converts a text to a simple layout. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns>A <see cref="SimpleLayout"/> object.</returns> public static implicit operator SimpleLayout(string text) { return new SimpleLayout(text); } /// <summary> /// Escapes the passed text so that it can /// be used literally in all places where /// layout is normally expected without being /// treated as layout. /// </summary> /// <param name="text">The text to be escaped.</param> /// <returns>The escaped text.</returns> /// <remarks> /// Escaping is done by replacing all occurrences of /// '${' with '${literal:text=${}' /// </remarks> public static string Escape(string text) { return text.Replace("${", "${literal:text=${}"); } /// <summary> /// Evaluates the specified text by expanding all layout renderers. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <param name="logEvent">Log event to be used for evaluation.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text, LogEventInfo logEvent) { var l = new SimpleLayout(text); return l.Render(logEvent); } /// <summary> /// Evaluates the specified text by expanding all layout renderers /// in new <see cref="LogEventInfo" /> context. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text) { return Evaluate(text, LogEventInfo.CreateNullEvent()); } /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current object. /// </returns> public override string ToString() { return "'" + this.Text + "'"; } internal void SetRenderers(LayoutRenderer[] renderers, string text) { this.Renderers = new ReadOnlyCollection<LayoutRenderer>(renderers); if (this.Renderers.Count == 0) { //todo fixedText = null is also used if the text is fixed, but is a empty renderers not fixed? this.fixedText = null; this.StackTraceUsage = StackTraceUsage.None; } else if (this.Renderers.Count == 1 && this.Renderers[0] is LiteralLayoutRenderer) { this.fixedText = ((LiteralLayoutRenderer)this.Renderers[0]).Text; this.StackTraceUsage = StackTraceUsage.None; } else { this.fixedText = null; this.StackTraceUsage = this.Renderers.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(usage => usage == null ? StackTraceUsage.None : usage.StackTraceUsage); } this.layoutText = text; } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers /// that make up the event. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { if (IsFixedText) { return this.fixedText; } string cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { return cachedValue; } int initialSize = this.maxRenderedLength; if (initialSize > MaxInitialRenderBufferLength) { initialSize = MaxInitialRenderBufferLength; } var builder = new StringBuilder(initialSize); //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < this.Renderers.Count; i++) { LayoutRenderer renderer = this.Renderers[i]; try { renderer.Render(builder, logEvent); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.Append()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } if (builder.Length > this.maxRenderedLength) { this.maxRenderedLength = builder.Length; } string value = builder.ToString(); logEvent.AddCachedLayoutValue(this, value); return value; } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using ServiceStack.Text.Common; using ServiceStack.Text.Support; #if NETFX_CORE using System.Threading.Tasks; #endif #if WINDOWS_PHONE using System.IO.IsolatedStorage; #if !WP8 using ServiceStack.Text.WP; #endif #endif namespace ServiceStack.Text { public static class StringExtensions { public static T To<T>(this string value) { return TypeSerializer.DeserializeFromString<T>(value); } public static T To<T>(this string value, T defaultValue) { return string.IsNullOrEmpty(value) ? defaultValue : TypeSerializer.DeserializeFromString<T>(value); } public static T ToOrDefaultValue<T>(this string value) { return string.IsNullOrEmpty(value) ? default(T) : TypeSerializer.DeserializeFromString<T>(value); } public static object To(this string value, Type type) { return TypeSerializer.DeserializeFromString(value, type); } /// <summary> /// Converts from base: 0 - 62 /// </summary> /// <param name="source">The source.</param> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <returns></returns> public static string BaseConvert(this string source, int from, int to) { const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var result = ""; var length = source.Length; var number = new int[length]; for (var i = 0; i < length; i++) { number[i] = chars.IndexOf(source[i]); } int newlen; do { var divide = 0; newlen = 0; for (var i = 0; i < length; i++) { divide = divide * from + number[i]; if (divide >= to) { number[newlen++] = divide / to; divide = divide % to; } else if (newlen > 0) { number[newlen++] = 0; } } length = newlen; result = chars[divide] + result; } while (newlen != 0); return result; } public static string EncodeXml(this string value) { return value.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&", "&amp;"); } public static string EncodeJson(this string value) { return string.Concat ("\"", value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "").Replace("\n", "\\n"), "\"" ); } public static string EncodeJsv(this string value) { if (JsState.QueryStringMode) value = UrlEncode(value); return string.IsNullOrEmpty(value) || !JsWriter.HasAnyEscapeChars(value) ? value : string.Concat ( JsWriter.QuoteString, value.Replace(JsWriter.QuoteString, TypeSerializer.DoubleQuoteString), JsWriter.QuoteString ); } public static string DecodeJsv(this string value) { const int startingQuotePos = 1; const int endingQuotePos = 2; return string.IsNullOrEmpty(value) || value[0] != JsWriter.QuoteChar ? value : value.Substring(startingQuotePos, value.Length - endingQuotePos) .Replace(TypeSerializer.DoubleQuoteString, JsWriter.QuoteString); } public static string UrlEncode(this string text) { if (string.IsNullOrEmpty(text)) return text; var sb = new StringBuilder(); foreach (var charCode in Encoding.UTF8.GetBytes(text)) { if ( charCode >= 65 && charCode <= 90 // A-Z || charCode >= 97 && charCode <= 122 // a-z || charCode >= 48 && charCode <= 57 // 0-9 || charCode >= 44 && charCode <= 46 // ,-. ) { sb.Append((char)charCode); } else { sb.Append('%' + charCode.ToString("x2")); } } return sb.ToString(); } public static string UrlDecode(this string text) { if (string.IsNullOrEmpty(text)) return null; var bytes = new List<byte>(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text[i]; if (c == '+') { bytes.Add(32); } else if (c == '%') { var hexNo = Convert.ToByte(text.Substring(i + 1, 2), 16); bytes.Add(hexNo); i += 2; } else { bytes.Add((byte)c); } } #if SILVERLIGHT byte[] byteArray = bytes.ToArray(); return Encoding.UTF8.GetString(byteArray, 0, byteArray.Length); #else return Encoding.UTF8.GetString(bytes.ToArray()); #endif } #if !XBOX public static string HexEscape(this string text, params char[] anyCharOf) { if (string.IsNullOrEmpty(text)) return text; if (anyCharOf == null || anyCharOf.Length == 0) return text; var encodeCharMap = new HashSet<char>(anyCharOf); var sb = new StringBuilder(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text[i]; if (encodeCharMap.Contains(c)) { sb.Append('%' + ((int)c).ToString("x")); } else { sb.Append(c); } } return sb.ToString(); } #endif public static string HexUnescape(this string text, params char[] anyCharOf) { if (string.IsNullOrEmpty(text)) return null; if (anyCharOf == null || anyCharOf.Length == 0) return text; var sb = new StringBuilder(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text.Substring(i, 1); if (c == "%") { var hexNo = Convert.ToInt32(text.Substring(i + 1, 2), 16); sb.Append((char)hexNo); i += 2; } else { sb.Append(c); } } return sb.ToString(); } public static string UrlFormat(this string url, params string[] urlComponents) { var encodedUrlComponents = new string[urlComponents.Length]; for (var i = 0; i < urlComponents.Length; i++) { var x = urlComponents[i]; encodedUrlComponents[i] = x.UrlEncode(); } return string.Format(url, encodedUrlComponents); } public static string ToRot13(this string value) { var array = value.ToCharArray(); for (var i = 0; i < array.Length; i++) { var number = (int)array[i]; if (number >= 'a' && number <= 'z') number += (number > 'm') ? -13 : 13; else if (number >= 'A' && number <= 'Z') number += (number > 'M') ? -13 : 13; array[i] = (char)number; } return new string(array); } public static string WithTrailingSlash(this string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); if (path[path.Length - 1] != '/') { return path + "/"; } return path; } public static string AppendPath(this string uri, params string[] uriComponents) { return AppendUrlPaths(uri, uriComponents); } public static string AppendUrlPaths(this string uri, params string[] uriComponents) { var sb = new StringBuilder(uri.WithTrailingSlash()); var i = 0; foreach (var uriComponent in uriComponents) { if (i++ > 0) sb.Append('/'); sb.Append(uriComponent.UrlEncode()); } return sb.ToString(); } public static string FromUtf8Bytes(this byte[] bytes) { return bytes == null ? null : Encoding.UTF8.GetString(bytes, 0, bytes.Length); } public static byte[] ToUtf8Bytes(this string value) { return Encoding.UTF8.GetBytes(value); } public static byte[] ToUtf8Bytes(this int intVal) { return FastToUtf8Bytes(intVal.ToString()); } public static byte[] ToUtf8Bytes(this long longVal) { return FastToUtf8Bytes(longVal.ToString()); } public static byte[] ToUtf8Bytes(this double doubleVal) { var doubleStr = doubleVal.ToString(CultureInfo.InvariantCulture.NumberFormat); if (doubleStr.IndexOf('E') != -1 || doubleStr.IndexOf('e') != -1) doubleStr = DoubleConverter.ToExactString(doubleVal); return FastToUtf8Bytes(doubleStr); } /// <summary> /// Skip the encoding process for 'safe strings' /// </summary> /// <param name="strVal"></param> /// <returns></returns> private static byte[] FastToUtf8Bytes(string strVal) { var bytes = new byte[strVal.Length]; for (var i = 0; i < strVal.Length; i++) bytes[i] = (byte)strVal[i]; return bytes; } public static string[] SplitOnFirst(this string strVal, char needle) { if (strVal == null) return new string[0]; var pos = strVal.IndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string[] SplitOnFirst(this string strVal, string needle) { if (strVal == null) return new string[0]; var pos = strVal.IndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string[] SplitOnLast(this string strVal, char needle) { if (strVal == null) return new string[0]; var pos = strVal.LastIndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string[] SplitOnLast(this string strVal, string needle) { if (strVal == null) return new string[0]; var pos = strVal.LastIndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string WithoutExtension(this string filePath) { if (string.IsNullOrEmpty(filePath)) return null; var extPos = filePath.LastIndexOf('.'); if (extPos == -1) return filePath; var dirPos = filePath.LastIndexOfAny(DirSeps); return extPos > dirPos ? filePath.Substring(0, extPos) : filePath; } #if NETFX_CORE private static readonly char DirSep = '\\';//Path.DirectorySeparatorChar; private static readonly char AltDirSep = '/';//Path.DirectorySeparatorChar == '/' ? '\\' : '/'; #else private static readonly char DirSep = Path.DirectorySeparatorChar; private static readonly char AltDirSep = Path.DirectorySeparatorChar == '/' ? '\\' : '/'; #endif static readonly char[] DirSeps = new[] { '\\', '/' }; public static string ParentDirectory(this string filePath) { if (string.IsNullOrEmpty(filePath)) return null; var dirSep = filePath.IndexOf(DirSep) != -1 ? DirSep : filePath.IndexOf(AltDirSep) != -1 ? AltDirSep : (char)0; return dirSep == 0 ? null : filePath.TrimEnd(dirSep).SplitOnLast(dirSep)[0]; } public static string ToJsv<T>(this T obj) { return TypeSerializer.SerializeToString(obj); } public static T FromJsv<T>(this string jsv) { return TypeSerializer.DeserializeFromString<T>(jsv); } public static string ToJson<T>(this T obj) { return JsConfig.PreferInterfaces ? JsonSerializer.SerializeToString(obj, AssemblyUtils.MainInterface<T>()) : JsonSerializer.SerializeToString(obj); } public static T FromJson<T>(this string json) { return JsonSerializer.DeserializeFromString<T>(json); } public static string ToCsv<T>(this T obj) { return CsvSerializer.SerializeToString(obj); } #if !XBOX && !SILVERLIGHT && !MONOTOUCH public static string ToXml<T>(this T obj) { return XmlSerializer.SerializeToString(obj); } #endif #if !XBOX && !SILVERLIGHT && !MONOTOUCH public static T FromXml<T>(this string json) { return XmlSerializer.DeserializeFromString<T>(json); } #endif public static string FormatWith(this string text, params object[] args) { return string.Format(text, args); } public static string Fmt(this string text, params object[] args) { return string.Format(text, args); } public static bool StartsWithIgnoreCase(this string text, string startsWith) { #if NETFX_CORE return text != null && text.StartsWith(startsWith, StringComparison.CurrentCultureIgnoreCase); #else return text != null && text.StartsWith(startsWith, StringComparison.InvariantCultureIgnoreCase); #endif } public static string ReadAllText(this string filePath) { #if XBOX && !SILVERLIGHT using( var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read ) ) { return new StreamReader( fileStream ).ReadToEnd( ) ; } #elif NETFX_CORE var task = Windows.Storage.StorageFile.GetFileFromPathAsync(filePath); task.AsTask().Wait(); var file = task.GetResults(); var streamTask = file.OpenStreamForReadAsync(); streamTask.Wait(); var fileStream = streamTask.Result; return new StreamReader( fileStream ).ReadToEnd( ) ; #elif WINDOWS_PHONE using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { using (var fileStream = isoStore.OpenFile(filePath, FileMode.Open)) { return new StreamReader(fileStream).ReadToEnd(); } } #else return File.ReadAllText(filePath); #endif } public static int IndexOfAny(this string text, params string[] needles) { return IndexOfAny(text, 0, needles); } public static int IndexOfAny(this string text, int startIndex, params string[] needles) { if (text == null) return -1; var firstPos = -1; foreach (var needle in needles) { var pos = text.IndexOf(needle); if (firstPos == -1 || pos < firstPos) firstPos = pos; } return firstPos; } public static string ExtractContents(this string fromText, string startAfter, string endAt) { return ExtractContents(fromText, startAfter, startAfter, endAt); } public static string ExtractContents(this string fromText, string uniqueMarker, string startAfter, string endAt) { if (string.IsNullOrEmpty(uniqueMarker)) throw new ArgumentNullException("uniqueMarker"); if (string.IsNullOrEmpty(startAfter)) throw new ArgumentNullException("startAfter"); if (string.IsNullOrEmpty(endAt)) throw new ArgumentNullException("endAt"); if (string.IsNullOrEmpty(fromText)) return null; var markerPos = fromText.IndexOf(uniqueMarker); if (markerPos == -1) return null; var startPos = fromText.IndexOf(startAfter, markerPos); if (startPos == -1) return null; startPos += startAfter.Length; var endPos = fromText.IndexOf(endAt, startPos); if (endPos == -1) endPos = fromText.Length; return fromText.Substring(startPos, endPos - startPos); } #if XBOX && !SILVERLIGHT static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled); #else static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>"); #endif public static string StripHtml(this string html) { return string.IsNullOrEmpty(html) ? null : StripHtmlRegEx.Replace(html, ""); } #if XBOX && !SILVERLIGHT static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]", RegexOptions.Compiled); static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)", RegexOptions.Compiled); #else static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]"); static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)"); #endif public static string StripMarkdownMarkup(this string markdown) { if (string.IsNullOrEmpty(markdown)) return null; markdown = StripBracketsRegEx.Replace(markdown, ""); markdown = StripBracesRegEx.Replace(markdown, ""); markdown = markdown .Replace("*", "") .Replace("!", "") .Replace("\r", "") .Replace("\n", "") .Replace("#", ""); return markdown; } private const int LowerCaseOffset = 'a' - 'A'; public static string ToCamelCase(this string value) { if (string.IsNullOrEmpty(value)) return value; var len = value.Length; var newValue = new char[len]; var firstPart = true; for (var i = 0; i < len; ++i) { var c0 = value[i]; var c1 = i < len - 1 ? value[i + 1] : 'A'; var c0isUpper = c0 >= 'A' && c0 <= 'Z'; var c1isUpper = c1 >= 'A' && c1 <= 'Z'; if (firstPart && c0isUpper && (c1isUpper || i == 0)) c0 = (char)(c0 + LowerCaseOffset); else firstPart = false; newValue[i] = c0; } return new string(newValue); } private static readonly TextInfo TextInfo = CultureInfo.InvariantCulture.TextInfo; public static string ToTitleCase(this string value) { #if SILVERLIGHT || __MonoCS__ string[] words = value.Split('_'); for (int i = 0; i <= words.Length - 1; i++) { if ((!object.ReferenceEquals(words[i], string.Empty))) { string firstLetter = words[i].Substring(0, 1); string rest = words[i].Substring(1); string result = firstLetter.ToUpper() + rest.ToLower(); words[i] = result; } } return String.Join("", words); #else return TextInfo.ToTitleCase(value).Replace("_", string.Empty); #endif } public static string ToLowercaseUnderscore(this string value) { if (string.IsNullOrEmpty(value)) return value; value = value.ToCamelCase(); var sb = new StringBuilder(value.Length); foreach (var t in value) { if (char.IsLower(t) || t == '_') { sb.Append(t); } else { sb.Append("_"); sb.Append(char.ToLower(t)); } } return sb.ToString(); } public static string SafeSubstring(this string value, int length) { return string.IsNullOrEmpty(value) ? string.Empty : value.Substring(Math.Min(length, value.Length)); } public static string SafeSubstring(this string value, int startIndex, int length) { if (string.IsNullOrEmpty(value)) return string.Empty; if (value.Length >= (startIndex + length)) return value.Substring(startIndex, length); return value.Length > startIndex ? value.Substring(startIndex) : string.Empty; } public static bool IsAnonymousType(this Type type) { if (type == null) throw new ArgumentNullException("type"); // HACK: The only way to detect anonymous types right now. #if NETFX_CORE return type.IsGenericType() && type.Name.Contains("AnonymousType") && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$")); #else return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false) && type.IsGenericType() && type.Name.Contains("AnonymousType") && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$")) && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic; #endif } } }
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.SiteRecovery; using Microsoft.WindowsAzure.Management.SiteRecovery.Models; namespace Microsoft.WindowsAzure.Management.SiteRecovery { public static partial class ProtectionProfileOperationsExtensions { /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='input'> /// Required. input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse CreateAndAssociate(this IProtectionProfileOperations operations, CreateAndAssociateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionProfileOperations)s).CreateAndAssociateAsync(input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='input'> /// Required. input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> CreateAndAssociateAsync(this IProtectionProfileOperations operations, CreateAndAssociateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders) { return operations.CreateAndAssociateAsync(input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='protectionProfileId'> /// Required. Protection Profile ID. /// </param> /// <param name='input'> /// Required. input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse DissociateAndDelete(this IProtectionProfileOperations operations, string protectionProfileId, CreateAndAssociateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionProfileOperations)s).DissociateAndDeleteAsync(protectionProfileId, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='protectionProfileId'> /// Required. Protection Profile ID. /// </param> /// <param name='input'> /// Required. input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> DissociateAndDeleteAsync(this IProtectionProfileOperations operations, string protectionProfileId, CreateAndAssociateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders) { return operations.DissociateAndDeleteAsync(protectionProfileId, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the protected Profile by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='protectionProfileId'> /// Required. Protection Profile ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Protection Profile object. /// </returns> public static ProtectionProfileResponse Get(this IProtectionProfileOperations operations, string protectionProfileId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionProfileOperations)s).GetAsync(protectionProfileId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the protected Profile by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='protectionProfileId'> /// Required. Protection Profile ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Protection Profile object. /// </returns> public static Task<ProtectionProfileResponse> GetAsync(this IProtectionProfileOperations operations, string protectionProfileId, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(protectionProfileId, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the list of all ProtectionContainers for the given server. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list ProtectionProfiles operation. /// </returns> public static ProtectionProfileListResponse List(this IProtectionProfileOperations operations, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionProfileOperations)s).ListAsync(customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all ProtectionContainers for the given server. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list ProtectionProfiles operation. /// </returns> public static Task<ProtectionProfileListResponse> ListAsync(this IProtectionProfileOperations operations, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(customRequestHeaders, CancellationToken.None); } /// <summary> /// Update protection profile. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='input'> /// Required. input. /// </param> /// <param name='protectionProfileId'> /// Required. Profile id. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse Update(this IProtectionProfileOperations operations, UpdateProtectionProfileInput input, string protectionProfileId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionProfileOperations)s).UpdateAsync(input, protectionProfileId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update protection profile. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionProfileOperations. /// </param> /// <param name='input'> /// Required. input. /// </param> /// <param name='protectionProfileId'> /// Required. Profile id. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> UpdateAsync(this IProtectionProfileOperations operations, UpdateProtectionProfileInput input, string protectionProfileId, CustomRequestHeaders customRequestHeaders) { return operations.UpdateAsync(input, protectionProfileId, customRequestHeaders, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace WG_BalancedPopMod { public class XML_VersionFive : WG_XMLBaseVersion { private const string popNodeName = "population"; private const string bonusHouseName = "bonusHouseHold"; private const string bonusWorkName = "bonusWorker"; private const string meshName = "meshName"; private const string consumeNodeName = "consumption"; private const string visitNodeName = "visitor"; private const string pollutionNodeName = "pollution"; private const string productionNodeName = "production"; /// <param name="doc"></param> public override void readXML(XmlDocument doc) { XmlElement root = doc.DocumentElement; try { //DataStore.enableExperimental = Convert.ToBoolean(root.Attributes["experimental"].InnerText); //DataStore.timeBasedRealism = Convert.ToBoolean(root.Attributes["enableTimeVariation"].InnerText); } catch (Exception) { DataStore.enableExperimental = false; } foreach (XmlNode node in root.ChildNodes) { try { if (node.Name.Equals(popNodeName)) { readPopulationNode(node); } else if (node.Name.Equals(consumeNodeName)) { readConsumptionNode(node); } else if (node.Name.Equals(visitNodeName)) { readVisitNode(node); } else if (node.Name.Equals(pollutionNodeName)) { readPollutionNode(node); } else if (node.Name.Equals(productionNodeName)) { readProductionNode(node); } else if (node.Name.Equals(bonusHouseName)) { readBonusHouseNode(node); } else if (node.Name.Equals(bonusWorkName)) { readBonusWorkers(node); } } catch (Exception e) { Debugging.bufferWarning(e.Message); UnityEngine.Debug.LogException(e); } } } // end readXML /// <param name="fullPathFileName"></param> /// <returns></returns> public override bool writeXML(string fullPathFileName) { // Should not be called now return false; } // end writeXML /// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void createPopulationNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("space_pp = Square metres per person"); rootNode.AppendChild(comment); comment = xmlDoc.CreateComment("level_height = Height of a floor. The height of chimneys have been taken into account"); rootNode.AppendChild(comment); comment = xmlDoc.CreateComment("calc = model or plot. To calculate the base using either the building model, or by the land size"); rootNode.AppendChild(comment); comment = xmlDoc.CreateComment("visit_mult = The number of visitors as a multiple of workers to 1 decimal place. This is used for commercial only"); // rootNode.AppendChild(comment); comment = xmlDoc.CreateComment("lvl_0 ... lvl_3 = Proportional values between the education levels (uneducated, educated, well educated, highly educated). Does not need to be percentages."); rootNode.AppendChild(comment); } /// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void createConsumptionNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Consumption values are per household, or per production unit"); rootNode.AppendChild(comment); } /// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void createVisitNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Visitor Values are multiplies of 100th of a person per cell."); rootNode.AppendChild(comment); } /// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void createPollutionNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Ground pollution is not used by residential, commercial and offices."); rootNode.AppendChild(comment); comment = xmlDoc.CreateComment("Noise pollution is not spread over the land by residential or offices."); rootNode.AppendChild(comment); } /// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void createProductionNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Production for offices is number of employees per production unit."); rootNode.AppendChild(comment); comment = xmlDoc.CreateComment("For industry, it used as hundredths of a unit per cell block."); rootNode.AppendChild(comment); } /// <param name="xmlDoc"></param> /// <param name="buildingType"></param> /// <param name="array"></param> /// <param name="rootPopNode"></param> /// <param name="consumNode"></param> /// <param name="pollutionNode"></param> private void makeNodes(XmlDocument xmlDoc, String buildingType, int[][] array, XmlNode rootPopNode, XmlNode consumNode, XmlNode visitNode, XmlNode pollutionNode, XmlNode productionNode) { for (int i = 0; i < array.GetLength(0); i++) { makeNodes(xmlDoc, buildingType, array[i], i, rootPopNode, consumNode, visitNode, pollutionNode, productionNode); } } /// <param name="xmlDoc"></param> /// <param name="buildingType"></param> /// <param name="array"></param> /// <param name="level"></param> /// <param name="rootPopNode"></param> /// <param name="consumNode"></param> /// <param name="pollutionNode"></param> private void makeNodes(XmlDocument xmlDoc, String buildingType, int[] array, int level, XmlNode rootPopNode, XmlNode consumNode, XmlNode visitNode, XmlNode pollutionNode, XmlNode productionNode) { makePopNode(rootPopNode, xmlDoc, buildingType, level, array); makeConsumeNode(consumNode, xmlDoc, buildingType, level, array[DataStore.POWER], array[DataStore.WATER], array[DataStore.SEWAGE], array[DataStore.GARBAGE], array[DataStore.INCOME]); makeVisitNode(visitNode, xmlDoc, buildingType, level, array); makePollutionNode(pollutionNode, xmlDoc, buildingType, level, array[DataStore.GROUND_POLLUTION], array[DataStore.NOISE_POLLUTION]); makeProductionNode(productionNode, xmlDoc, buildingType, level, array[DataStore.PRODUCTION]); } /// <param name="root"></param> /// <param name="xmlDoc"></param> /// <param name="buildingType"></param> /// <param name="level"></param> /// <param name="array"></param> private void makePopNode(XmlNode root, XmlDocument xmlDoc, String buildingType, int level, int[] array) { XmlNode node = xmlDoc.CreateElement(buildingType + "_" + (level + 1)); XmlAttribute attribute = xmlDoc.CreateAttribute("space_pp"); attribute.Value = Convert.ToString(transformPopulationModifier(buildingType, level, array[DataStore.PEOPLE], true)); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("level_height"); attribute.Value = Convert.ToString(array[DataStore.LEVEL_HEIGHT]); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("calc"); attribute.Value = array[DataStore.CALC_METHOD] == 0 ? "model" : "plot"; node.Attributes.Append(attribute); if (array[DataStore.WORK_LVL0] >= 0) { attribute = xmlDoc.CreateAttribute("ground_mult"); attribute.Value = Convert.ToString(array[DataStore.DENSIFICATION]); node.Attributes.Append(attribute); for (int i = 0; i < 4; i++) { attribute = xmlDoc.CreateAttribute("lvl_" + i); attribute.Value = Convert.ToString(array[DataStore.WORK_LVL0 + i]); node.Attributes.Append(attribute); } } root.AppendChild(node); } /// <param name="root"></param> /// <param name="xmlDoc"></param> /// <param name="buildingType"></param> /// <param name="level"></param> /// <param name="array"></param> private void makeVisitNode(XmlNode root, XmlDocument xmlDoc, String buildingType, int level, int[] array) { if (array[DataStore.VISIT] >= 0) { XmlNode node = xmlDoc.CreateElement(buildingType + "_" + (level + 1)); XmlAttribute attribute = xmlDoc.CreateAttribute("visit"); attribute.Value = Convert.ToString(array[DataStore.VISIT]); node.Attributes.Append(attribute); root.AppendChild(node); } } /// <param name="root"></param> /// <param name="xmlDoc"></param> /// <param name="buildingType"></param> /// <param name="level"></param> /// <param name="power"></param> /// <param name="water"></param> /// <param name="sewage"></param> /// <param name="garbage"></param> /// <param name="wealth"></param> private void makeConsumeNode(XmlNode root, XmlDocument xmlDoc, String buildingType, int level, int power, int water, int sewage, int garbage, int wealth) { XmlNode node = xmlDoc.CreateElement(buildingType + "_" + (level + 1)); XmlAttribute attribute = xmlDoc.CreateAttribute("power"); attribute.Value = Convert.ToString(power); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("water"); attribute.Value = Convert.ToString(water); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("sewage"); attribute.Value = Convert.ToString(sewage); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("garbage"); attribute.Value = Convert.ToString(garbage); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("wealth"); attribute.Value = Convert.ToString(wealth); node.Attributes.Append(attribute); root.AppendChild(node); } /// <param name="root"></param> /// <param name="root"></param> /// <param name="xmlDoc"></param> /// <param name="buildingType"></param> /// <param name="level"></param> /// <param name="ground"></param> /// <param name="noise"></param> private void makePollutionNode(XmlNode root, XmlDocument xmlDoc, String buildingType, int level, int ground, int noise) { XmlNode node = xmlDoc.CreateElement(buildingType + "_" + (level + 1)); XmlAttribute attribute = xmlDoc.CreateAttribute("ground"); attribute.Value = Convert.ToString(ground); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("noise"); attribute.Value = Convert.ToString(noise); node.Attributes.Append(attribute); root.AppendChild(node); } /// <param name="root"></param> /// <param name="xmlDoc"></param> /// <param name="buildingType"></param> /// <param name="level"></param> /// <param name="production"></param> private void makeProductionNode(XmlNode root, XmlDocument xmlDoc, string buildingType, int level, int production) { if (production >= 0) { XmlNode node = xmlDoc.CreateElement(buildingType + "_" + (level + 1)); XmlAttribute attribute = xmlDoc.CreateAttribute("production"); attribute.Value = Convert.ToString(production); node.Attributes.Append(attribute); root.AppendChild(node); } } /// <param name="pollutionNode"></param> private void readPollutionNode(XmlNode pollutionNode) { string name = ""; foreach (XmlNode node in pollutionNode.ChildNodes) { try { // Extract power, water, sewage, garbage and wealth string[] attr = node.Name.Split(new char[] { '_' }); name = attr[0]; int level = Convert.ToInt32(attr[1]) - 1; int ground = Convert.ToInt32(node.Attributes["ground"].InnerText); int noise = Convert.ToInt32(node.Attributes["noise"].InnerText); switch (name) { case "ResidentialLow": setPollutionRates(DataStore.residentialLow[level], ground, noise); break; case "ResidentialHigh": setPollutionRates(DataStore.residentialHigh[level], ground, noise); break; case "CommercialLow": setPollutionRates(DataStore.commercialLow[level], ground, noise); break; case "CommercialHigh": setPollutionRates(DataStore.commercialHigh[level], ground, noise); break; case "CommercialTourist": setPollutionRates(DataStore.commercialTourist[level], ground, noise); break; case "CommercialLeisure": setPollutionRates(DataStore.commercialLeisure[level], ground, noise); break; case "Office": setPollutionRates(DataStore.office[level], ground, noise); break; case "Industry": setPollutionRates(DataStore.industry[level], ground, noise); break; case "IndustryOre": setPollutionRates(DataStore.industry_ore[level], ground, noise); break; case "IndustryOil": setPollutionRates(DataStore.industry_oil[level], ground, noise); break; case "IndustryForest": setPollutionRates(DataStore.industry_forest[level], ground, noise); break; case "IndustryFarm": setPollutionRates(DataStore.industry_farm[level], ground, noise); break; } } catch (Exception e) { Debugging.bufferWarning("readPollutionNode: " + name + " " + e.Message); } } // end foreach } /// <param name="consumeNode"></param> private void readConsumptionNode(XmlNode consumeNode) { foreach (XmlNode node in consumeNode.ChildNodes) { try { // Extract power, water, sewage, garbage and wealth string[] attr = node.Name.Split(new char[] { '_' }); string name = attr[0]; int level = Convert.ToInt32(attr[1]) - 1; int power = Convert.ToInt32(node.Attributes["power"].InnerText); int water = Convert.ToInt32(node.Attributes["water"].InnerText); int sewage = Convert.ToInt32(node.Attributes["sewage"].InnerText); int garbage = Convert.ToInt32(node.Attributes["garbage"].InnerText); int wealth = Convert.ToInt32(node.Attributes["wealth"].InnerText); int[] array = getArray(name, level, "readConsumptionNode"); setConsumptionRates(array, power, water, sewage, garbage, wealth); } catch (Exception e) { Debugging.bufferWarning("readConsumptionNode: " + e.Message); } } } /// <param name="popNode"></param> private void readPopulationNode(XmlNode popNode) { try { DataStore.strictCapacity = Convert.ToBoolean(popNode.Attributes["strictCapacity"].InnerText); } catch (Exception) { // Do nothing } foreach (XmlNode node in popNode.ChildNodes) { // TODO - These two to be removed in Jan 2017 if (node.Name.Equals(bonusHouseName)) { readBonusHouseNode(node); } else if (node.Name.Equals(bonusWorkName)) { readBonusWorkers(node); } else { string[] attr = node.Name.Split(new char[] { '_' }); string name = attr[0]; int level = Convert.ToInt32(attr[1]) - 1; int[] array = new int[12]; try { array = getArray(name, level, "readPopulationNode"); int temp = Convert.ToInt32(node.Attributes["level_height"].InnerText); array[DataStore.LEVEL_HEIGHT] = temp > 0 ? temp : 10; temp = Convert.ToInt32(node.Attributes["space_pp"].InnerText); if (temp <= 0) { temp = 100; // Bad person trying to give negative or div0 error. } array[DataStore.PEOPLE] = transformPopulationModifier(name, level, temp, false); } catch (Exception e) { Debugging.bufferWarning("readPopulationNode, part a: " + e.Message); } try { if (Convert.ToBoolean(node.Attributes["calc"].InnerText.Equals("plot"))) { array[DataStore.CALC_METHOD] = 1; } else { array[DataStore.CALC_METHOD] = 0; } } catch { } if (!name.Contains("Residential")) { try { int dense = Convert.ToInt32(node.Attributes["ground_mult"].InnerText); array[DataStore.DENSIFICATION] = dense >= 0 ? dense : 0; // Force to be greater than 0 int level0 = Convert.ToInt32(node.Attributes["lvl_0"].InnerText); int level1 = Convert.ToInt32(node.Attributes["lvl_1"].InnerText); int level2 = Convert.ToInt32(node.Attributes["lvl_2"].InnerText); int level3 = Convert.ToInt32(node.Attributes["lvl_3"].InnerText); // Ensure all is there first array[DataStore.WORK_LVL0] = level0; array[DataStore.WORK_LVL1] = level1; array[DataStore.WORK_LVL2] = level2; array[DataStore.WORK_LVL3] = level3; } catch (Exception e) { Debugging.bufferWarning("readPopulationNode, part b: " + e.Message); } } } // end if } // end foreach } /// <param name="name"></param> /// <param name="level"></param> /// <param name="value"></param> /// <param name="toXML">Transformation into XML value</param> /// <returns></returns> private int transformPopulationModifier(string name, int level, int value, bool toXML) { int dividor = 1; switch (name) { case "ResidentialLow": case "ResidentialHigh": dividor = 5; // 5 people break; } if (toXML) { return (value / dividor); } else { return (value * dividor); } } /// <param name="node"></param> private void readBonusHouseNode(XmlNode parent) { try { DataStore.printResidentialNames = Convert.ToBoolean(parent.Attributes["printResNames"].InnerText); } catch (Exception) { // Do nothing } try { DataStore.mergeResidentialNames = Convert.ToBoolean(parent.Attributes["mergeResNames"].InnerText); } catch (Exception) { // Do nothing } foreach (XmlNode node in parent.ChildNodes) { if (node.Name.Equals(meshName)) { try { string name = node.InnerText; int bonus = 1; bonus = Convert.ToInt32(node.Attributes["bonus"].InnerText); if (name.Length > 0) { // Needs a value to be valid DataStore.bonusHouseholdCache.Add(name, bonus); } } catch (Exception e) { Debugging.bufferWarning("readBonusHouseNode: " + e.Message + ". Setting to 1"); } } } } /// <param name="node"></param> private void readBonusWorkers(XmlNode parent) { try { DataStore.printEmploymentNames = Convert.ToBoolean(parent.Attributes["printWorkNames"].InnerText); } catch (Exception) { // Do nothing } try { DataStore.mergeEmploymentNames = Convert.ToBoolean(parent.Attributes["mergeWorkNames"].InnerText); } catch (Exception) { // Do nothing } foreach (XmlNode node in parent.ChildNodes) { if (node.Name.Equals(meshName)) { try { string name = node.InnerText; int bonus = 5; bonus = Convert.ToInt32(node.Attributes["bonus"].InnerText); if (name.Length > 0) { // Needs a value to be valid DataStore.bonusWorkerCache.Add(name, bonus); } } catch (Exception e) { Debugging.bufferWarning("readBonusWorkers: " + e.Message + ". Setting to 5"); } } } } /// <param name="produceNode"></param> private void readVisitNode(XmlNode produceNode) { foreach (XmlNode node in produceNode.ChildNodes) { try { // Extract power, water, sewage, garbage and wealth string[] attr = node.Name.Split(new char[] { '_' }); string name = attr[0]; int level = Convert.ToInt32(attr[1]) - 1; int[] array = getArray(name, level, "readVisitNode"); array[DataStore.VISIT] = Convert.ToInt32(node.Attributes["visit"].InnerText); if (array[DataStore.VISIT] <= 0) { array[DataStore.VISIT] = 1; } } catch (Exception e) { Debugging.bufferWarning("readVisitNode: " + e.Message); } } } /// <param name="produceNode"></param> private void readProductionNode(XmlNode produceNode) { foreach (XmlNode node in produceNode.ChildNodes) { try { // Extract power, water, sewage, garbage and wealth string[] attr = node.Name.Split(new char[] { '_' }); string name = attr[0]; int level = Convert.ToInt32(attr[1]) - 1; int[] array = getArray(name, level, "readProductionNode"); array[DataStore.PRODUCTION] = Convert.ToInt32(node.Attributes["production"].InnerText); if (array[DataStore.PRODUCTION] <= 0) { array[DataStore.PRODUCTION] = 1; } } catch (Exception e) { Debugging.bufferWarning("readProductionNode: " + e.Message); } } } /// <param name="name"></param> /// <param name="level"></param> /// <param name="callingFunction">For debug purposes</param> /// <returns></returns> private static int[] getArray(string name, int level, string callingFunction) { int[] array = new int[14]; switch (name) { case "ResidentialLow": array = DataStore.residentialLow[level]; break; case "ResidentialHigh": array = DataStore.residentialHigh[level]; break; case "CommercialLow": array = DataStore.commercialLow[level]; break; case "CommercialHigh": array = DataStore.commercialHigh[level]; break; case "CommercialTourist": array = DataStore.commercialTourist[level]; break; case "CommercialLeisure": array = DataStore.commercialLeisure[level]; break; case "Office": array = DataStore.office[level]; break; case "Industry": array = DataStore.industry[level]; break; case "IndustryOre": array = DataStore.industry_ore[level]; break; case "IndustryOil": array = DataStore.industry_oil[level]; break; case "IndustryForest": array = DataStore.industry_forest[level]; break; case "IndustryFarm": array = DataStore.industry_farm[level]; break; default: Debugging.panelMessage(callingFunction + ". unknown element name: " + name); break; } return array; } // end getArray /// <param name="p"></param> /// <param name="power"></param> /// <param name="water"></param> /// <param name="sewage"></param> /// <param name="garbage"></param> /// <param name="wealth"></param> private void setConsumptionRates(int[] p, int power, int water, int sewage, int garbage, int wealth) { p[DataStore.POWER] = power; p[DataStore.WATER] = water; p[DataStore.SEWAGE] = sewage; p[DataStore.GARBAGE] = garbage; p[DataStore.INCOME] = wealth; } /// <param name="p"></param> /// <param name="ground"></param> /// <param name="noise"></param> private void setPollutionRates(int[] p, int ground, int noise) { p[DataStore.GROUND_POLLUTION] = ground; p[DataStore.NOISE_POLLUTION] = noise; } } }
// // Manager.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.Collections; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; namespace Hal { internal delegate void DBusDeviceAddedHandler(string udi); internal delegate void DBusDeviceRemovedHandler(string udi); internal delegate void DBusNewCapabilityHandler(string udi, string capability); [Interface("org.freedesktop.Hal.Manager")] internal interface IManager { event DBusDeviceAddedHandler DeviceAdded; event DBusDeviceRemovedHandler DeviceRemoved; event DBusNewCapabilityHandler NewCapability; string [] GetAllDevices(); bool DeviceExists(string udi); string [] FindDeviceStringMatch(string key, string value); string [] FindDeviceByCapability(string capability); } public class DeviceArgs : EventArgs { private string udi; public DeviceArgs(string udi) { this.udi = udi; } public string Udi { get { return udi; } } } public class DeviceAddedArgs : DeviceArgs { private Device device; public DeviceAddedArgs(string udi) : base(udi) { } public Device Device { get { if(device == null) { device = new Device(Udi); } return device; } } } public class DeviceRemovedArgs : DeviceArgs { public DeviceRemovedArgs(string udi) : base(udi) { } } public class NewCapabilityArgs : DeviceArgs { private string capability; public NewCapabilityArgs(string udi, string capability) : base(udi) { this.capability = capability; } public string Capability { get { return capability; } } } public delegate void DeviceAddedHandler(object o, DeviceAddedArgs args); public delegate void DeviceRemovedHandler(object o, DeviceRemovedArgs args); public delegate void NewCapabilityHandler(object o, NewCapabilityArgs args); public class Manager : IEnumerable<string> { private IManager manager; public event DeviceAddedHandler DeviceAdded; public event DeviceRemovedHandler DeviceRemoved; public event NewCapabilityHandler NewCapability; public Manager() { if(!Bus.System.NameHasOwner("org.freedesktop.Hal")) { // try to start it var reply = Bus.System.StartServiceByName ("org.freedesktop.Hal"); if (reply != StartReply.Success && reply != StartReply.AlreadyRunning) { throw new ApplicationException("Could not start org.freedesktop.Hal"); } // If still not started, we're done if(!Bus.System.NameHasOwner("org.freedesktop.Hal")) { throw new ApplicationException("Could not find org.freedesktop.Hal"); } } manager = Bus.System.GetObject<IManager>("org.freedesktop.Hal", new ObjectPath("/org/freedesktop/Hal/Manager")); if(manager == null) { throw new ApplicationException("The /org/freedesktop/Hal/Manager object could not be located on the DBUs interface org.freedesktop.Hal"); } manager.DeviceAdded += OnDeviceAdded; manager.DeviceRemoved += OnDeviceRemoved; manager.NewCapability += OnNewCapability; } protected virtual void OnDeviceAdded(string udi) { if(DeviceAdded != null) { DeviceAdded(this, new DeviceAddedArgs(udi)); } } protected virtual void OnDeviceRemoved(string udi) { if(DeviceRemoved != null) { DeviceRemoved(this, new DeviceRemovedArgs(udi)); } } protected virtual void OnNewCapability(string udi, string capability) { if(NewCapability != null) NewCapability(this, new NewCapabilityArgs(udi, capability)); } public bool DeviceExists(string udi) { return manager.DeviceExists(udi); } public string [] FindDeviceByStringMatch(string key, string value) { return manager.FindDeviceStringMatch(key, value); } public string [] FindDeviceByCapability(string capability) { return manager.FindDeviceByCapability(capability); } public Device [] FindDeviceByCapabilityAsDevice(string capability) { return Device.UdisToDevices(FindDeviceByCapability(capability)); } public Device [] FindDeviceByStringMatchAsDevice(string key, string value) { return Device.UdisToDevices(FindDeviceByStringMatch(key, value)); } public string [] GetAllDevices() { return manager.GetAllDevices(); } public IEnumerator<string> GetEnumerator() { foreach(string device in GetAllDevices()) { yield return device; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
// 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 MultiplyScalarDouble() { var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); 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__MultiplyScalarDouble { 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__MultiplyScalarDouble testClass) { var result = Sse2.MultiplyScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyScalarDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.MultiplyScalar( 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__MultiplyScalarDouble() { 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__MultiplyScalarDouble() { 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.MultiplyScalar( 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.MultiplyScalar( 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.MultiplyScalar( 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.MultiplyScalar), 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.MultiplyScalar), 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.MultiplyScalar), 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.MultiplyScalar( _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.MultiplyScalar( 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.MultiplyScalar(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.MultiplyScalar(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.MultiplyScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); var result = Sse2.MultiplyScalar(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__MultiplyScalarDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.MultiplyScalar( 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.MultiplyScalar(_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.MultiplyScalar( 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.MultiplyScalar(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.MultiplyScalar( 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(left[0] * right[0]) != BitConverter.DoubleToInt64Bits(result[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.MultiplyScalar)}<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.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Common.Data; using Common.Types; using Common.Data.MongoDB; using Common.Data.MongoDB.Test; using KT.Data.Models; using KT.Domain; using Common.Domain; namespace KT.Data.MongoDB.Test { [TestClass] public class UserIdentityServiceTests { #region Initialization [TestInitialize] public void Initialize() { TestUtils.ClearCollection(typeof(UserIdentity).Name); } #endregion [TestMethod] public async Task AuthenticateWithPassword_returns_null_when_invalid_password() { UserIdentity identity = new UserIdentity() { PasswordHash = "test", UserName = "bourbest" }; KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); await svc.AddEntityAsync(identity); UserIdentity result = await svc.AuthenticateWithPassword("bourbest", "sdfsd"); Assert.IsNull(result); } [TestMethod] public async Task AuthenticateWithPassword_returns_null_when_user_not_exists() { UserIdentity identity = new UserIdentity() { PasswordHash = "test", UserName = "bourbest" }; KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); await svc.AddEntityAsync(identity); UserIdentity result = await svc.AuthenticateWithPassword("bourbest2", "sdfsd"); Assert.IsNull(result); } [TestMethod] public async Task AuthenticateWithPassword_returns_identity_when_password_match() { UserIdentity identity = new UserIdentity() { PasswordHash = "test", UserName = "bourbest" }; KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); await svc.AddEntityAsync(identity); UserIdentity result = await svc.AuthenticateWithPassword("bourbest", "test"); Assert.IsNotNull(result); Assert.AreNotEqual(identity.Id, result.Id); } [TestMethod] public async Task AuthenticateWithPassword_is_case_insensitive_on_username() { UserIdentity identity = new UserIdentity() { PasswordHash = "test", UserName = "bourbest" }; KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); await svc.AddEntityAsync(identity); UserIdentity result = await svc.AuthenticateWithPassword("BOURBEST", "test"); Assert.IsNotNull(result); Assert.AreNotEqual(identity.Id, result.Id); } [TestMethod] public async Task AddEntity_Hashes_Password() { string password = "test"; UserIdentity identity = new UserIdentity() { PasswordHash = password }; KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); await svc.AddEntityAsync(identity); Assert.AreNotEqual(password, identity.PasswordHash); UserIdentity result = await svc.GetEntityAsync(identity.Id); Assert.AreNotEqual(password, result.PasswordHash); } [TestMethod] public async Task UpdateEntity_Updates_only_writtable_Fields() { UserIdentity identity = new UserIdentity(); KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); identity.UserName = "bourbest"; identity.FirstName = "Joe"; identity.LastName = "Bin"; identity.PasswordHash = "sfsdfsdf"; identity.Email = "good@email.com"; identity.Roles = new List<string>() { "test" }; await svc.AddEntityAsync(identity); UserIdentity update = new UserIdentity(); // cannot modify update.Id = identity.Id; update.CreatedOn = DateTime.Now.AddDays(-10); update.ModifiedOn = DateTime.Now.AddDays(-10); update.PasswordHash = "dsdfkjsldkj"; update.SecurityStamp = "sdfsdfsd"; update.UserName = "sdjfsdhfksjdhk"; update.IsArchived = true; // can modify update.LastName = "new lastname"; update.FirstName = "new firstname"; update.Email = "new email"; update.Roles = new List<string>() { "new permissions" }; // service will set modified date ctx.TaskBeginTime = DateTime.Now.RemoveTicks().AddDays(-1); await svc.UpdateEntityAsync(update); UserIdentity updated = await svc.GetEntityAsync(identity.Id); // modified Assert.AreEqual(update.FirstName, updated.FirstName); Assert.AreEqual(update.LastName, updated.LastName); Assert.AreEqual(update.Email, updated.Email); Assert.AreEqual(update.Roles.First(), updated.Roles.First()); // Assert.AreEqual(ctx.TaskBeginTime, updated.ModifiedOn); // unmodified Assert.AreEqual(identity.IsArchived, updated.IsArchived); // Assert.AreEqual(identity.CreatedOn, updated.CreatedOn); Assert.AreEqual(identity.PasswordHash, updated.PasswordHash); Assert.AreEqual(identity.UserName, updated.UserName); Assert.AreEqual(identity.SecurityStamp, updated.SecurityStamp); } [TestMethod] [ExpectedException(typeof(EntityNotFoundException))] public async Task Change_password_throws_when_user_not_found() { KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); bool ret = await svc.ChangePassword("asdas", "aaa", "asdas"); } [TestMethod] public async Task Change_password_Returns_false_when_old_password_doesnt_match() { UserIdentity identity = new UserIdentity(); KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); identity.UserName = "bourbest"; identity.PasswordHash = "sfsdfsdf"; await svc.AddEntityAsync(identity); bool ret = await svc.ChangePassword(identity.Id, "aaa", "asdas"); Assert.IsFalse(ret); } [TestMethod] public async Task Change_password_Returns_true_when_old_password_matches() { UserIdentity identity = new UserIdentity(); KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); identity.UserName = "bourbest"; identity.PasswordHash = "test"; await svc.AddEntityAsync(identity); bool ret = await svc.ChangePassword(identity.Id, "test", "new"); Assert.IsTrue(ret); } [TestMethod] public async Task Change_password_hashes_new_password() { UserIdentity identity = new UserIdentity(); KTDomainContext ctx = new KTDomainContext(); UserIdentityService svc = new UserIdentityService(ctx); identity.UserName = "bourbest"; identity.PasswordHash = "test"; await svc.AddEntityAsync(identity); bool ret = await svc.ChangePassword(identity.Id, "test", "new"); UserIdentity updated = await svc.GetEntityAsync(identity.Id); Assert.AreNotEqual("new", updated.PasswordHash); } } }
/* * Copyright (c) Citrix Systems, 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) 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. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// A new piece of functionality /// First published in XenServer 7.2. /// </summary> public partial class Feature : XenObject<Feature> { public Feature() { } public Feature(string uuid, string name_label, string name_description, bool enabled, bool experimental, string version, XenRef<Host> host) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.enabled = enabled; this.experimental = experimental; this.version = version; this.host = host; } /// <summary> /// Creates a new Feature from a Proxy_Feature. /// </summary> /// <param name="proxy"></param> public Feature(Proxy_Feature proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Feature update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; enabled = update.enabled; experimental = update.experimental; version = update.version; host = update.host; } internal void UpdateFromProxy(Proxy_Feature proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; enabled = (bool)proxy.enabled; experimental = (bool)proxy.experimental; version = proxy.version == null ? null : (string)proxy.version; host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); } public Proxy_Feature ToProxy() { Proxy_Feature result_ = new Proxy_Feature(); result_.uuid = (uuid != null) ? uuid : ""; result_.name_label = (name_label != null) ? name_label : ""; result_.name_description = (name_description != null) ? name_description : ""; result_.enabled = enabled; result_.experimental = experimental; result_.version = (version != null) ? version : ""; result_.host = (host != null) ? host : ""; return result_; } /// <summary> /// Creates a new Feature from a Hashtable. /// </summary> /// <param name="table"></param> public Feature(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); enabled = Marshalling.ParseBool(table, "enabled"); experimental = Marshalling.ParseBool(table, "experimental"); version = Marshalling.ParseString(table, "version"); host = Marshalling.ParseRef<Host>(table, "host"); } public bool DeepEquals(Feature other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._enabled, other._enabled) && Helper.AreEqual2(this._experimental, other._experimental) && Helper.AreEqual2(this._version, other._version) && Helper.AreEqual2(this._host, other._host); } public override string SaveChanges(Session session, string opaqueRef, Feature server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static Feature get_record(Session session, string _feature) { return new Feature((Proxy_Feature)session.proxy.feature_get_record(session.uuid, (_feature != null) ? _feature : "").parse()); } /// <summary> /// Get a reference to the Feature instance with the specified UUID. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Feature> get_by_uuid(Session session, string _uuid) { return XenRef<Feature>.Create(session.proxy.feature_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get all the Feature instances with the given label. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<Feature>> get_by_name_label(Session session, string _label) { return XenRef<Feature>.Create(session.proxy.feature_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse()); } /// <summary> /// Get the uuid field of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_uuid(Session session, string _feature) { return (string)session.proxy.feature_get_uuid(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the name/label field of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_name_label(Session session, string _feature) { return (string)session.proxy.feature_get_name_label(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the name/description field of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_name_description(Session session, string _feature) { return (string)session.proxy.feature_get_name_description(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the enabled field of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static bool get_enabled(Session session, string _feature) { return (bool)session.proxy.feature_get_enabled(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the experimental field of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static bool get_experimental(Session session, string _feature) { return (bool)session.proxy.feature_get_experimental(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the version field of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_version(Session session, string _feature) { return (string)session.proxy.feature_get_version(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the host field of the given Feature. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static XenRef<Host> get_host(Session session, string _feature) { return XenRef<Host>.Create(session.proxy.feature_get_host(session.uuid, (_feature != null) ? _feature : "").parse()); } /// <summary> /// Return a list of all the Features known to the system. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Feature>> get_all(Session session) { return XenRef<Feature>.Create(session.proxy.feature_get_all(session.uuid).parse()); } /// <summary> /// Get all the Feature Records at once, in a single XML RPC call /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Feature>, Feature> get_all_records(Session session) { return XenRef<Feature>.Create<Proxy_Feature>(session.proxy.feature_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// Indicates whether the feature is enabled /// </summary> public virtual bool enabled { get { return _enabled; } set { if (!Helper.AreEqual(value, _enabled)) { _enabled = value; Changed = true; NotifyPropertyChanged("enabled"); } } } private bool _enabled; /// <summary> /// Indicates whether the feature is experimental (as opposed to stable and fully supported) /// </summary> public virtual bool experimental { get { return _experimental; } set { if (!Helper.AreEqual(value, _experimental)) { _experimental = value; Changed = true; NotifyPropertyChanged("experimental"); } } } private bool _experimental; /// <summary> /// The version of this feature /// </summary> public virtual string version { get { return _version; } set { if (!Helper.AreEqual(value, _version)) { _version = value; Changed = true; NotifyPropertyChanged("version"); } } } private string _version; /// <summary> /// The host where this feature is available /// </summary> public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; Changed = true; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host; } }
// 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.Immutable; using System.Runtime.InteropServices.ComTypes; using Microsoft.DiaSymReader; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class MockSymUnmanagedReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3 { private readonly ImmutableDictionary<int, MethodDebugInfoBytes> _methodDebugInfoMap; public MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes> methodDebugInfoMap) { _methodDebugInfoMap = methodDebugInfoMap; } public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal) { Assert.Equal(1, version); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { retVal = null; return SymUnmanagedReaderExtensions.E_FAIL; } Assert.NotNull(info); retVal = info.Method; return SymUnmanagedReaderExtensions.S_OK; } public int GetSymAttribute(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { // The EE should never be calling ISymUnmanagedReader.GetSymAttribute. // In order to account for EnC updates, it should always be calling // ISymUnmanagedReader3.GetSymAttributeByVersion instead. // TODO (DevDiv #1145183): throw ExceptionUtilities.Unreachable; return GetSymAttributeByVersion(methodToken, 1, name, bufferLength, out count, customDebugInformation); } public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { Assert.Equal(1, version); Assert.Equal("MD2", name); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { count = 0; return SymUnmanagedReaderExtensions.S_FALSE; // This is a guess. We're not consuming it, so it doesn't really matter. } Assert.NotNull(info); info.Bytes.TwoPhaseCopy(bufferLength, out count, customDebugInformation); return SymUnmanagedReaderExtensions.S_OK; } public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document) { throw new NotImplementedException(); } public int GetDocuments(int bufferLength, out int count, ISymUnmanagedDocument[] documents) { throw new NotImplementedException(); } public int GetUserEntryPoint(out int methodToken) { throw new NotImplementedException(); } public int GetMethod(int methodToken, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream) { throw new NotImplementedException(); } public int UpdateSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int ReplaceSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name) { throw new NotImplementedException(); } public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent) { throw new NotImplementedException(); } public int GetMethodVersion(ISymUnmanagedMethod method, out int version) { throw new NotImplementedException(); } public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedMethod : ISymUnmanagedMethod { private readonly ISymUnmanagedScope _rootScope; public MockSymUnmanagedMethod(ISymUnmanagedScope rootScope) { _rootScope = rootScope; } int ISymUnmanagedMethod.GetRootScope(out ISymUnmanagedScope retVal) { retVal = _rootScope; return SymUnmanagedReaderExtensions.S_OK; } int ISymUnmanagedMethod.GetSequencePointCount(out int retVal) { retVal = 1; return SymUnmanagedReaderExtensions.S_OK; } int ISymUnmanagedMethod.GetSequencePoints(int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns) { pcPoints = 1; offsets[0] = 0; documents[0] = null; lines[0] = 0; columns[0] = 0; endLines[0] = 0; endColumns[0] = 0; return SymUnmanagedReaderExtensions.S_OK; } int ISymUnmanagedMethod.GetNamespace(out ISymUnmanagedNamespace retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetToken(out int pToken) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedScope : ISymUnmanagedScope, ISymUnmanagedScope2 { private readonly ImmutableArray<ISymUnmanagedScope> _children; private readonly ImmutableArray<ISymUnmanagedNamespace> _namespaces; private readonly int _startOffset; private readonly int _endOffset; public MockSymUnmanagedScope(ImmutableArray<ISymUnmanagedScope> children, ImmutableArray<ISymUnmanagedNamespace> namespaces, int startOffset = 0, int endOffset = 1) { _children = children; _namespaces = namespaces; _startOffset = startOffset; _endOffset = endOffset; } public int GetChildren(int numDesired, out int numRead, ISymUnmanagedScope[] buffer) { _children.TwoPhaseCopy(numDesired, out numRead, buffer); return SymUnmanagedReaderExtensions.S_OK; } public int GetNamespaces(int numDesired, out int numRead, ISymUnmanagedNamespace[] buffer) { _namespaces.TwoPhaseCopy(numDesired, out numRead, buffer); return SymUnmanagedReaderExtensions.S_OK; } public int GetStartOffset(out int pRetVal) { pRetVal = _startOffset; return SymUnmanagedReaderExtensions.S_OK; } public int GetEndOffset(out int pRetVal) { pRetVal = _endOffset; return SymUnmanagedReaderExtensions.S_OK; } public int GetLocalCount(out int pRetVal) { pRetVal = 0; return SymUnmanagedReaderExtensions.S_OK; } public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals) { pcLocals = 0; return SymUnmanagedReaderExtensions.S_OK; } public int GetMethod(out ISymUnmanagedMethod pRetVal) { throw new NotImplementedException(); } public int GetParent(out ISymUnmanagedScope pRetVal) { throw new NotImplementedException(); } public int GetConstantCount(out int pRetVal) { pRetVal = 0; return SymUnmanagedReaderExtensions.S_OK; } public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants) { pcConstants = 0; return SymUnmanagedReaderExtensions.S_OK; } } internal sealed class MockSymUnmanagedNamespace : ISymUnmanagedNamespace { private readonly ImmutableArray<char> _nameChars; public MockSymUnmanagedNamespace(string name) { if (name != null) { var builder = ArrayBuilder<char>.GetInstance(); builder.AddRange(name); builder.AddRange('\0'); _nameChars = builder.ToImmutableAndFree(); } } int ISymUnmanagedNamespace.GetName(int numDesired, out int numRead, char[] buffer) { _nameChars.TwoPhaseCopy(numDesired, out numRead, buffer); return 0; } int ISymUnmanagedNamespace.GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } int ISymUnmanagedNamespace.GetVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] pVars) { throw new NotImplementedException(); } } internal static class MockSymUnmanagedHelpers { public static void TwoPhaseCopy<T>(this ImmutableArray<T> source, int numDesired, out int numRead, T[] destination) { if (destination == null) { Assert.Equal(0, numDesired); numRead = source.IsDefault ? 0 : source.Length; } else { Assert.False(source.IsDefault); Assert.Equal(source.Length, numDesired); source.CopyTo(0, destination, 0, numDesired); numRead = numDesired; } } public static void Add2(this ArrayBuilder<byte> bytes, short s) { var shortBytes = BitConverter.GetBytes(s); Assert.Equal(2, shortBytes.Length); bytes.AddRange(shortBytes); } public static void Add4(this ArrayBuilder<byte> bytes, int i) { var intBytes = BitConverter.GetBytes(i); Assert.Equal(4, intBytes.Length); bytes.AddRange(intBytes); } } }
// 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. namespace System.Xml.Xsl.XsltOld { using System.Diagnostics; using System.Text; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Xml.XPath; using System.Xml.Xsl.Runtime; internal class NumberAction : ContainerAction { private const long msofnfcNil = 0x00000000; // no flags private const long msofnfcTraditional = 0x00000001; // use traditional numbering private const long msofnfcAlwaysFormat = 0x00000002; // if requested format is not supported, use Arabic (Western) style private const int cchMaxFormat = 63; // max size of formatted result private const int cchMaxFormatDecimal = 11; // max size of formatted decimal result (doesn't handle the case of a very large pwszSeparator or minlen) internal class FormatInfo { public bool isSeparator; // False for alphanumeric strings of chars public NumberingSequence numSequence; // Specifies numbering sequence public int length; // Minimum length of decimal numbers (if necessary, pad to left with zeros) public string formatString; // Format string for separator token public FormatInfo(bool isSeparator, string formatString) { this.isSeparator = isSeparator; this.formatString = formatString; } public FormatInfo() { } } private static FormatInfo s_defaultFormat = new FormatInfo(false, "0"); private static FormatInfo s_defaultSeparator = new FormatInfo(true, "."); private class NumberingFormat : NumberFormatterBase { private NumberingSequence _seq; private int _cMinLen; private string _separator; private int _sizeGroup; internal NumberingFormat() { } internal void setNumberingType(NumberingSequence seq) { _seq = seq; } //void setLangID(LID langid) {_langid = langid;} //internal void setTraditional(bool fTraditional) {_grfnfc = fTraditional ? msofnfcTraditional : 0;} internal void setMinLen(int cMinLen) { _cMinLen = cMinLen; } internal void setGroupingSeparator(string separator) { _separator = separator; } internal void setGroupingSize(int sizeGroup) { if (0 <= sizeGroup && sizeGroup <= 9) { _sizeGroup = sizeGroup; } } internal String FormatItem(object value) { double dblVal; if (value is int) { dblVal = (int)value; } else { dblVal = XmlConvert.ToXPathDouble(value); if (0.5 <= dblVal && !double.IsPositiveInfinity(dblVal)) { dblVal = XmlConvert.XPathRound(dblVal); } else { // It is an error if the number is NaN, infinite or less than 0.5; an XSLT processor may signal the error; // if it does not signal the error, it must recover by converting the number to a string as if by a call // to the string function and inserting the resulting string into the result tree. return XmlConvert.ToXPathString(value); } } Debug.Assert(dblVal >= 1); switch (_seq) { case NumberingSequence.Arabic: break; case NumberingSequence.UCLetter: case NumberingSequence.LCLetter: if (dblVal <= MaxAlphabeticValue) { StringBuilder sb = new StringBuilder(); ConvertToAlphabetic(sb, dblVal, _seq == NumberingSequence.UCLetter ? 'A' : 'a', 26); return sb.ToString(); } break; case NumberingSequence.UCRoman: case NumberingSequence.LCRoman: if (dblVal <= MaxRomanValue) { StringBuilder sb = new StringBuilder(); ConvertToRoman(sb, dblVal, _seq == NumberingSequence.UCRoman); return sb.ToString(); } break; } return ConvertToArabic(dblVal, _cMinLen, _sizeGroup, _separator); } private static string ConvertToArabic(double val, int minLength, int groupSize, string groupSeparator) { String str; if (groupSize != 0 && groupSeparator != null) { NumberFormatInfo NumberFormat = new NumberFormatInfo(); NumberFormat.NumberGroupSizes = new int[] { groupSize }; NumberFormat.NumberGroupSeparator = groupSeparator; if (Math.Floor(val) == val) { NumberFormat.NumberDecimalDigits = 0; } str = val.ToString("N", NumberFormat); } else { str = Convert.ToString(val, CultureInfo.InvariantCulture); } if (str.Length >= minLength) { return str; } else { StringBuilder sb = new StringBuilder(minLength); sb.Append('0', minLength - str.Length); sb.Append(str); return sb.ToString(); } } } // States: private const int OutputNumber = 2; private String _level; private String _countPattern; private int _countKey = Compiler.InvalidQueryKey; private String _from; private int _fromKey = Compiler.InvalidQueryKey; private String _value; private int _valueKey = Compiler.InvalidQueryKey; private Avt _formatAvt; private Avt _langAvt; private Avt _letterAvt; private Avt _groupingSepAvt; private Avt _groupingSizeAvt; // Compile time precalculated AVTs private List<FormatInfo> _formatTokens; private String _lang; private String _letter; private String _groupingSep; private String _groupingSize; private bool _forwardCompatibility; internal override bool CompileAttribute(Compiler compiler) { string name = compiler.Input.LocalName; string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Level)) { if (value != "any" && value != "multiple" && value != "single") { throw XsltException.Create(SR.Xslt_InvalidAttrValue, "level", value); } _level = value; } else if (Ref.Equal(name, compiler.Atoms.Count)) { _countPattern = value; _countKey = compiler.AddQuery(value, /*allowVars:*/true, /*allowKey:*/true, /*pattern*/true); } else if (Ref.Equal(name, compiler.Atoms.From)) { _from = value; _fromKey = compiler.AddQuery(value, /*allowVars:*/true, /*allowKey:*/true, /*pattern*/true); } else if (Ref.Equal(name, compiler.Atoms.Value)) { _value = value; _valueKey = compiler.AddQuery(value); } else if (Ref.Equal(name, compiler.Atoms.Format)) { _formatAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.Lang)) { _langAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.LetterValue)) { _letterAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.GroupingSeparator)) { _groupingSepAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.GroupingSize)) { _groupingSizeAvt = Avt.CompileAvt(compiler, value); } else { return false; } return true; } internal override void Compile(Compiler compiler) { CompileAttributes(compiler); CheckEmpty(compiler); _forwardCompatibility = compiler.ForwardCompatibility; _formatTokens = ParseFormat(PrecalculateAvt(ref _formatAvt)); _letter = ParseLetter(PrecalculateAvt(ref _letterAvt)); _lang = PrecalculateAvt(ref _langAvt); _groupingSep = PrecalculateAvt(ref _groupingSepAvt); if (_groupingSep != null && _groupingSep.Length > 1) { throw XsltException.Create(SR.Xslt_CharAttribute, "grouping-separator"); } _groupingSize = PrecalculateAvt(ref _groupingSizeAvt); } private int numberAny(Processor processor, ActionFrame frame) { int result = 0; // Our current point will be our end point in this search XPathNavigator endNode = frame.Node; if (endNode.NodeType == XPathNodeType.Attribute || endNode.NodeType == XPathNodeType.Namespace) { endNode = endNode.Clone(); endNode.MoveToParent(); } XPathNavigator startNode = endNode.Clone(); if (_fromKey != Compiler.InvalidQueryKey) { bool hitFrom = false; // First try to find start by traversing up. This gives the best candidate or we hit root do { if (processor.Matches(startNode, _fromKey)) { hitFrom = true; break; } } while (startNode.MoveToParent()); Debug.Assert( processor.Matches(startNode, _fromKey) || // we hit 'from' or startNode.NodeType == XPathNodeType.Root // we are at root ); // from this point (matched parent | root) create descendent quiery: // we have to reset 'result' on each 'from' node, because this point can' be not last from point; XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true); while (sel.MoveNext()) { if (processor.Matches(sel.Current, _fromKey)) { hitFrom = true; result = 0; } else if (MatchCountKey(processor, frame.Node, sel.Current)) { result++; } if (sel.Current.IsSamePosition(endNode)) { break; } } if (!hitFrom) { result = 0; } } else { // without 'from' we startting from the root startNode.MoveToRoot(); XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true); // and count root node by itself while (sel.MoveNext()) { if (MatchCountKey(processor, frame.Node, sel.Current)) { result++; } if (sel.Current.IsSamePosition(endNode)) { break; } } } return result; } // check 'from' condition: // if 'from' exist it has to be ancestor-or-self for the nav private bool checkFrom(Processor processor, XPathNavigator nav) { if (_fromKey == Compiler.InvalidQueryKey) { return true; } do { if (processor.Matches(nav, _fromKey)) { return true; } } while (nav.MoveToParent()); return false; } private bool moveToCount(XPathNavigator nav, Processor processor, XPathNavigator contextNode) { do { if (_fromKey != Compiler.InvalidQueryKey && processor.Matches(nav, _fromKey)) { return false; } if (MatchCountKey(processor, contextNode, nav)) { return true; } } while (nav.MoveToParent()); return false; } private int numberCount(XPathNavigator nav, Processor processor, XPathNavigator contextNode) { Debug.Assert(nav.NodeType != XPathNodeType.Attribute && nav.NodeType != XPathNodeType.Namespace); Debug.Assert(MatchCountKey(processor, contextNode, nav)); XPathNavigator runner = nav.Clone(); int number = 1; if (runner.MoveToParent()) { runner.MoveToFirstChild(); while (!runner.IsSamePosition(nav)) { if (MatchCountKey(processor, contextNode, runner)) { number++; } if (!runner.MoveToNext()) { Debug.Fail("We implementing preceding-sibling::node() and some how miss context node 'nav'"); break; } } } return number; } private static object SimplifyValue(object value) { // If result of xsl:number is not in correct range it should be returned as is. // so we need intermidiate string value. // If it's already a double we would like to keep it as double. // So this function converts to string only if if result is nodeset or RTF Debug.Assert(!(value is int)); if (value.GetType() == typeof(Object)) { XPathNodeIterator nodeset = value as XPathNodeIterator; if (nodeset != null) { if (nodeset.MoveNext()) { return nodeset.Current.Value; } return string.Empty; } XPathNavigator nav = value as XPathNavigator; if (nav != null) { return nav.Value; } } return value; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); ArrayList list = processor.NumberList; switch (frame.State) { case Initialized: Debug.Assert(frame != null); Debug.Assert(frame.NodeSet != null); list.Clear(); if (_valueKey != Compiler.InvalidQueryKey) { list.Add(SimplifyValue(processor.Evaluate(frame, _valueKey))); } else if (_level == "any") { int number = numberAny(processor, frame); if (number != 0) { list.Add(number); } } else { bool multiple = (_level == "multiple"); XPathNavigator contextNode = frame.Node; // context of xsl:number element. We using this node in MatchCountKey() XPathNavigator countNode = frame.Node.Clone(); // node we count for if (countNode.NodeType == XPathNodeType.Attribute || countNode.NodeType == XPathNodeType.Namespace) { countNode.MoveToParent(); } while (moveToCount(countNode, processor, contextNode)) { list.Insert(0, numberCount(countNode, processor, contextNode)); if (!multiple || !countNode.MoveToParent()) { break; } } if (!checkFrom(processor, countNode)) { list.Clear(); } } /*CalculatingFormat:*/ frame.StoredOutput = Format(list, _formatAvt == null ? _formatTokens : ParseFormat(_formatAvt.Evaluate(processor, frame)), _langAvt == null ? _lang : _langAvt.Evaluate(processor, frame), _letterAvt == null ? _letter : ParseLetter(_letterAvt.Evaluate(processor, frame)), _groupingSepAvt == null ? _groupingSep : _groupingSepAvt.Evaluate(processor, frame), _groupingSizeAvt == null ? _groupingSize : _groupingSizeAvt.Evaluate(processor, frame) ); goto case OutputNumber; case OutputNumber: Debug.Assert(frame.StoredOutput != null); if (!processor.TextEvent(frame.StoredOutput)) { frame.State = OutputNumber; break; } frame.Finished(); break; default: Debug.Fail("Invalid Number Action execution state"); break; } } private bool MatchCountKey(Processor processor, XPathNavigator contextNode, XPathNavigator nav) { if (_countKey != Compiler.InvalidQueryKey) { return processor.Matches(nav, _countKey); } if (contextNode.Name == nav.Name && BasicNodeType(contextNode.NodeType) == BasicNodeType(nav.NodeType)) { return true; } return false; } private XPathNodeType BasicNodeType(XPathNodeType type) { if (type == XPathNodeType.SignificantWhitespace || type == XPathNodeType.Whitespace) { return XPathNodeType.Text; } else { return type; } } // SDUB: perf. // for each call to xsl:number Format() will build new NumberingFormat object. // in case of no AVTs we can build this object at compile time and reuse it on execution time. // even partial step in this derection will be usefull (when cFormats == 0) private static string Format(ArrayList numberlist, List<FormatInfo> tokens, string lang, string letter, string groupingSep, string groupingSize) { StringBuilder result = new StringBuilder(); int cFormats = 0; if (tokens != null) { cFormats = tokens.Count; } NumberingFormat numberingFormat = new NumberingFormat(); if (groupingSize != null) { try { numberingFormat.setGroupingSize(Convert.ToInt32(groupingSize, CultureInfo.InvariantCulture)); } catch (System.FormatException) { } catch (System.OverflowException) { } } if (groupingSep != null) { if (groupingSep.Length > 1) { // It is a breaking change to throw an exception, SQLBUDT 324367 //throw XsltException.Create(SR.Xslt_CharAttribute, "grouping-separator"); } numberingFormat.setGroupingSeparator(groupingSep); } if (0 < cFormats) { FormatInfo prefix = tokens[0]; Debug.Assert(prefix == null || prefix.isSeparator); FormatInfo sufix = null; if (cFormats % 2 == 1) { sufix = tokens[cFormats - 1]; cFormats--; } FormatInfo periodicSeparator = 2 < cFormats ? tokens[cFormats - 2] : s_defaultSeparator; FormatInfo periodicFormat = 0 < cFormats ? tokens[cFormats - 1] : s_defaultFormat; if (prefix != null) { result.Append(prefix.formatString); } int numberlistCount = numberlist.Count; for (int i = 0; i < numberlistCount; i++) { int formatIndex = i * 2; bool haveFormat = formatIndex < cFormats; if (0 < i) { FormatInfo thisSeparator = haveFormat ? tokens[formatIndex + 0] : periodicSeparator; Debug.Assert(thisSeparator.isSeparator); result.Append(thisSeparator.formatString); } FormatInfo thisFormat = haveFormat ? tokens[formatIndex + 1] : periodicFormat; Debug.Assert(!thisFormat.isSeparator); //numberingFormat.setletter(this.letter); //numberingFormat.setLang(this.lang); numberingFormat.setNumberingType(thisFormat.numSequence); numberingFormat.setMinLen(thisFormat.length); result.Append(numberingFormat.FormatItem(numberlist[i])); } if (sufix != null) { result.Append(sufix.formatString); } } else { numberingFormat.setNumberingType(NumberingSequence.Arabic); for (int i = 0; i < numberlist.Count; i++) { if (i != 0) { result.Append("."); } result.Append(numberingFormat.FormatItem(numberlist[i])); } } return result.ToString(); } /* ---------------------------------------------------------------------------- mapFormatToken() Maps a token of alphanumeric characters to a numbering format ID and a minimum length bound. Tokens specify the character(s) that begins a Unicode numbering sequence. For example, "i" specifies lower case roman numeral numbering. Leading "zeros" specify a minimum length to be maintained by padding, if necessary. ---------------------------------------------------------------------------- */ private static void mapFormatToken(String wsToken, int startLen, int tokLen, out NumberingSequence seq, out int pminlen) { char wch = wsToken[startLen]; bool UseArabic = false; pminlen = 1; seq = NumberingSequence.Nil; switch ((int)wch) { case 0x0030: // Digit zero case 0x0966: // Hindi digit zero case 0x0e50: // Thai digit zero case 0xc77b: // Korean digit zero case 0xff10: // Digit zero (double-byte) do { // Leading zeros request padding. Track how much. pminlen++; } while ((--tokLen > 0) && (wch == wsToken[++startLen])); if (wsToken[startLen] != (char)(wch + 1)) { // If next character isn't "one", then use Arabic UseArabic = true; } break; } if (!UseArabic) { // Map characters of token to number format ID switch ((int)wsToken[startLen]) { case 0x0031: seq = NumberingSequence.Arabic; break; case 0x0041: seq = NumberingSequence.UCLetter; break; case 0x0049: seq = NumberingSequence.UCRoman; break; case 0x0061: seq = NumberingSequence.LCLetter; break; case 0x0069: seq = NumberingSequence.LCRoman; break; case 0x0410: seq = NumberingSequence.UCRus; break; case 0x0430: seq = NumberingSequence.LCRus; break; case 0x05d0: seq = NumberingSequence.Hebrew; break; case 0x0623: seq = NumberingSequence.ArabicScript; break; case 0x0905: seq = NumberingSequence.Hindi2; break; case 0x0915: seq = NumberingSequence.Hindi1; break; case 0x0967: seq = NumberingSequence.Hindi3; break; case 0x0e01: seq = NumberingSequence.Thai1; break; case 0x0e51: seq = NumberingSequence.Thai2; break; case 0x30a2: seq = NumberingSequence.DAiueo; break; case 0x30a4: seq = NumberingSequence.DIroha; break; case 0x3131: seq = NumberingSequence.DChosung; break; case 0x4e00: seq = NumberingSequence.FEDecimal; break; case 0x58f1: seq = NumberingSequence.DbNum3; break; case 0x58f9: seq = NumberingSequence.ChnCmplx; break; case 0x5b50: seq = NumberingSequence.Zodiac2; break; case 0xac00: seq = NumberingSequence.Ganada; break; case 0xc77c: seq = NumberingSequence.KorDbNum1; break; case 0xd558: seq = NumberingSequence.KorDbNum3; break; case 0xff11: seq = NumberingSequence.DArabic; break; case 0xff71: seq = NumberingSequence.Aiueo; break; case 0xff72: seq = NumberingSequence.Iroha; break; case 0x7532: if (tokLen > 1 && wsToken[startLen + 1] == 0x5b50) { // 60-based Zodiak numbering begins with two characters seq = NumberingSequence.Zodiac3; tokLen--; startLen++; } else { // 10-based Zodiak numbering begins with one character seq = NumberingSequence.Zodiac1; } break; default: seq = NumberingSequence.Arabic; break; } } //if (tokLen != 1 || UseArabic) { if (UseArabic) { // If remaining token length is not 1, then don't recognize // sequence and default to Arabic with no zero padding. seq = NumberingSequence.Arabic; pminlen = 0; } } /* ---------------------------------------------------------------------------- parseFormat() Parse format string into format tokens (alphanumeric) and separators (non-alphanumeric). */ private static List<FormatInfo> ParseFormat(string formatString) { if (formatString == null || formatString.Length == 0) { return null; } int length = 0; bool lastAlphaNumeric = CharUtil.IsAlphaNumeric(formatString[length]); List<FormatInfo> tokens = new List<FormatInfo>(); int count = 0; if (lastAlphaNumeric) { // If the first one is alpha num add empty separator as a prefix. tokens.Add(null); } while (length <= formatString.Length) { // Loop until a switch from format token to separator is detected (or vice-versa) bool currentchar = length < formatString.Length ? CharUtil.IsAlphaNumeric(formatString[length]) : !lastAlphaNumeric; if (lastAlphaNumeric != currentchar) { FormatInfo formatInfo = new FormatInfo(); if (lastAlphaNumeric) { // We just finished a format token. Map it to a numbering format ID and a min-length bound. mapFormatToken(formatString, count, length - count, out formatInfo.numSequence, out formatInfo.length); } else { formatInfo.isSeparator = true; // We just finished a separator. Save its length and a pointer to it. formatInfo.formatString = formatString.Substring(count, length - count); } count = length; length++; // Begin parsing the next format token or separator tokens.Add(formatInfo); // Flip flag from format token to separator (or vice-versa) lastAlphaNumeric = currentchar; } else { length++; } } return tokens; } private string ParseLetter(string letter) { if (letter == null || letter == "traditional" || letter == "alphabetic") { return letter; } if (!_forwardCompatibility) { throw XsltException.Create(SR.Xslt_InvalidAttrValue, "letter-value", letter); } return null; } } }
// 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. // Code adapted from https://blogs.msdn.microsoft.com/haibo_luo/2010/04/19/ilvisualizer-2010-solution using System.Collections.Generic; using System.IO; using System.Reflection; namespace System.Linq.Expressions.Tests { public interface IILStringCollector { void Process(ILInstruction ilInstruction, string operandString); } public class ReadableILStringToTextWriter : IILStringCollector { protected readonly TextWriter _writer; public ReadableILStringToTextWriter(TextWriter writer) { _writer = writer; } public virtual void Process(ILInstruction ilInstruction, string operandString) { _writer.WriteLine("IL_{0:x4}: {1,-10} {2}", ilInstruction.Offset, ilInstruction.OpCode.Name, operandString); } } public class RawILStringToTextWriter : ReadableILStringToTextWriter { public RawILStringToTextWriter(TextWriter writer) : base(writer) { } public override void Process(ILInstruction ilInstruction, string operandString) { _writer.WriteLine("IL_{0:x4}: {1,-4}| {2, -8}", ilInstruction.Offset, ilInstruction.OpCode.Value.ToString("x2"), operandString); } } public class RichILStringToTextWriter : ReadableILStringToTextWriter { private readonly Dictionary<int, int> _startCounts = new Dictionary<int, int>(); private readonly Dictionary<int, Type> _startCatch = new Dictionary<int, Type>(); private readonly Dictionary<int, int> _endCounts = new Dictionary<int, int>(); private readonly HashSet<int> _startFinally = new HashSet<int>(); private readonly HashSet<int> _startFault = new HashSet<int>(); private readonly HashSet<int> _startFilter = new HashSet<int>(); private string _indent = ""; public RichILStringToTextWriter(TextWriter writer, ExceptionInfo[] exceptions) : base(writer) { foreach (var e in exceptions) { int startCount = 0; if (!_startCounts.TryGetValue(e.StartAddress, out startCount)) { _startCounts.Add(e.StartAddress, startCount); } _startCounts[e.StartAddress] += e.Handlers.Length; foreach (var c in e.Handlers) { if (c.Kind == HandlerKind.Finally) { _startFinally.Add(c.StartAddress); } else if (c.Kind == HandlerKind.Fault) { _startFault.Add(c.StartAddress); } else if (c.Kind == HandlerKind.Filter) { _startFilter.Add(c.StartAddress); } else { _startCatch.Add(c.StartAddress, c.Type); } int endCount = 0; if (!_endCounts.TryGetValue(c.EndAddress, out endCount)) { _endCounts.Add(c.EndAddress, endCount); } _endCounts[c.EndAddress]++; } } } public override void Process(ILInstruction instruction, string operandString) { int endCount = 0; if (_endCounts.TryGetValue(instruction.Offset, out endCount)) { for (var i = 0; i < endCount; i++) { Dedent(); _writer.WriteLine(_indent + "}"); } } int startCount = 0; if (_startCounts.TryGetValue(instruction.Offset, out startCount)) { for (var i = 0; i < startCount; i++) { _writer.WriteLine(_indent + ".try"); _writer.WriteLine(_indent + "{"); Indent(); } } var t = default(Type); if (_startCatch.TryGetValue(instruction.Offset, out t)) { Dedent(); _writer.WriteLine(_indent + "}"); _writer.WriteLine(_indent + $"catch ({t.ToIL()})"); _writer.WriteLine(_indent + "{"); Indent(); } if (_startFilter.Contains(instruction.Offset)) { Dedent(); _writer.WriteLine(_indent + "}"); _writer.WriteLine(_indent + "filter"); _writer.WriteLine(_indent + "{"); Indent(); } if (_startFinally.Contains(instruction.Offset)) { Dedent(); _writer.WriteLine(_indent + "}"); _writer.WriteLine(_indent + "finally"); _writer.WriteLine(_indent + "{"); Indent(); } if (_startFault.Contains(instruction.Offset)) { Dedent(); _writer.WriteLine(_indent + "}"); _writer.WriteLine(_indent + "fault"); _writer.WriteLine(_indent + "{"); Indent(); } _writer.WriteLine(string.Format("{3}IL_{0:x4}: {1,-10} {2}", instruction.Offset, instruction.OpCode.Name, operandString, _indent)); } public void Indent() { _indent = new string(' ', _indent.Length + 2); } public void Dedent() { _indent = new string(' ', _indent.Length - 2); } } public abstract class ILInstructionVisitor { public virtual void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction) { } public virtual void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction) { } public virtual void VisitInlineIInstruction(InlineIInstruction inlineIInstruction) { } public virtual void VisitInlineI8Instruction(InlineI8Instruction inlineI8Instruction) { } public virtual void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction) { } public virtual void VisitInlineNoneInstruction(InlineNoneInstruction inlineNoneInstruction) { } public virtual void VisitInlineRInstruction(InlineRInstruction inlineRInstruction) { } public virtual void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction) { } public virtual void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction) { } public virtual void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction) { } public virtual void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction) { } public virtual void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction) { } public virtual void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction) { } public virtual void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction) { } public virtual void VisitShortInlineIInstruction(ShortInlineIInstruction shortInlineIInstruction) { } public virtual void VisitShortInlineRInstruction(ShortInlineRInstruction shortInlineRInstruction) { } public virtual void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction) { } } public class ReadableILStringVisitor : ILInstructionVisitor { protected readonly IFormatProvider formatProvider; protected readonly IILStringCollector collector; public ReadableILStringVisitor(IILStringCollector collector) : this(collector, DefaultFormatProvider.Instance) { } public ReadableILStringVisitor(IILStringCollector collector, IFormatProvider formatProvider) { this.formatProvider = formatProvider; this.collector = collector; } public override void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction) { collector.Process(inlineBrTargetInstruction, formatProvider.Label(inlineBrTargetInstruction.TargetOffset)); } public override void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction) { string field; try { field = inlineFieldInstruction.Field.ToIL(); } catch (Exception ex) { field = "!" + ex.Message + "!"; } collector.Process(inlineFieldInstruction, field); } public override void VisitInlineIInstruction(InlineIInstruction inlineIInstruction) { collector.Process(inlineIInstruction, inlineIInstruction.Value.ToString()); } public override void VisitInlineI8Instruction(InlineI8Instruction inlineI8Instruction) { collector.Process(inlineI8Instruction, inlineI8Instruction.Value.ToString()); } public override void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction) { string method; try { method = inlineMethodInstruction.Method.ToIL(); } catch (Exception ex) { method = "!" + ex.Message + "!"; } collector.Process(inlineMethodInstruction, method); } public override void VisitInlineNoneInstruction(InlineNoneInstruction inlineNoneInstruction) { collector.Process(inlineNoneInstruction, string.Empty); } public override void VisitInlineRInstruction(InlineRInstruction inlineRInstruction) { collector.Process(inlineRInstruction, inlineRInstruction.Value.ToString()); } public override void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction) { collector.Process(inlineSigInstruction, formatProvider.SigByteArrayToString(inlineSigInstruction.Signature)); } public override void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction) { collector.Process(inlineStringInstruction, formatProvider.EscapedString(inlineStringInstruction.String)); } public override void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction) { collector.Process(inlineSwitchInstruction, formatProvider.MultipleLabels(inlineSwitchInstruction.TargetOffsets)); } public override void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction) { string member; try { string prefix = ""; string token = ""; switch (inlineTokInstruction.Member.MemberType) { case MemberTypes.Method: case MemberTypes.Constructor: prefix = "method "; token = ((MethodBase)inlineTokInstruction.Member).ToIL(); break; case MemberTypes.Field: prefix = "field "; token = ((FieldInfo)inlineTokInstruction.Member).ToIL(); break; default: token = ((TypeInfo)inlineTokInstruction.Member).ToIL(); break; } member = prefix + token; } catch (Exception ex) { member = "!" + ex.Message + "!"; } collector.Process(inlineTokInstruction, member); } public override void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction) { string type; try { type = inlineTypeInstruction.Type.ToIL(); } catch (Exception ex) { type = "!" + ex.Message + "!"; } collector.Process(inlineTypeInstruction, type); } public override void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction) { collector.Process(inlineVarInstruction, formatProvider.Argument(inlineVarInstruction.Ordinal)); } public override void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction) { collector.Process(shortInlineBrTargetInstruction, formatProvider.Label(shortInlineBrTargetInstruction.TargetOffset)); } public override void VisitShortInlineIInstruction(ShortInlineIInstruction shortInlineIInstruction) { collector.Process(shortInlineIInstruction, shortInlineIInstruction.Value.ToString()); } public override void VisitShortInlineRInstruction(ShortInlineRInstruction shortInlineRInstruction) { collector.Process(shortInlineRInstruction, shortInlineRInstruction.Value.ToString()); } public override void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction) { collector.Process(shortInlineVarInstruction, formatProvider.Argument(shortInlineVarInstruction.Ordinal)); } } public sealed class RawILStringVisitor : ReadableILStringVisitor { public RawILStringVisitor(IILStringCollector collector) : this(collector, DefaultFormatProvider.Instance) { } public RawILStringVisitor(IILStringCollector collector, IFormatProvider formatProvider) : base(collector, formatProvider) { } public override void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction) { collector.Process(inlineBrTargetInstruction, formatProvider.Int32ToHex(inlineBrTargetInstruction.Delta)); } public override void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction) { collector.Process(inlineFieldInstruction, formatProvider.Int32ToHex(inlineFieldInstruction.Token)); } public override void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction) { collector.Process(inlineMethodInstruction, formatProvider.Int32ToHex(inlineMethodInstruction.Token)); } public override void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction) { collector.Process(inlineSigInstruction, formatProvider.Int32ToHex(inlineSigInstruction.Token)); } public override void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction) { collector.Process(inlineStringInstruction, formatProvider.Int32ToHex(inlineStringInstruction.Token)); } public override void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction) { collector.Process(inlineSwitchInstruction, "..."); } public override void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction) { collector.Process(inlineTokInstruction, formatProvider.Int32ToHex(inlineTokInstruction.Token)); } public override void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction) { collector.Process(inlineTypeInstruction, formatProvider.Int32ToHex(inlineTypeInstruction.Token)); } public override void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction) { collector.Process(inlineVarInstruction, formatProvider.Int16ToHex(inlineVarInstruction.Ordinal)); } public override void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction) { collector.Process(shortInlineBrTargetInstruction, formatProvider.Int8ToHex(shortInlineBrTargetInstruction.Delta)); } public override void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction) { collector.Process(shortInlineVarInstruction, formatProvider.Int8ToHex(shortInlineVarInstruction.Ordinal)); } } internal static class ILHelpers { public static string ToIL(this Type type) => ToIL(type?.GetTypeInfo()); public static string ToIL(this TypeInfo type) { if (type == null) { return ""; } if (type.IsArray) { if (type.GetElementType().MakeArrayType().GetTypeInfo() == type) { return ToIL(type.GetElementType()) + "[]"; } else { string bounds = string.Join(",", Enumerable.Repeat("...", type.GetArrayRank())); return ToIL(type.GetElementType()) + "[" + bounds + "]"; } } else if (type.IsGenericType && !type.IsGenericTypeDefinition && !type.IsGenericParameter /* TODO */) { string args = string.Join(",", type.GetGenericArguments().Select(ToIL)); string def = ToIL(type.GetGenericTypeDefinition()); return def + "<" + args + ">"; } else if (type.IsByRef) { return ToIL(type.GetElementType()) + "&"; } else if (type.IsPointer) { return ToIL(type.GetElementType()) + "*"; } else { var res = default(string); if (!s_primitives.TryGetValue(type, out res)) { res = "[" + type.Assembly.GetName().Name + "]" + type.FullName; if (type.IsValueType) { res = "valuetype " + res; } else { res = "class " + res; } } return res; } } public static string ToIL(this MethodBase method) { if (method == null) { return ""; } string res = ""; if (!method.IsStatic) { res = "instance "; } var mtd = method as MethodInfo; Type ret = mtd?.ReturnType ?? typeof(void); res += ret.ToIL() + " "; res += method.DeclaringType.ToIL(); res += "::"; res += method.Name; if (method.IsGenericMethod) { res += "<" + string.Join(",", method.GetGenericArguments().Select(ToIL)) + ">"; } res += "(" + string.Join(",", method.GetParameters().Select(p => ToIL(p.ParameterType))) + ")"; return res; } public static string ToIL(this FieldInfo field) { return field.DeclaringType.ToIL() + "::" + field.Name; } private static readonly Dictionary<TypeInfo, string> s_primitives = new Dictionary<Type, string> { { typeof(object), "object" }, { typeof(void), "void" }, { typeof(IntPtr), "native int" }, { typeof(UIntPtr), "native uint" }, { typeof(char), "char" }, { typeof(string), "string" }, { typeof(bool), "bool" }, { typeof(float), "float32" }, { typeof(double), "float64" }, { typeof(sbyte), "int8" }, { typeof(short), "int16" }, { typeof(int), "int32" }, { typeof(long), "int64" }, { typeof(byte), "uint8" }, { typeof(ushort), "uint16" }, { typeof(uint), "uint32" }, { typeof(ulong), "uint64" }, //{ typeof(TypedReference), "typedref" }, }.ToDictionary(kv => kv.Key.GetTypeInfo(), kv => kv.Value); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: test.proto #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace grpc.testing { public static class TestService { static readonly string __ServiceName = "grpc.testing.TestService"; static readonly Marshaller<global::grpc.testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.Empty.ParseFrom); static readonly Marshaller<global::grpc.testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.SimpleRequest.ParseFrom); static readonly Marshaller<global::grpc.testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.SimpleResponse.ParseFrom); static readonly Marshaller<global::grpc.testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingOutputCallRequest.ParseFrom); static readonly Marshaller<global::grpc.testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingOutputCallResponse.ParseFrom); static readonly Marshaller<global::grpc.testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingInputCallRequest.ParseFrom); static readonly Marshaller<global::grpc.testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingInputCallResponse.ParseFrom); static readonly Method<global::grpc.testing.Empty, global::grpc.testing.Empty> __Method_EmptyCall = new Method<global::grpc.testing.Empty, global::grpc.testing.Empty>( MethodType.Unary, __ServiceName, "EmptyCall", __Marshaller_Empty, __Marshaller_Empty); static readonly Method<global::grpc.testing.SimpleRequest, global::grpc.testing.SimpleResponse> __Method_UnaryCall = new Method<global::grpc.testing.SimpleRequest, global::grpc.testing.SimpleResponse>( MethodType.Unary, __ServiceName, "UnaryCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); static readonly Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse>( MethodType.ServerStreaming, __ServiceName, "StreamingOutputCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); static readonly Method<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> __Method_StreamingInputCall = new Method<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse>( MethodType.ClientStreaming, __ServiceName, "StreamingInputCall", __Marshaller_StreamingInputCallRequest, __Marshaller_StreamingInputCallResponse); static readonly Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse>( MethodType.DuplexStreaming, __ServiceName, "FullDuplexCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); static readonly Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse>( MethodType.DuplexStreaming, __ServiceName, "HalfDuplexCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); // client interface public interface ITestServiceClient { global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, CallOptions options); AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, CallOptions options); global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, CallOptions options); AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, CallOptions options); AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, CallOptions options); AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options); AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options); AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options); } // server-side interface public interface ITestService { Task<global::grpc.testing.Empty> EmptyCall(global::grpc.testing.Empty request, ServerCallContext context); Task<global::grpc.testing.SimpleResponse> UnaryCall(global::grpc.testing.SimpleRequest request, ServerCallContext context); Task StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, IServerStreamWriter<global::grpc.testing.StreamingOutputCallResponse> responseStream, ServerCallContext context); Task<global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<global::grpc.testing.StreamingInputCallRequest> requestStream, ServerCallContext context); Task FullDuplexCall(IAsyncStreamReader<global::grpc.testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::grpc.testing.StreamingOutputCallResponse> responseStream, ServerCallContext context); Task HalfDuplexCall(IAsyncStreamReader<global::grpc.testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::grpc.testing.StreamingOutputCallResponse> responseStream, ServerCallContext context); } // client stub public class TestServiceClient : ClientBase, ITestServiceClient { public TestServiceClient(Channel channel) : base(channel) { } public global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_EmptyCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, CallOptions options) { var call = CreateCall(__Method_EmptyCall, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_EmptyCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, CallOptions options) { var call = CreateCall(__Method_EmptyCall, options); return Calls.AsyncUnaryCall(call, request); } public global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_UnaryCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, CallOptions options) { var call = CreateCall(__Method_UnaryCall, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_UnaryCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, CallOptions options) { var call = CreateCall(__Method_UnaryCall, options); return Calls.AsyncUnaryCall(call, request); } public AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_StreamingOutputCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncServerStreamingCall(call, request); } public AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, CallOptions options) { var call = CreateCall(__Method_StreamingOutputCall, options); return Calls.AsyncServerStreamingCall(call, request); } public AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_StreamingInputCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncClientStreamingCall(call); } public AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options) { var call = CreateCall(__Method_StreamingInputCall, options); return Calls.AsyncClientStreamingCall(call); } public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_FullDuplexCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); } public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options) { var call = CreateCall(__Method_FullDuplexCall, options); return Calls.AsyncDuplexStreamingCall(call); } public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_HalfDuplexCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); } public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options) { var call = CreateCall(__Method_HalfDuplexCall, options); return Calls.AsyncDuplexStreamingCall(call); } } // creates service definition that can be registered with a server public static ServerServiceDefinition BindService(ITestService serviceImpl) { return ServerServiceDefinition.CreateBuilder(__ServiceName) .AddMethod(__Method_EmptyCall, serviceImpl.EmptyCall) .AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall) .AddMethod(__Method_StreamingOutputCall, serviceImpl.StreamingOutputCall) .AddMethod(__Method_StreamingInputCall, serviceImpl.StreamingInputCall) .AddMethod(__Method_FullDuplexCall, serviceImpl.FullDuplexCall) .AddMethod(__Method_HalfDuplexCall, serviceImpl.HalfDuplexCall).Build(); } // creates a new client public static TestServiceClient NewClient(Channel channel) { return new TestServiceClient(channel); } } } #endregion
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Experimental.Physics; using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Physics; using Microsoft.MixedReality.Toolkit.Utilities; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Serialization; namespace Microsoft.MixedReality.Toolkit.UI { /// <summary> /// This script allows for an object to be movable, scalable, and rotatable with one or two hands. /// You may also configure the script on only enable certain manipulations. The script works with /// both HoloLens' gesture input and immersive headset's motion controller input. /// </summary> [HelpURL("https://docs.microsoft.com/windows/mixed-reality/mrtk-unity/features/ux-building-blocks/object-manipulator")] [RequireComponent(typeof(ConstraintManager))] public class ObjectManipulator : MonoBehaviour, IMixedRealityPointerHandler, IMixedRealityFocusChangedHandler, IMixedRealitySourcePoseHandler { #region Public Enums /// <summary> /// Describes what pivot the manipulated object will rotate about when /// you rotate your hand. This is not a description of any limits or /// additional rotation logic. If no other factors (such as constraints) /// are involved, rotating your hand by an amount should rotate the object /// by the same amount. /// For example a possible future value here is RotateAboutUserDefinedPoint /// where the user could specify a pivot that the object is to rotate /// around. /// An example of a value that should not be found here is MaintainRotationToUser /// as this restricts rotation of the object when we rotate the hand. /// </summary> public enum RotateInOneHandType { RotateAboutObjectCenter, RotateAboutGrabPoint }; [System.Flags] public enum ReleaseBehaviorType { KeepVelocity = 1 << 0, KeepAngularVelocity = 1 << 1 } #endregion Public Enums #region Serialized Fields [SerializeField] [Tooltip("Transform that will be dragged. Defaults to the object of the component.")] private Transform hostTransform = null; /// <summary> /// Transform that will be dragged. Defaults to the object of the component. /// </summary> public Transform HostTransform { get { if (hostTransform == null) { hostTransform = gameObject.transform; } return hostTransform; } set => hostTransform = value; } [SerializeField] [EnumFlags] [Tooltip("Can manipulation be done only with one hand, only with two hands, or with both?")] private ManipulationHandFlags manipulationType = ManipulationHandFlags.OneHanded | ManipulationHandFlags.TwoHanded; /// <summary> /// Can manipulation be done only with one hand, only with two hands, or with both? /// </summary> public ManipulationHandFlags ManipulationType { get => manipulationType; set => manipulationType = value; } [SerializeField] [EnumFlags] [Tooltip("What manipulation will two hands perform?")] private TransformFlags twoHandedManipulationType = TransformFlags.Move | TransformFlags.Rotate | TransformFlags.Scale; /// <summary> /// What manipulation will two hands perform? /// </summary> public TransformFlags TwoHandedManipulationType { get => twoHandedManipulationType; set => twoHandedManipulationType = value; } [SerializeField] [Tooltip("Specifies whether manipulation can be done using far interaction with pointers.")] private bool allowFarManipulation = true; /// <summary> /// Specifies whether manipulation can be done using far interaction with pointers. /// </summary> public bool AllowFarManipulation { get => allowFarManipulation; set => allowFarManipulation = value; } [SerializeField] [Tooltip( "Whether physics forces are used to move the object when performing near manipulations. " + "Off will make the object feel more directly connected to the hand. On will honor the mass and inertia of the object. " + "The default is off.")] private bool useForcesForNearManipulation = false; /// <summary> /// Whether physics forces are used to move the object when performing near manipulations. /// </summary> /// <remarks> /// <para>Setting this to <c>false</c> will make the object feel more directly connected to the /// users hand. Setting this to <c>true</c> will honor the mass and inertia of the object, /// but may feel as though the object is connected through a spring. The default is <c>false</c>.</para> /// </remarks> public bool UseForcesForNearManipulation { get => useForcesForNearManipulation; set => useForcesForNearManipulation = value; } [SerializeField] [Tooltip("Rotation behavior of object when using one hand near")] private RotateInOneHandType oneHandRotationModeNear = RotateInOneHandType.RotateAboutGrabPoint; /// <summary> /// Rotation behavior of object when using one hand near /// </summary> public RotateInOneHandType OneHandRotationModeNear { get => oneHandRotationModeNear; set => oneHandRotationModeNear = value; } [SerializeField] [Tooltip("Rotation behavior of object when using one hand at distance")] private RotateInOneHandType oneHandRotationModeFar = RotateInOneHandType.RotateAboutGrabPoint; /// <summary> /// Rotation behavior of object when using one hand at distance /// </summary> public RotateInOneHandType OneHandRotationModeFar { get => oneHandRotationModeFar; set => oneHandRotationModeFar = value; } [SerializeField] [EnumFlags] [Tooltip("Rigid body behavior of the dragged object when releasing it.")] private ReleaseBehaviorType releaseBehavior = ReleaseBehaviorType.KeepVelocity | ReleaseBehaviorType.KeepAngularVelocity; /// <summary> /// Rigid body behavior of the dragged object when releasing it. /// </summary> public ReleaseBehaviorType ReleaseBehavior { get => releaseBehavior; set => releaseBehavior = value; } /// <summary> /// Obsolete: Whether to enable frame-rate independent smoothing. /// </summary> [Obsolete("SmoothingActive is obsolete and will be removed in a future version. Applications should use SmoothingFar, SmoothingNear or a combination of the two.")] public bool SmoothingActive { get => smoothingFar; set => smoothingFar = value; } [SerializeField] [Tooltip("The concrete type of TransformSmoothingLogic to use for smoothing between transforms.")] [Implements(typeof(ITransformSmoothingLogic), TypeGrouping.ByNamespaceFlat)] private SystemType transformSmoothingLogicType = typeof(DefaultTransformSmoothingLogic); [FormerlySerializedAs("smoothingActive")] [SerializeField] [Tooltip("Frame-rate independent smoothing for far interactions. Far smoothing is enabled by default.")] private bool smoothingFar = true; /// <summary> /// Whether to enable frame-rate independent smoothing for far interactions. /// </summary> /// <remarks> /// Far smoothing is enabled by default. /// </remarks> public bool SmoothingFar { get => smoothingFar; set => smoothingFar = value; } [SerializeField] [Tooltip("Frame-rate independent smoothing for near interactions. Note that enabling near smoothing may be perceived as being 'disconnected' from the hand.")] private bool smoothingNear = true; /// <summary> /// Whether to enable frame-rate independent smoothing for near interactions. /// </summary> /// <remarks> /// Note that enabling near smoothing may be perceived as being 'disconnected' from the hand. /// </remarks> public bool SmoothingNear { get => smoothingNear; set => smoothingNear = value; } [SerializeField] [Range(0, 1)] [Tooltip("Enter amount representing amount of smoothing to apply to the movement. Smoothing of 0 means no smoothing. Max value means no change to value.")] private float moveLerpTime = 0.001f; /// <summary> /// Enter amount representing amount of smoothing to apply to the movement. Smoothing of 0 means no smoothing. Max value means no change to value. /// </summary> public float MoveLerpTime { get => moveLerpTime; set => moveLerpTime = value; } [SerializeField] [Range(0, 1)] [Tooltip("Enter amount representing amount of smoothing to apply to the rotation. Smoothing of 0 means no smoothing. Max value means no change to value.")] private float rotateLerpTime = 0.001f; /// <summary> /// Enter amount representing amount of smoothing to apply to the rotation. Smoothing of 0 means no smoothing. Max value means no change to value. /// </summary> public float RotateLerpTime { get => rotateLerpTime; set => rotateLerpTime = value; } [SerializeField] [Range(0, 1)] [Tooltip("Enter amount representing amount of smoothing to apply to the scale. Smoothing of 0 means no smoothing. Max value means no change to value.")] private float scaleLerpTime = 0.001f; /// <summary> /// Enter amount representing amount of smoothing to apply to the scale. Smoothing of 0 means no smoothing. Max value means no change to value. /// </summary> public float ScaleLerpTime { get => scaleLerpTime; set => scaleLerpTime = value; } [SerializeField] [Tooltip("Enable or disable constraint support of this component. When enabled transform " + "changes will be post processed by the linked constraint manager.")] private bool enableConstraints = true; /// <summary> /// Enable or disable constraint support of this component. When enabled, transform /// changes will be post processed by the linked constraint manager. /// </summary> public bool EnableConstraints { get => enableConstraints; set => enableConstraints = value; } [SerializeField] [Tooltip("Constraint manager slot to enable constraints when manipulating the object.")] private ConstraintManager constraintsManager; /// <summary> /// Constraint manager slot to enable constraints when manipulating the object. /// </summary> public ConstraintManager ConstraintsManager { get => constraintsManager; set => constraintsManager = value; } [SerializeField] [Tooltip("Elastics Manager slot to enable elastics simulation when manipulating the object.")] private ElasticsManager elasticsManager; /// <summary> /// Elastics Manager slot to enable elastics simulation when manipulating the object. /// </summary> public ElasticsManager ElasticsManager { get => elasticsManager; set => elasticsManager = value; } #endregion Serialized Fields #region Event handlers [Header("Manipulation Events")] [SerializeField] [FormerlySerializedAs("OnManipulationStarted")] private ManipulationEvent onManipulationStarted = new ManipulationEvent(); /// <summary> /// Unity event raised on manipulation started /// </summary> public ManipulationEvent OnManipulationStarted { get => onManipulationStarted; set => onManipulationStarted = value; } [SerializeField] [FormerlySerializedAs("OnManipulationEnded")] private ManipulationEvent onManipulationEnded = new ManipulationEvent(); /// <summary> /// Unity event raised on manipulation ended /// </summary> public ManipulationEvent OnManipulationEnded { get => onManipulationEnded; set => onManipulationEnded = value; } [SerializeField] [FormerlySerializedAs("OnHoverEntered")] private ManipulationEvent onHoverEntered = new ManipulationEvent(); /// <summary> /// Unity event raised on hover started /// </summary> public ManipulationEvent OnHoverEntered { get => onHoverEntered; set => onHoverEntered = value; } [SerializeField] [FormerlySerializedAs("OnHoverExited")] private ManipulationEvent onHoverExited = new ManipulationEvent(); /// <summary> /// Unity event raised on hover ended /// </summary> public ManipulationEvent OnHoverExited { get => onHoverExited; set => onHoverExited = value; } #endregion Event Handlers #region Private Properties private ManipulationMoveLogic moveLogic; private TwoHandScaleLogic scaleLogic; private TwoHandRotateLogic rotateLogic; private ITransformSmoothingLogic smoothingLogic; /// <summary> /// Holds the pointer and the initial intersection point of the pointer ray /// with the object on pointer down in pointer space /// </summary> private struct PointerData { public IMixedRealityPointer pointer; private Vector3 initialGrabPointInPointer; public PointerData(IMixedRealityPointer pointer, Vector3 worldGrabPoint) : this() { this.pointer = pointer; this.initialGrabPointInPointer = Quaternion.Inverse(pointer.Rotation) * (worldGrabPoint - pointer.Position); } public bool IsNearPointer => pointer is IMixedRealityNearPointer; /// Returns the grab point on the manipulated object in world space public Vector3 GrabPoint => (pointer.Rotation * initialGrabPointInPointer) + pointer.Position; } private Dictionary<uint, PointerData> pointerIdToPointerMap = new Dictionary<uint, PointerData>(); private Quaternion objectToGripRotation; private bool isNearManipulation; private bool isManipulationStarted; private bool isSmoothing; private Rigidbody rigidBody; private bool wasGravity = false; private bool wasKinematic = false; private bool IsOneHandedManipulationEnabled => manipulationType.HasFlag(ManipulationHandFlags.OneHanded) && pointerIdToPointerMap.Count == 1; private bool IsTwoHandedManipulationEnabled => manipulationType.HasFlag(ManipulationHandFlags.TwoHanded) && pointerIdToPointerMap.Count > 1; private Quaternion leftHandRotation; private Quaternion rightHandRotation; #endregion Private Properties #region MonoBehaviour Functions private void Awake() { moveLogic = new ManipulationMoveLogic(); rotateLogic = new TwoHandRotateLogic(); scaleLogic = new TwoHandScaleLogic(); smoothingLogic = Activator.CreateInstance(transformSmoothingLogicType) as ITransformSmoothingLogic; if (elasticsManager) { elasticsManager.InitializeElastics(HostTransform); } } private void Start() { rigidBody = HostTransform.GetComponent<Rigidbody>(); if (constraintsManager == null && EnableConstraints) { constraintsManager = gameObject.EnsureComponent<ConstraintManager>(); } // Get child objects with NearInteractionGrabbable attached var children = GetComponentsInChildren<NearInteractionGrabbable>(); if (children.Length == 0) { Debug.Log($"Near interactions are not enabled for {gameObject.name}. To enable near interactions, add a " + $"{nameof(NearInteractionGrabbable)} component to {gameObject.name} or to a child object of {gameObject.name} that contains a collider."); } } #endregion #region Private Methods /// <summary> /// Calculates the unweighted average, or centroid, of all pointers' /// grab points, as defined by the PointerData.GrabPoint property. /// Does not use the rotation of each pointer; represents a pure /// geometric centroid of the grab points in world space. /// </summary> /// <returns> /// Worldspace grab point centroid of all pointers /// in pointerIdToPointerMap. /// </returns> private Vector3 GetPointersGrabPoint() { Vector3 sum = Vector3.zero; int count = 0; foreach (var p in pointerIdToPointerMap.Values) { sum += p.GrabPoint; count++; } return sum / Math.Max(1, count); } /// <summary> /// Calculates the multiple-handed pointer pose, used for /// far-interaction hand-ray-based manipulations. Uses the /// unweighted vector average of the pointers' forward vectors /// to calculate a compound pose that takes into account the /// pointing direction of each pointer. /// </summary> /// <returns> /// Compound pose calculated as the average of the poses /// corresponding to all of the pointers in pointerIdToPointerMap. /// </returns> private MixedRealityPose GetPointersPose() { Vector3 sumPos = Vector3.zero; Vector3 sumDir = Vector3.zero; int count = 0; foreach (var p in pointerIdToPointerMap.Values) { sumPos += p.pointer.Position; sumDir += p.pointer.Rotation * Vector3.forward; count++; } return new MixedRealityPose { Position = sumPos / Math.Max(1, count), Rotation = Quaternion.LookRotation(sumDir / Math.Max(1, count)) }; } private Vector3 GetPointersVelocity() { Vector3 sum = Vector3.zero; int numControllers = 0; foreach (var p in pointerIdToPointerMap.Values) { // Check pointer has a valid controller (e.g. gaze pointer doesn't) if (p.pointer.Controller != null) { numControllers++; sum += p.pointer.Controller.Velocity; } } return sum / Math.Max(1, numControllers); } private Vector3 GetPointersAngularVelocity() { Vector3 sum = Vector3.zero; int numControllers = 0; foreach (var p in pointerIdToPointerMap.Values) { // Check pointer has a valid controller (e.g. gaze pointer doesn't) if (p.pointer.Controller != null) { numControllers++; sum += p.pointer.Controller.AngularVelocity; } } return sum / Math.Max(1, numControllers); } private bool IsNearManipulation() { foreach (var item in pointerIdToPointerMap) { if (item.Value.IsNearPointer) { return true; } } return false; } #endregion Private Methods #region Public Methods /// <summary> /// Releases the object that is currently manipulated /// </summary> public void ForceEndManipulation() { // end manipulation if (isManipulationStarted) { HandleManipulationEnded(GetPointersGrabPoint(), GetPointersVelocity(), GetPointersAngularVelocity()); } pointerIdToPointerMap.Clear(); } /// <summary> /// Gets the grab point for the given pointer id. /// Only use if you know that your given pointer id corresponds to a pointer that has grabbed /// this component. /// </summary> public Vector3 GetPointerGrabPoint(uint pointerId) { Assert.IsTrue(pointerIdToPointerMap.ContainsKey(pointerId)); return pointerIdToPointerMap[pointerId].GrabPoint; } #endregion Public Methods #region Hand Event Handlers /// <inheritdoc /> public void OnPointerDown(MixedRealityPointerEventData eventData) { if (eventData.used || (!allowFarManipulation && eventData.Pointer as IMixedRealityNearPointer == null)) { return; } // If we only allow one handed manipulations, check there is no hand interacting yet. if (manipulationType != ManipulationHandFlags.OneHanded || pointerIdToPointerMap.Count == 0) { uint id = eventData.Pointer.PointerId; // Ignore poke pointer events if (!pointerIdToPointerMap.ContainsKey(id)) { // cache start ptr grab point pointerIdToPointerMap.Add(id, new PointerData(eventData.Pointer, eventData.Pointer.Result.Details.Point)); // Re-initialize elastic systems. if (elasticsManager) { elasticsManager.InitializeElastics(HostTransform); } // Call manipulation started handlers if (IsTwoHandedManipulationEnabled) { if (!isManipulationStarted) { HandleManipulationStarted(); } HandleTwoHandManipulationStarted(); } else if (IsOneHandedManipulationEnabled) { if (!isManipulationStarted) { HandleManipulationStarted(); } HandleOneHandMoveStarted(); } } } if (pointerIdToPointerMap.Count > 0) { // Always mark the pointer data as used to prevent any other behavior to handle pointer events // as long as the ObjectManipulator is active. // This is due to us reacting to both "Select" and "Grip" events. eventData.Use(); } } public void OnPointerDragged(MixedRealityPointerEventData eventData) { // Call manipulation updated handlers if (IsOneHandedManipulationEnabled) { HandleOneHandMoveUpdated(); } else if (IsTwoHandedManipulationEnabled) { HandleTwoHandManipulationUpdated(); } } /// <inheritdoc /> public void OnPointerUp(MixedRealityPointerEventData eventData) { // Get pointer data before they are removed from the map Vector3 grabPoint = GetPointersGrabPoint(); Vector3 velocity = GetPointersVelocity(); Vector3 angularVelocity = GetPointersAngularVelocity(); uint id = eventData.Pointer.PointerId; if (pointerIdToPointerMap.ContainsKey(id)) { pointerIdToPointerMap.Remove(id); } // Call manipulation ended handlers var handsPressedCount = pointerIdToPointerMap.Count; if (manipulationType.HasFlag(ManipulationHandFlags.TwoHanded) && handsPressedCount == 1) { if (manipulationType.HasFlag(ManipulationHandFlags.OneHanded)) { HandleOneHandMoveStarted(); } else { HandleManipulationEnded(grabPoint, velocity, angularVelocity); } } else if (isManipulationStarted && handsPressedCount == 0) { HandleManipulationEnded(grabPoint, velocity, angularVelocity); } eventData.Use(); } #endregion Hand Event Handlers #region Private Event Handlers private void HandleTwoHandManipulationStarted() { var handPositionArray = GetHandPositionArray(); if (twoHandedManipulationType.HasFlag(TransformFlags.Rotate)) { rotateLogic.Setup(handPositionArray, HostTransform); } if (twoHandedManipulationType.HasFlag(TransformFlags.Move)) { // If near manipulation, a pure grabpoint centroid is used for // the initial pointer pose; if far manipulation, a more complex // look-rotation-based pointer pose is used. MixedRealityPose pointerPose = IsNearManipulation() ? new MixedRealityPose(GetPointersGrabPoint()) : GetPointersPose(); MixedRealityPose hostPose = new MixedRealityPose(HostTransform.position, HostTransform.rotation); moveLogic.Setup(pointerPose, GetPointersGrabPoint(), hostPose, HostTransform.localScale); } if (twoHandedManipulationType.HasFlag(TransformFlags.Scale)) { scaleLogic.Setup(handPositionArray, HostTransform); } } private void HandleTwoHandManipulationUpdated() { var targetTransform = new MixedRealityTransform(HostTransform.position, HostTransform.rotation, HostTransform.localScale); var handPositionArray = GetHandPositionArray(); if (twoHandedManipulationType.HasFlag(TransformFlags.Scale)) { targetTransform.Scale = scaleLogic.UpdateMap(handPositionArray); if (EnableConstraints && constraintsManager != null) { constraintsManager.ApplyScaleConstraints(ref targetTransform, false, IsNearManipulation()); } } if (twoHandedManipulationType.HasFlag(TransformFlags.Rotate)) { targetTransform.Rotation = rotateLogic.Update(handPositionArray, targetTransform.Rotation); if (EnableConstraints && constraintsManager != null) { constraintsManager.ApplyRotationConstraints(ref targetTransform, false, IsNearManipulation()); } } if (twoHandedManipulationType.HasFlag(TransformFlags.Move)) { // If near manipulation, a pure GrabPoint centroid is used for // the pointer pose; if far manipulation, a more complex // look-rotation-based pointer pose is used. MixedRealityPose pose = IsNearManipulation() ? new MixedRealityPose(GetPointersGrabPoint()) : GetPointersPose(); targetTransform.Position = moveLogic.Update(pose, targetTransform.Rotation, targetTransform.Scale, true); if (EnableConstraints && constraintsManager != null) { constraintsManager.ApplyTranslationConstraints(ref targetTransform, false, IsNearManipulation()); } } ApplyTargetTransform(targetTransform); } private void HandleOneHandMoveStarted() { Assert.IsTrue(pointerIdToPointerMap.Count == 1); PointerData pointerData = GetFirstPointer(); IMixedRealityPointer pointer = pointerData.pointer; // Calculate relative transform from object to grip. Quaternion gripRotation; TryGetGripRotation(pointer, out gripRotation); Quaternion worldToGripRotation = Quaternion.Inverse(gripRotation); objectToGripRotation = worldToGripRotation * HostTransform.rotation; MixedRealityPose pointerPose = new MixedRealityPose(pointer.Position, pointer.Rotation); MixedRealityPose hostPose = new MixedRealityPose(HostTransform.position, HostTransform.rotation); moveLogic.Setup(pointerPose, pointerData.GrabPoint, hostPose, HostTransform.localScale); } private void HandleOneHandMoveUpdated() { Debug.Assert(pointerIdToPointerMap.Count == 1); PointerData pointerData = GetFirstPointer(); IMixedRealityPointer pointer = pointerData.pointer; var targetTransform = new MixedRealityTransform(HostTransform.position, HostTransform.rotation, HostTransform.localScale); if (EnableConstraints && constraintsManager != null) { constraintsManager.ApplyScaleConstraints(ref targetTransform, true, IsNearManipulation()); } Quaternion gripRotation; TryGetGripRotation(pointer, out gripRotation); targetTransform.Rotation = gripRotation * objectToGripRotation; if (EnableConstraints && constraintsManager != null) { constraintsManager.ApplyRotationConstraints(ref targetTransform, true, IsNearManipulation()); } RotateInOneHandType rotateInOneHandType = isNearManipulation ? oneHandRotationModeNear : oneHandRotationModeFar; MixedRealityPose pointerPose = new MixedRealityPose(pointer.Position, pointer.Rotation); targetTransform.Position = moveLogic.Update(pointerPose, targetTransform.Rotation, targetTransform.Scale, rotateInOneHandType != RotateInOneHandType.RotateAboutObjectCenter); if (EnableConstraints && constraintsManager != null) { constraintsManager.ApplyTranslationConstraints(ref targetTransform, true, IsNearManipulation()); } ApplyTargetTransform(targetTransform); } private void HandleManipulationStarted() { isManipulationStarted = true; isNearManipulation = IsNearManipulation(); isSmoothing = (isNearManipulation ? smoothingNear : smoothingFar); // TODO: If we are on HoloLens 1, push and pop modal input handler so that we can use old // gaze/gesture/voice manipulation. For HoloLens 2, we don't want to do this. if (OnManipulationStarted != null) { OnManipulationStarted.Invoke(new ManipulationEventData { ManipulationSource = gameObject, IsNearInteraction = isNearManipulation, Pointer = GetFirstPointer().pointer, PointerCentroid = GetPointersGrabPoint(), PointerVelocity = GetPointersVelocity(), PointerAngularVelocity = GetPointersAngularVelocity() }); } if (rigidBody != null) { wasGravity = rigidBody.useGravity; wasKinematic = rigidBody.isKinematic; rigidBody.useGravity = false; rigidBody.isKinematic = false; } if (EnableConstraints && constraintsManager != null) { constraintsManager.Initialize(new MixedRealityTransform(HostTransform)); } if (elasticsManager != null) { elasticsManager.EnableElasticsUpdate = false; } } private void HandleManipulationEnded(Vector3 pointerGrabPoint, Vector3 pointerVelocity, Vector3 pointerAnglularVelocity) { isManipulationStarted = false; // TODO: If we are on HoloLens 1, push and pop modal input handler so that we can use old // gaze/gesture/voice manipulation. For HoloLens 2, we don't want to do this. if (OnManipulationEnded != null) { OnManipulationEnded.Invoke(new ManipulationEventData { ManipulationSource = gameObject, IsNearInteraction = isNearManipulation, PointerCentroid = pointerGrabPoint, PointerVelocity = pointerVelocity, PointerAngularVelocity = pointerAnglularVelocity }); } ReleaseRigidBody(pointerVelocity, pointerAnglularVelocity); if (elasticsManager != null) { elasticsManager.EnableElasticsUpdate = true; } } #endregion Private Event Handlers #region Unused Event Handlers /// <inheritdoc /> public void OnPointerClicked(MixedRealityPointerEventData eventData) { } public void OnBeforeFocusChange(FocusEventData eventData) { } #endregion Unused Event Handlers #region Private methods private void ApplyTargetTransform(MixedRealityTransform targetTransform) { bool applySmoothing = isSmoothing && smoothingLogic != null; if (rigidBody == null) { TransformFlags transformUpdated = 0; if (elasticsManager != null) { transformUpdated = elasticsManager.ApplyTargetTransform(targetTransform); } if (!transformUpdated.HasFlag(TransformFlags.Move)) { HostTransform.position = applySmoothing ? smoothingLogic.SmoothPosition(HostTransform.position, targetTransform.Position, moveLerpTime, Time.deltaTime) : targetTransform.Position; } if (!transformUpdated.HasFlag(TransformFlags.Rotate)) { HostTransform.rotation = applySmoothing ? smoothingLogic.SmoothRotation(HostTransform.rotation, targetTransform.Rotation, rotateLerpTime, Time.deltaTime) : targetTransform.Rotation; } if (!transformUpdated.HasFlag(TransformFlags.Scale)) { HostTransform.localScale = applySmoothing ? smoothingLogic.SmoothScale(HostTransform.localScale, targetTransform.Scale, scaleLerpTime, Time.deltaTime) : targetTransform.Scale; } } else { // There is a RigidBody. Potential different paths for near vs far manipulation if (isNearManipulation && !useForcesForNearManipulation) { // This is a near manipulation and we're not using forces // Apply direct updates but account for smoothing if (applySmoothing) { rigidBody.MovePosition(smoothingLogic.SmoothPosition(rigidBody.position, targetTransform.Position, moveLerpTime, Time.deltaTime)); rigidBody.MoveRotation(smoothingLogic.SmoothRotation(rigidBody.rotation, targetTransform.Rotation, rotateLerpTime, Time.deltaTime)); } else { rigidBody.MovePosition(targetTransform.Position); rigidBody.MoveRotation(targetTransform.Rotation); } } else { // We are using forces rigidBody.velocity = ((1f - Mathf.Pow(moveLerpTime, Time.deltaTime)) / Time.deltaTime) * (targetTransform.Position - HostTransform.position); var relativeRotation = targetTransform.Rotation * Quaternion.Inverse(HostTransform.rotation); relativeRotation.ToAngleAxis(out float angle, out Vector3 axis); if (axis.IsValidVector()) { if (angle > 180f) { angle -= 360f; } rigidBody.angularVelocity = ((1f - Mathf.Pow(rotateLerpTime, Time.deltaTime)) / Time.deltaTime) * (axis.normalized * angle * Mathf.Deg2Rad); } } HostTransform.localScale = applySmoothing ? smoothingLogic.SmoothScale(HostTransform.localScale, targetTransform.Scale, scaleLerpTime, Time.deltaTime) : targetTransform.Scale; } } private Vector3[] GetHandPositionArray() { var handPositionMap = new Vector3[pointerIdToPointerMap.Count]; int index = 0; foreach (var item in pointerIdToPointerMap) { handPositionMap[index++] = item.Value.pointer.Position; } return handPositionMap; } public void OnFocusChanged(FocusEventData eventData) { bool isFar = !(eventData.Pointer is IMixedRealityNearPointer); if (isFar && !AllowFarManipulation) { return; } if (eventData.OldFocusedObject == null || !eventData.OldFocusedObject.transform.IsChildOf(transform)) { if (OnHoverEntered != null) { OnHoverEntered.Invoke(new ManipulationEventData { ManipulationSource = gameObject, Pointer = eventData.Pointer, IsNearInteraction = !isFar }); } } else if (eventData.NewFocusedObject == null || !eventData.NewFocusedObject.transform.IsChildOf(transform)) { if (OnHoverExited != null) { OnHoverExited.Invoke(new ManipulationEventData { ManipulationSource = gameObject, Pointer = eventData.Pointer, IsNearInteraction = !isFar }); } } } private void ReleaseRigidBody(Vector3 velocity, Vector3 angularVelocity) { if (rigidBody != null) { rigidBody.useGravity = wasGravity; rigidBody.isKinematic = wasKinematic; // Match the object's velocity to the controller for near interactions // Otherwise keep the objects current velocity so that it's not dampened unnaturally if (isNearManipulation) { if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepVelocity)) { rigidBody.velocity = velocity; } if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepAngularVelocity)) { rigidBody.angularVelocity = angularVelocity; } } } } private PointerData GetFirstPointer() { // We may be able to do this without allocating memory. // Moving to a method for later investigation. return pointerIdToPointerMap.Values.First(); } private bool TryGetGripRotation(IMixedRealityPointer pointer, out Quaternion rotation) { rotation = Quaternion.identity; switch (pointer.Controller?.ControllerHandedness) { case Handedness.Left: rotation = leftHandRotation; break; case Handedness.Right: rotation = rightHandRotation; break; default: return false; } return true; } #endregion #region Source Pose Handler Implementation /// <summary> /// Raised when the source pose tracking state is changed. /// </summary> public void OnSourcePoseChanged(SourcePoseEventData<TrackingState> eventData) { } /// <summary> /// Raised when the source position is changed. /// </summary> public void OnSourcePoseChanged(SourcePoseEventData<Vector2> eventData) { } /// <summary> /// Raised when the source position is changed. /// </summary> public void OnSourcePoseChanged(SourcePoseEventData<Vector3> eventData) { } /// <summary> /// Raised when the source rotation is changed. /// </summary> public void OnSourcePoseChanged(SourcePoseEventData<Quaternion> eventData) { } /// <summary> /// Raised when the source pose is changed. /// </summary> public void OnSourcePoseChanged(SourcePoseEventData<MixedRealityPose> eventData) { switch (eventData.Controller?.ControllerHandedness) { case Handedness.Left: leftHandRotation = eventData.SourceData.Rotation; break; case Handedness.Right: rightHandRotation = eventData.SourceData.Rotation; break; default: break; } } public void OnSourceDetected(SourceStateEventData eventData) { } public void OnSourceLost(SourceStateEventData eventData) { } #endregion } }
using UnityEngine; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.Security.AccessControl; using System; using System.Xml; using System.Xml.Serialization; using System.Text; /// <summary> /// Recording /// Serialized to save recordings /// Fields can be added (and will assume their default value if not available in the file) /// but removing or renaming a field will result in an exception when a file is next loaded /// </summary> [System.Serializable] public class Recording { [System.Serializable] public struct Score { public float time; public float score; public float speed; public void Write(BinaryWriter writer) { writer.Write(time); writer.Write(score); writer.Write(speed); } public void Read(BinaryReader reader) { time = reader.ReadSingle(); score = reader.ReadSingle(); speed = reader.ReadSingle(); } } [System.Serializable] public struct State { public bool grappling; public float3 grapplepos; public float3 position; public float3 velocity; public void Write(BinaryWriter writer) { writer.Write(grappling); grapplepos.Write(writer); position.Write(writer); velocity.Write(writer); } public void Read(BinaryReader reader) { grappling = reader.ReadBoolean(); grapplepos.Read(reader); position.Read(reader); velocity.Read(reader); } } [System.Serializable] public struct float3 { public float x, y, z; public Vector3 ToVector() { return new Vector3(x, y, z); } public void Write(BinaryWriter writer) { writer.Write(x); writer.Write(y); writer.Write(z); } public void Read(BinaryReader reader) { x = reader.ReadSingle(); y = reader.ReadSingle(); z = reader.ReadSingle(); } } public const string dir = "/recordings"; public const int VERSION = 2; public string SaveDir { get { return Application.persistentDataPath + dir; } } public bool flagged = false; public int fps = 0; public Score score; public string levelName; public List<State> states = new List<State>(); public string playername = "Steve"; public void Add(Vector3 position, Vector3 velocity, bool grappling, Vector3 grapple) { State state; state.position.x = position.x; state.position.y = position.y; state.position.z = position.z; state.velocity.x = velocity.x; state.velocity.y = velocity.y; state.velocity.z = velocity.z; state.grappling = grappling; state.grapplepos.x = grapple.x; state.grapplepos.y = grapple.y; state.grapplepos.z = grapple.z; if (states == null) { states = new List<State>(); } states.Add(state); } public Vector3 GetPosition(float time) { if (states.Count == 0) return Vector3.zero; float frame = fps * time; int firstframe = (int)frame; int nextFrame = firstframe + 1; float lerpCoefficient = frame - (float)firstframe; if (firstframe < 0) return states[0].position.ToVector(); else if (firstframe >= states.Count || nextFrame >= states.Count) return states[states.Count-1].position.ToVector(); Vector3 last = states[firstframe].position.ToVector(); Vector3 next = states[nextFrame].position.ToVector(); Vector3 v = Vector3.Lerp(last, next, lerpCoefficient); v = last; return v; } public Vector3 GetVelocity(float time) { if (states.Count == 0) return Vector3.zero; float frame = fps * time; int firstframe = (int)frame; int nextFrame = firstframe + 1; float lerpCoefficient = frame - (float)firstframe; if (firstframe < 0) return states[0].velocity.ToVector(); else if (firstframe >= states.Count || nextFrame >= states.Count) return states[states.Count-1].velocity.ToVector(); Vector3 last = states[firstframe].velocity.ToVector(); Vector3 next = states[nextFrame].velocity.ToVector(); return Vector3.Lerp(last, next, lerpCoefficient); } public bool IsGrappling(float time) { int frame = (int)(fps * time); if (frame < 0 || frame >= states.Count) return false; return states[frame].grappling; } public Vector3 GetGrapplePos(float time) { Vector3 pos = new Vector3(0, 0, 0); int frame = (int)(fps * time); if (frame >= 0 && frame < states.Count) { pos.x = states[frame].grapplepos.x; pos.y = states[frame].grapplepos.y; pos.z = states[frame].grapplepos.z; } return pos; } public string Write(string filename) { string fullfilename = filename; // Write the recording to file. FileStream file = new FileStream(fullfilename, FileMode.OpenOrCreate, FileAccess.Write); Write(file); file.Close(); return fullfilename; } public void Write(Stream stream) { BinaryWriter writer = new BinaryWriter(stream); // Write the version number writer.Write(VERSION); // Write the flagged value writer.Write(flagged); // Write the fps writer.Write(fps); // Write the score score.Write(writer); // Write the level name writer.Write(levelName); // Write the players name. writer.Write(playername); // Write all the states. writer.Write(states.Count); // How many states there are. for (int i = 0; i < states.Count; ++i) { states[i].Write(writer); } writer.Close(); } public static Recording Read(string filename) { // Open the file. FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(file); Recording rec = Read(reader); reader.Close(); file.Close(); return rec; } public static Recording Read(BinaryReader reader) { // Read the version of the recording. Recording read = null; int version = reader.ReadInt32(); switch (version) { case 1: read = Read1(reader); break; case 2: read = Read2(reader); break; default: throw new NotImplementedException(); } return read; } public static Recording Read1(BinaryReader reader) { // Create a recording Recording rec = new Recording(); // Read the flagged value rec.flagged = reader.ReadBoolean(); // Read the fps rec.fps = reader.ReadInt32(); // Read the score. rec.score.Read(reader); // Read the level name rec.levelName = reader.ReadString(); // Read all the states. int stateCount = reader.ReadInt32(); for (int i = 0; i < stateCount; ++i) { State state = new State(); state.Read(reader); rec.states.Add(state); } return rec; } public static Recording Read2(BinaryReader reader) { // Create a recording Recording rec = new Recording(); // Read the flagged value rec.flagged = reader.ReadBoolean(); // Read the fps rec.fps = reader.ReadInt32(); // Read the score. rec.score.Read(reader); // Read the level name rec.levelName = reader.ReadString(); // Read the players name rec.playername = reader.ReadString(); // Read all the states. int stateCount = reader.ReadInt32(); for (int i = 0; i < stateCount; ++i) { State state = new State(); state.Read(reader); rec.states.Add(state); } return rec; } }
//------------------------------------------------------------------------------ // <copyright file="Style.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Globalization; using System.Text; using System.Web; using System.Web.UI; /// <devdoc> /// <para> Defines the properties and methods of the <see cref='System.Web.UI.WebControls.Style'/> class.</para> /// </devdoc> [ ToolboxItem(false), TypeConverterAttribute(typeof(EmptyStringExpandableObjectConverter)) ] public class Style : Component, IStateManager { // !!NOTE!! // PanelStyle also defines a set of flag contants and both sets have to // be unique. Please be careful when adding new flags to either list. internal const int UNUSED = 0x0001; internal const int PROP_CSSCLASS = 0x0002; internal const int PROP_FORECOLOR = 0x0004; internal const int PROP_BACKCOLOR = 0x0008; internal const int PROP_BORDERCOLOR = 0x0010; internal const int PROP_BORDERWIDTH = 0x0020; internal const int PROP_BORDERSTYLE = 0x0040; internal const int PROP_HEIGHT = 0x0080; internal const int PROP_WIDTH = 0x0100; internal const int PROP_FONT_NAMES = 0x0200; internal const int PROP_FONT_SIZE = 0x0400; internal const int PROP_FONT_BOLD = 0x0800; internal const int PROP_FONT_ITALIC = 0x1000; internal const int PROP_FONT_UNDERLINE = 0x2000; internal const int PROP_FONT_OVERLINE = 0x4000; internal const int PROP_FONT_STRIKEOUT = 0x8000; internal const string SetBitsKey = "_!SB"; private StateBag statebag; private FontInfo fontInfo; private string registeredCssClass; private bool ownStateBag; private bool marked; private int setBits; private int markedBits; // For performance, use this array instead of Enum.Format() to convert a BorderStyle to // a string. CLR is investigating improving the perf of Enum.Format(). (VSWhidbey internal static readonly string[] borderStyles = new string[] {"NotSet", "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "Outset"}; /// <devdoc> /// Initializes a new instance of the Style class. /// </devdoc> public Style() : this(null) { ownStateBag = true; } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.UI.WebControls.Style'/> class with the /// specified state bag information. Do not use this constructor if you are overriding /// CreateControlStyle() and are changing some properties on the created style. /// </para> /// </devdoc> public Style(StateBag bag) { statebag = bag; marked = false; setBits = 0; // VSWhidbey 541984: Style inherits from Component and requires finalization, resulting in bad performance // When inheriting, if finalization is desired, call GC.ReRegisterForFinalize GC.SuppressFinalize(this); } /// <devdoc> /// <para> /// Gets or sets the background color property of the <see cref='System.Web.UI.WebControls.Style'/> class. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(typeof(Color), ""), WebSysDescription(SR.Style_BackColor), NotifyParentProperty(true), TypeConverterAttribute(typeof(WebColorConverter)) ] public Color BackColor { get { if (IsSet(PROP_BACKCOLOR)) { return(Color)(ViewState["BackColor"]); } return Color.Empty; } set { ViewState["BackColor"] = value; SetBit(PROP_BACKCOLOR); } } /// <devdoc> /// <para> /// Gets or sets the border color property of the <see cref='System.Web.UI.WebControls.Style'/> class. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(typeof(Color), ""), WebSysDescription(SR.Style_BorderColor), NotifyParentProperty(true), TypeConverterAttribute(typeof(WebColorConverter)) ] public Color BorderColor { get { if (IsSet(PROP_BORDERCOLOR)) { return(Color)(ViewState["BorderColor"]); } return Color.Empty; } set { ViewState["BorderColor"] = value; SetBit(PROP_BORDERCOLOR); } } /// <devdoc> /// <para> /// Gets or sets the border width property of the <see cref='System.Web.UI.WebControls.Style'/> class. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(typeof(Unit), ""), WebSysDescription(SR.Style_BorderWidth), NotifyParentProperty(true) ] public Unit BorderWidth { get { if (IsSet(PROP_BORDERWIDTH)) { return(Unit)(ViewState["BorderWidth"]); } return Unit.Empty; } set { if ((value.Type == UnitType.Percentage) || (value.Value < 0)) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.Style_InvalidBorderWidth)); } ViewState["BorderWidth"] = value; SetBit(PROP_BORDERWIDTH); } } /// <devdoc> /// <para>Gets or sets the border style property of the <see cref='System.Web.UI.WebControls.Style'/> /// class.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(BorderStyle.NotSet), WebSysDescription(SR.Style_BorderStyle), NotifyParentProperty(true) ] public BorderStyle BorderStyle { get { if (IsSet(PROP_BORDERSTYLE)) { return(BorderStyle)(ViewState["BorderStyle"]); } return BorderStyle.NotSet; } set { if (value < BorderStyle.NotSet || value > BorderStyle.Outset) { throw new ArgumentOutOfRangeException("value"); } ViewState["BorderStyle"] = value; SetBit(PROP_BORDERSTYLE); } } /// <devdoc> /// <para>Gets or sets the CSS class property of the <see cref='System.Web.UI.WebControls.Style'/> class.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.Style_CSSClass), NotifyParentProperty(true), CssClassProperty() ] public string CssClass { get { if (IsSet(PROP_CSSCLASS)) { string s = (string)ViewState["CssClass"]; return (s == null) ? String.Empty : s; } return String.Empty; } set { ViewState["CssClass"] = value; SetBit(PROP_CSSCLASS); } } /// <devdoc> /// <para>Gets font information of the <see cref='System.Web.UI.WebControls.Style'/> class.</para> /// </devdoc> [ WebCategory("Appearance"), WebSysDescription(SR.Style_Font), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true) ] public FontInfo Font { get { if (fontInfo == null) fontInfo = new FontInfo(this); return fontInfo; } } /// <devdoc> /// <para> /// Gets or sets the foreground color (typically the color /// of the text) property of the <see cref='System.Web.UI.WebControls.Style'/> /// class. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(typeof(Color), ""), WebSysDescription(SR.Style_ForeColor), NotifyParentProperty(true), TypeConverterAttribute(typeof(WebColorConverter)) ] public Color ForeColor { get { if (IsSet(PROP_FORECOLOR)) { return(Color)(ViewState["ForeColor"]); } return Color.Empty; } set { ViewState["ForeColor"] = value; SetBit(PROP_FORECOLOR); } } /// <devdoc> /// <para> /// Gets or sets the height property of the <see cref='System.Web.UI.WebControls.Style'/> class. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(typeof(Unit), ""), WebSysDescription(SR.Style_Height), NotifyParentProperty(true) ] public Unit Height { get { if (IsSet(PROP_HEIGHT)) { return(Unit)(ViewState["Height"]); } return Unit.Empty; } set { if (value.Value < 0) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.Style_InvalidHeight)); } ViewState["Height"] = value; SetBit(PROP_HEIGHT); } } /// <internalonly/> /// <devdoc> /// Gets a value indicating whether any style properties have been set. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public virtual bool IsEmpty { [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get { return ((setBits == 0) && (RegisteredCssClass.Length == 0)); } } /// <devdoc> /// Returns a value indicating whether /// any style elements have been defined in the state bag. /// </devdoc> protected bool IsTrackingViewState { get { return marked; } } /// <devdoc> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Advanced) ] public string RegisteredCssClass { get { if (registeredCssClass == null) { return String.Empty; } return registeredCssClass; } } /// <internalonly/> /// <devdoc> /// Gets the state bag that holds the style properties. /// Marked as internal, because FontInfo accesses view state of its owner Style /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] protected internal StateBag ViewState { get { if (statebag == null) { statebag = new StateBag(false); if (IsTrackingViewState) statebag.TrackViewState(); } return statebag; } } /// <devdoc> /// <para> /// Gets or sets the width property of the <see cref='System.Web.UI.WebControls.Style'/> class. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(typeof(Unit), ""), WebSysDescription(SR.Style_Width), NotifyParentProperty(true) ] public Unit Width { get { if (IsSet(PROP_WIDTH)) { return(Unit)(ViewState["Width"]); } return Unit.Empty; } set { if (value.Value < 0) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.Style_InvalidWidth)); } ViewState["Width"] = value; SetBit(PROP_WIDTH); } } /// <devdoc> /// </devdoc> public void AddAttributesToRender(HtmlTextWriter writer) { AddAttributesToRender(writer, null); } /// <devdoc> /// <para> /// Adds all non-blank style attributes to the HTML output stream to be rendered /// to the client. /// </para> /// </devdoc> public virtual void AddAttributesToRender(HtmlTextWriter writer, WebControl owner) { string cssClass = String.Empty; bool renderInlineStyle = true; if (IsSet(PROP_CSSCLASS)) { cssClass = (string)ViewState["CssClass"]; if (cssClass == null) { cssClass = String.Empty; } } if (!String.IsNullOrEmpty(registeredCssClass)) { renderInlineStyle = false; if (cssClass.Length != 0) { cssClass += " " + registeredCssClass; } else { cssClass = registeredCssClass; } } if (cssClass.Length > 0) { writer.AddAttribute(HtmlTextWriterAttribute.Class, cssClass); } if (renderInlineStyle) { CssStyleCollection styleAttributes = GetStyleAttributes(owner); styleAttributes.Render(writer); } } /// <devdoc> /// <para> /// Clears the setBits int of the given bit. /// </para> /// </devdoc> internal void ClearBit(int bit) { setBits &= ~bit; } /// <devdoc> /// <para> /// Copies non-blank elements from the specified style, /// overwriting existing style elements if necessary. /// </para> /// </devdoc> public virtual void CopyFrom(Style s) { if (RegisteredCssClass.Length != 0) { throw new InvalidOperationException(SR.GetString(SR.Style_RegisteredStylesAreReadOnly)); } if (s != null && !s.IsEmpty) { this.Font.CopyFrom(s.Font); if (s.IsSet(PROP_CSSCLASS)) this.CssClass = s.CssClass; // if the source Style is registered and this one isn't, // reset all the styles set by the source Style so it's // css class can be used to set those values if (s.RegisteredCssClass.Length != 0) { if (IsSet(PROP_CSSCLASS)) { CssClass += " " + s.RegisteredCssClass; } else { CssClass = s.RegisteredCssClass; } if (s.IsSet(PROP_BACKCOLOR) && (s.BackColor != Color.Empty)) { ViewState.Remove("BackColor"); ClearBit(PROP_BACKCOLOR); } if (s.IsSet(PROP_FORECOLOR) && (s.ForeColor != Color.Empty)) { ViewState.Remove("ForeColor"); ClearBit(PROP_FORECOLOR); } if (s.IsSet(PROP_BORDERCOLOR) && (s.BorderColor != Color.Empty)) { ViewState.Remove("BorderColor"); ClearBit(PROP_BORDERCOLOR); } if (s.IsSet(PROP_BORDERWIDTH) && (s.BorderWidth != Unit.Empty)) { ViewState.Remove("BorderWidth"); ClearBit(PROP_BORDERWIDTH); } if (s.IsSet(PROP_BORDERSTYLE)) { ViewState.Remove("BorderStyle"); ClearBit(PROP_BORDERSTYLE); } if (s.IsSet(PROP_HEIGHT) && (s.Height != Unit.Empty)) { ViewState.Remove("Height"); ClearBit(PROP_HEIGHT); } if (s.IsSet(PROP_WIDTH) && (s.Width != Unit.Empty)) { ViewState.Remove("Width"); ClearBit(PROP_WIDTH); } } else { if (s.IsSet(PROP_BACKCOLOR) && (s.BackColor != Color.Empty)) this.BackColor = s.BackColor; if (s.IsSet(PROP_FORECOLOR) && (s.ForeColor != Color.Empty)) this.ForeColor = s.ForeColor; if (s.IsSet(PROP_BORDERCOLOR) && (s.BorderColor != Color.Empty)) this.BorderColor = s.BorderColor; if (s.IsSet(PROP_BORDERWIDTH) && (s.BorderWidth != Unit.Empty)) this.BorderWidth = s.BorderWidth; if (s.IsSet(PROP_BORDERSTYLE)) this.BorderStyle = s.BorderStyle; if (s.IsSet(PROP_HEIGHT) && (s.Height != Unit.Empty)) this.Height = s.Height; if (s.IsSet(PROP_WIDTH) && (s.Width != Unit.Empty)) this.Width = s.Width; } } } protected virtual void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { StateBag viewState = ViewState; Color c; // ForeColor if (IsSet(PROP_FORECOLOR)) { c = (Color)viewState["ForeColor"]; if (!c.IsEmpty) { attributes.Add(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(c)); } } // BackColor if (IsSet(PROP_BACKCOLOR)) { c = (Color)viewState["BackColor"]; if (!c.IsEmpty) { attributes.Add(HtmlTextWriterStyle.BackgroundColor, ColorTranslator.ToHtml(c)); } } // BorderColor if (IsSet(PROP_BORDERCOLOR)) { c = (Color)viewState["BorderColor"]; if (!c.IsEmpty) { attributes.Add(HtmlTextWriterStyle.BorderColor, ColorTranslator.ToHtml(c)); } } BorderStyle bs = this.BorderStyle; Unit bu = this.BorderWidth; if (!bu.IsEmpty) { attributes.Add(HtmlTextWriterStyle.BorderWidth, bu.ToString(CultureInfo.InvariantCulture)); if (bs == BorderStyle.NotSet) { if (bu.Value != 0.0) { attributes.Add(HtmlTextWriterStyle.BorderStyle, "solid"); } } else { attributes.Add(HtmlTextWriterStyle.BorderStyle, borderStyles[(int)bs]); } } else { if (bs != BorderStyle.NotSet) { attributes.Add(HtmlTextWriterStyle.BorderStyle, borderStyles[(int)bs]); } } // need to call the property get in case we have font properties from view state and have not // created the font object FontInfo font = Font; // Font.Names string[] names = font.Names; if (names.Length > 0) { attributes.Add(HtmlTextWriterStyle.FontFamily, Style.FormatStringArray(names, ',')); } // Font.Size FontUnit fu = font.Size; if (fu.IsEmpty == false) { attributes.Add(HtmlTextWriterStyle.FontSize, fu.ToString(CultureInfo.InvariantCulture)); } // Font.Bold if (IsSet(PROP_FONT_BOLD)) { if (font.Bold) { attributes.Add(HtmlTextWriterStyle.FontWeight, "bold"); } else { attributes.Add(HtmlTextWriterStyle.FontWeight, "normal"); } } // Font.Italic if (IsSet(PROP_FONT_ITALIC)) { if (font.Italic == true) { attributes.Add(HtmlTextWriterStyle.FontStyle, "italic"); } else { attributes.Add(HtmlTextWriterStyle.FontStyle, "normal"); } } // string textDecoration = String.Empty; if (font.Underline) { textDecoration = "underline"; } if (font.Overline) { textDecoration += " overline"; } if (font.Strikeout) { textDecoration += " line-through"; } if (textDecoration.Length > 0) { attributes.Add(HtmlTextWriterStyle.TextDecoration, textDecoration); } else { if (IsSet(PROP_FONT_UNDERLINE) || IsSet(PROP_FONT_OVERLINE) || IsSet(PROP_FONT_STRIKEOUT)) { attributes.Add(HtmlTextWriterStyle.TextDecoration, "none"); } } Unit u; // Height if (IsSet(PROP_HEIGHT)) { u = (Unit)viewState["Height"]; if (!u.IsEmpty) { attributes.Add(HtmlTextWriterStyle.Height, u.ToString(CultureInfo.InvariantCulture)); } } // Width if (IsSet(PROP_WIDTH)) { u = (Unit)viewState["Width"]; if (!u.IsEmpty) { attributes.Add(HtmlTextWriterStyle.Width, u.ToString(CultureInfo.InvariantCulture)); } } } private static string FormatStringArray(string[] array, char delimiter) { int n = array.Length; if (n == 1) { return array[0]; } if (n == 0) { return String.Empty; } return String.Join(delimiter.ToString(CultureInfo.InvariantCulture), array); } /// <devdoc> /// Retrieves the collection of CSS style attributes represented by this style. /// </devdoc> public CssStyleCollection GetStyleAttributes(IUrlResolutionService urlResolver) { CssStyleCollection attributes = new CssStyleCollection(); FillStyleAttributes(attributes, urlResolver); return attributes; } /// <devdoc> /// Returns a value indicating whether the specified style /// property has been defined in the state bag. /// </devdoc> [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] internal bool IsSet(int propKey) { return (setBits & propKey) != 0; } /// <devdoc> /// Load the previously saved state. /// </devdoc> protected internal void LoadViewState(object state) { if (state != null && ownStateBag) ViewState.LoadViewState(state); if (statebag != null) { object o = ViewState[SetBitsKey]; if (o != null) { markedBits = (int)o; // markedBits indicates properties that got reloaded into // view state, so update setBits, to indicate these // properties are set as well. setBits |= markedBits; } } } /// <devdoc> /// A protected method. Marks the beginning for tracking /// state changes on the control. Any changes made after "mark" will be tracked and /// saved as part of the control viewstate. /// </devdoc> [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] protected internal virtual void TrackViewState() { if (ownStateBag) { ViewState.TrackViewState(); } marked = true; } /// <devdoc> /// Copies non-blank elements from the specified style, /// but will not overwrite any existing style elements. /// </devdoc> public virtual void MergeWith(Style s) { if (RegisteredCssClass.Length != 0) { throw new InvalidOperationException(SR.GetString(SR.Style_RegisteredStylesAreReadOnly)); } if (s == null || s.IsEmpty) return; if (IsEmpty) { // merge into an empty style is equivalent to a copy, which // is more efficient CopyFrom(s); return; } this.Font.MergeWith(s.Font); if (s.IsSet(PROP_CSSCLASS) && !this.IsSet(PROP_CSSCLASS)) this.CssClass = s.CssClass; // If the source Style is registered and this one isn't, copy // the CSS class and any style props not included in the CSS class // if they aren't set on this Style if (s.RegisteredCssClass.Length == 0) { if (s.IsSet(PROP_BACKCOLOR) && (!this.IsSet(PROP_BACKCOLOR) || (BackColor == Color.Empty))) this.BackColor = s.BackColor; if (s.IsSet(PROP_FORECOLOR) && (!this.IsSet(PROP_FORECOLOR) || (ForeColor == Color.Empty))) this.ForeColor = s.ForeColor; if (s.IsSet(PROP_BORDERCOLOR) && (!this.IsSet(PROP_BORDERCOLOR) || (BorderColor == Color.Empty))) this.BorderColor = s.BorderColor; if (s.IsSet(PROP_BORDERWIDTH) && (!this.IsSet(PROP_BORDERWIDTH) || (BorderWidth == Unit.Empty))) this.BorderWidth = s.BorderWidth; if (s.IsSet(PROP_BORDERSTYLE) && !this.IsSet(PROP_BORDERSTYLE)) this.BorderStyle = s.BorderStyle; if (s.IsSet(PROP_HEIGHT) && (!this.IsSet(PROP_HEIGHT) || (Height == Unit.Empty))) this.Height = s.Height; if (s.IsSet(PROP_WIDTH) && (!this.IsSet(PROP_WIDTH) || (Width == Unit.Empty))) this.Width = s.Width; } else { if (IsSet(PROP_CSSCLASS)) { CssClass += " " + s.RegisteredCssClass; } else { CssClass = s.RegisteredCssClass; } } } /// <devdoc> /// Clears out any defined style elements from the state bag. /// </devdoc> public virtual void Reset() { if (statebag != null) { if (IsSet(PROP_CSSCLASS)) ViewState.Remove("CssClass"); if (IsSet(PROP_BACKCOLOR)) ViewState.Remove("BackColor"); if (IsSet(PROP_FORECOLOR)) ViewState.Remove("ForeColor"); if (IsSet(PROP_BORDERCOLOR)) ViewState.Remove("BorderColor"); if (IsSet(PROP_BORDERWIDTH)) ViewState.Remove("BorderWidth"); if (IsSet(PROP_BORDERSTYLE)) ViewState.Remove("BorderStyle"); if (IsSet(PROP_HEIGHT)) ViewState.Remove("Height"); if (IsSet(PROP_WIDTH)) ViewState.Remove("Width"); Font.Reset(); ViewState.Remove(SetBitsKey); markedBits = 0; } setBits = 0; } /// <devdoc> /// Saves any state that has been modified /// after the TrackViewState method was invoked. /// </devdoc> protected internal virtual object SaveViewState() { if (statebag != null) { if (markedBits != 0) { // new bits or properties were changed // updating the state bag at this point will automatically mark // SetBitsKey as dirty, and it will be added to the resulting viewstate ViewState[SetBitsKey] = markedBits; } if (ownStateBag) return ViewState.SaveViewState(); } return null; } /// <internalonly/> protected internal virtual void SetBit(int bit) { setBits |= bit; if (IsTrackingViewState) { // since we're tracking changes, include this property change or // bit into the markedBits flag set. markedBits |= bit; } } public void SetDirty() { ViewState.SetDirty(true); markedBits = setBits; } /// <devdoc> /// Associated this Style with a CSS class as part of registration with /// a style sheet. /// </devdoc> internal void SetRegisteredCssClass(string cssClass) { registeredCssClass = cssClass; } #region Implementation of IStateManager /// <internalonly/> bool IStateManager.IsTrackingViewState { get { return IsTrackingViewState; } } /// <internalonly/> void IStateManager.LoadViewState(object state) { LoadViewState(state); } /// <internalonly/> void IStateManager.TrackViewState() { TrackViewState(); } /// <internalonly/> object IStateManager.SaveViewState() { return SaveViewState(); } #endregion } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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; using System.Collections.Generic; using System.Threading; namespace MindTouch.Collections { /// <summary> /// Exception thrown by <see cref="BlockingQueue{T}.Enqueue"/> and <see cref="BlockingQueue{T}.Dequeue"/> when the underlying queue has already been closed. /// </summary> public class QueueClosedException : Exception { /// <summary> /// Create a new exception instance. /// </summary> public QueueClosedException() : base("BlockingQueue has already been closed") { } } /// <summary> /// Provides a thread-safe queue that blocks on queue and dequeue operations under lock contention or when no items are available. /// </summary> /// <typeparam name="T">Type of the data items in the queue</typeparam> public interface IBlockingQueue<T> : IEnumerable<T> { //--- Properties --- /// <summary> /// <see langword="True"/> when the queue has been closed and can no longer accept new items, <see langword="False"/> otherwise. /// </summary> bool IsClosed { get; } /// <summary> /// Total number of items currently in the queue. /// </summary> int Count { get; } //--- Methods --- /// <summary> /// Attempt to dequeue an item from the queue. /// </summary> /// <remarks>Dequeue timeout can occur either because a lock could not be acquired or because no item was available.</remarks> /// <param name="timeout">Time to wait for an item to become available.</param> /// <param name="item">The location for a dequeue item.</param> /// <returns><see langword="True"/> if an item was dequeued, <see langword="False"/> if the operation timed out instead.</returns> bool TryDequeue(TimeSpan timeout, out T item); /// <summary> /// Blocking dequeue operation. Will not return until an item is available. /// </summary> /// <returns>A data item.</returns> /// <exception cref="QueueClosedException">Thrown when the queue is closed and has no more items.</exception> T Dequeue(); /// <summary> /// Enqueue a new item into the queue. /// </summary> /// <param name="data">A data item.</param> /// <exception cref="QueueClosedException">Thrown when the queue is closed and does not accept new items.</exception> void Enqueue(T data); /// <summary> /// Close the queue and stop it from accepting more items. /// </summary> /// <remarks>Pending items can still be dequeued.</remarks> void Close(); } /// <summary> /// Provides a thread-safe queue that blocks on queue and dequeue operations under lock contention or when no items are available. /// </summary> /// <typeparam name="T">Type of the data items in the queue</typeparam> public class BlockingQueue<T> : IBlockingQueue<T> { //--- Class Fields --- private static readonly log4net.ILog _log = LogUtils.CreateLog(); //--- Fields --- private readonly Queue<T> _queue = new Queue<T>(); private bool _closed; //--- Properties --- /// <summary> /// <see langword="True"/> when the queue has been closed and can no longer accept new items, <see langword="False"/> otherwise. /// </summary> public bool IsClosed { get { return _closed; } } /// <summary> /// Total number of items currently in the queue. /// </summary> public int Count { get { lock(_queue) return _queue.Count; } } //--- Methods ---- /// <summary> /// Blocking dequeue operation. Will not return until an item is available. /// </summary> /// <returns>A data item.</returns> /// <exception cref="QueueClosedException">Thrown when the queue is closed and has no more items.</exception> public T Dequeue() { T returnValue; if(!TryDequeue(TimeSpan.FromMilliseconds(-1), out returnValue)) { throw new QueueClosedException(); } return returnValue; } /// <summary> /// Attempt to dequeue an item from the queue. /// </summary> /// <remarks>Dequeue timeout can occur either because a lock could not be acquired or because no item was available.</remarks> /// <param name="timeout">Time to wait for an item to become available.</param> /// <param name="item">The location for a dequeue item.</param> /// <returns><see langword="True"/> if an item was dequeued, <see langword="False"/> if the operation timed out instead.</returns> public bool TryDequeue(TimeSpan timeout, out T item) { item = default(T); if(IsClosed && _queue.Count == 0) { _log.Debug("dropping out of dequeue, queue is empty and closed (1)"); return false; } lock(_queue) { while(_queue.Count == 0 && !IsClosed) { if(!Monitor.Wait(_queue, timeout, false)) { _log.Debug("dropping out of dequeue, timed out"); return false; } } if(_queue.Count == 0 && IsClosed) { _log.Debug("dropping out of dequeue, queue is empty and closed (2)"); return false; } item = _queue.Dequeue(); return true; } } /// <summary> /// Enqueue a new item into the queue. /// </summary> /// <param name="data">A data item.</param> /// <exception cref="QueueClosedException">Thrown when the queue is closed and does not accept new items.</exception> public void Enqueue(T data) { if(_closed) { throw new InvalidOperationException("cannot enqueue new items on a closed queue"); } lock(_queue) { _queue.Enqueue(data); Monitor.PulseAll(_queue); } } /// <summary> /// Close the queue and stop it from accepting more items. /// </summary> /// <remarks>Pending items can still be dequeued.</remarks> public void Close() { _log.Debug("closing queue"); _closed = true; lock(_queue) { Monitor.PulseAll(_queue); } } //--- IEnumerable<T> Members --- IEnumerator<T> IEnumerable<T>.GetEnumerator() { while(true) { T returnValue; if(!TryDequeue(TimeSpan.FromMilliseconds(-1), out returnValue)) { yield break; } yield return returnValue; } } //--- IEnumerable Members --- IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.Linq; using Aspose.HTML.Live.Demos.UI.Services.HTML.Applications.Conversion; using Aspose.HTML.Live.Demos.UI.Services.HTML.Applications.Merger; using Microsoft.Ajax.Utilities; namespace Aspose.HTML.Live.Demos.UI.Services.HTML.Applications { public class ApplicationRegistry { private Dictionary<ApplicationId, Application> applications; static ApplicationRegistry instance; static object sync = new object(); public static ApplicationRegistry Instance { get { if (instance == null) { lock (sync) { if (instance == null) instance = new ApplicationRegistry(); } } return instance; } } ApplicationRegistry() { applications = new Dictionary<ApplicationId, Application>(); // Conversion App Register<ConversionApplicationBuilder>(x => x .Handler(new HTMLConversionHandler(), o => o .Filter(FileFormat.HTML, FileFormat.PDF, true) .Filter(FileFormat.HTML, FileFormat.XPS, true) .Filter(FileFormat.HTML, FileFormat.JPEG) .Filter(FileFormat.HTML, FileFormat.PNG) .Filter(FileFormat.HTML, FileFormat.BMP) .Filter(FileFormat.HTML, FileFormat.TIFF, true) .Filter(FileFormat.HTML, FileFormat.GIF) .Filter(FileFormat.HTML, FileFormat.MD) ) .Handler(new HTMLConversionHandler(), o => o .Filter(FileFormat.XHTML, FileFormat.PDF, true) .Filter(FileFormat.XHTML, FileFormat.XPS, true) .Filter(FileFormat.XHTML, FileFormat.JPEG) .Filter(FileFormat.XHTML, FileFormat.PNG) .Filter(FileFormat.XHTML, FileFormat.BMP) .Filter(FileFormat.XHTML, FileFormat.TIFF, true) .Filter(FileFormat.XHTML, FileFormat.GIF) .Filter(FileFormat.XHTML, FileFormat.MD) ) .Handler(new HTMLToMHTMLConversionHandler(), o => o .Filter(FileFormat.HTML, FileFormat.MHTML, true) .Filter(FileFormat.XHTML, FileFormat.MHTML, true) ) .Handler(new MHTMLConversionHandler(), o => o .Filter(FileFormat.MHTML, FileFormat.PDF, true) .Filter(FileFormat.MHTML, FileFormat.XPS, true) .Filter(FileFormat.MHTML, FileFormat.JPEG) .Filter(FileFormat.MHTML, FileFormat.PNG) .Filter(FileFormat.MHTML, FileFormat.BMP) .Filter(FileFormat.MHTML, FileFormat.TIFF, true) .Filter(FileFormat.MHTML, FileFormat.GIF) ) .Handler(new EPUBConversionHandler(), o => o .Filter(FileFormat.EPUB, FileFormat.PDF, true) .Filter(FileFormat.EPUB, FileFormat.XPS, true) .Filter(FileFormat.EPUB, FileFormat.JPEG) .Filter(FileFormat.EPUB, FileFormat.PNG) .Filter(FileFormat.EPUB, FileFormat.BMP) .Filter(FileFormat.EPUB, FileFormat.TIFF, true) .Filter(FileFormat.EPUB, FileFormat.GIF) ) .Handler(new SVGConversionHandler(), o => o .Filter(FileFormat.SVG, FileFormat.PDF, true) .Filter(FileFormat.SVG, FileFormat.XPS, true) .Filter(FileFormat.SVG, FileFormat.JPEG) .Filter(FileFormat.SVG, FileFormat.PNG) .Filter(FileFormat.SVG, FileFormat.BMP) .Filter(FileFormat.SVG, FileFormat.TIFF, true) .Filter(FileFormat.SVG, FileFormat.GIF) ) .Handler(new MarkdownConversionHandler(), o => o .Filter(FileFormat.MD, FileFormat.PDF, true) .Filter(FileFormat.MD, FileFormat.XPS, true) .Filter(FileFormat.MD, FileFormat.JPEG) .Filter(FileFormat.MD, FileFormat.PNG) .Filter(FileFormat.MD, FileFormat.BMP) .Filter(FileFormat.MD, FileFormat.TIFF, true) .Filter(FileFormat.MD, FileFormat.GIF) .Filter(FileFormat.MD, FileFormat.HTML) ) ); // Merger App Register<MergerApplicationBuilder>(x => x .Handler(new HTMLConversionHandler(), o => o .Filter(FileFormat.HTML, FileFormat.PDF, true) .Filter(FileFormat.HTML, FileFormat.XPS, true) .Filter(FileFormat.HTML, FileFormat.TIFF, true) ) .Handler(new HTMLConversionHandler(), o => o .Filter(FileFormat.XHTML, FileFormat.PDF, true) .Filter(FileFormat.XHTML, FileFormat.XPS, true) .Filter(FileFormat.XHTML, FileFormat.TIFF, true) ) .Handler(new HTMLToMHTMLConversionHandler(), o => o .Filter(FileFormat.HTML, FileFormat.MHTML, true) .Filter(FileFormat.XHTML, FileFormat.MHTML, true) ) .Handler(new MHTMLConversionHandler(), o => o .Filter(FileFormat.MHTML, FileFormat.PDF, true) .Filter(FileFormat.MHTML, FileFormat.XPS, true) .Filter(FileFormat.MHTML, FileFormat.TIFF, true) ) .Handler(new EPUBConversionHandler(), o => o .Filter(FileFormat.EPUB, FileFormat.PDF, true) .Filter(FileFormat.EPUB, FileFormat.XPS, true) .Filter(FileFormat.EPUB, FileFormat.TIFF, true) ) .Handler(new SVGConversionHandler(), o => o .Filter(FileFormat.SVG, FileFormat.PDF, true) .Filter(FileFormat.SVG, FileFormat.XPS, true) .Filter(FileFormat.SVG, FileFormat.TIFF, true) ) .Handler(new MarkdownConversionHandler(), o => o .Filter(FileFormat.MD, FileFormat.PDF, true) .Filter(FileFormat.MD, FileFormat.XPS, true) .Filter(FileFormat.MD, FileFormat.TIFF, true) ).Handler(new SVGMergerHandler(), o => o .Filter(FileFormat.SVG, FileFormat.SVG) )); } public Application Get(ApplicationId id) { return applications[id]; } void Register<T>(Action<T> builder) where T : ApplicationBuilder, new() { var b = new T(); builder(b); var app = b.Build(); this.applications.Add(app.Id, app); } abstract class ApplicationBuilder { public abstract Application Build(); } class ConversionApplicationBuilder : ApplicationBuilder { private IList<ConversionHandler> handlers = new List<ConversionHandler>(); public override Application Build() { return new ConversionApplication(handlers.ToArray()); } public ConversionApplicationBuilder Handler(ConversionHandler handler, Action<ConversionFilterBuilder> options) { var f = new ConversionFilterBuilder(); options(f); f.Build().ForEach(x => handler.Filters.Add(x)); handlers.Add(handler); return this; } } class ConversionFilterBuilder { IList<ConversionHandlerFilter> filters = new List<ConversionHandlerFilter>(); public ConversionFilterBuilder Filter(FileFormat inputFormat, FileFormat outputFormat) { return Filter(inputFormat, outputFormat, false); } public ConversionFilterBuilder Filter(FileFormat inputFormat, FileFormat outputFormat, bool allowMerging) { this.filters.Add(new ConversionHandlerFilter(inputFormat, outputFormat, allowMerging)); return this; } public IList<ConversionHandlerFilter> Build() { return filters; } } class MergerApplicationBuilder : ApplicationBuilder { private IList<ApplicationExecutionHandler> handlers = new List<ApplicationExecutionHandler>(); public override Application Build() { return new MergerApplication(handlers.ToArray()); } public MergerApplicationBuilder Handler(MergerHandler handler, Action<MergerFilterBuilder> options) { var f = new MergerFilterBuilder(); options(f); f.Build().ForEach(x => handler.Filters.Add(x)); handlers.Add(handler); return this; } public MergerApplicationBuilder Handler(ConversionHandler handler, Action<ConversionFilterBuilder> options) { var f = new ConversionFilterBuilder(); options(f); f.Build().ForEach(x => { handler.Filters.Add(x); }); handlers.Add(handler); return this; } } class MergerFilterBuilder { IList<MergerHandlerFilter> filters = new List<MergerHandlerFilter>(); public MergerFilterBuilder Filter(FileFormat inputFormat, FileFormat outputFormat) { this.filters.Add(new MergerHandlerFilter(inputFormat, outputFormat)); return this; } public IList<MergerHandlerFilter> Build() { return filters; } } } }
/* * SVM.NET Library * Copyright (C) 2008 Matthew Johnson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; namespace SVM { /// <summary> /// Class containing the routines to train SVM models. /// </summary> public static class Training { /// <summary> /// Whether the system will output information to the console during the training process. /// </summary> public static bool IsVerbose { get { return Procedures.IsVerbose; } set { Procedures.IsVerbose = value; } } private static double doCrossValidation(Problem problem, Parameter parameters, int nr_fold) { int i; double[] target = new double[problem.Count]; Procedures.svm_cross_validation(problem, parameters, nr_fold, target); int total_correct = 0; double total_error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; if (parameters.SvmType == SvmType.EPSILON_SVR || parameters.SvmType == SvmType.NU_SVR) { for (i = 0; i < problem.Count; i++) { double y = problem.Y[i]; double v = target[i]; total_error += (v - y) * (v - y); sumv += v; sumy += y; sumvv += v * v; sumyy += y * y; sumvy += v * y; } return(problem.Count * sumvy - sumv * sumy) / (Math.Sqrt(problem.Count * sumvv - sumv * sumv) * Math.Sqrt(problem.Count * sumyy - sumy * sumy)); } else for (i = 0; i < problem.Count; i++) if (target[i] == problem.Y[i]) ++total_correct; return (double)total_correct / problem.Count; } public static void SetRandomSeed(int seed) { Procedures.setRandomSeed(seed); } /// <summary> /// Legacy. Allows use as if this was svm_train. See libsvm documentation for details on which arguments to pass. /// </summary> /// <param name="args"></param> [Obsolete("Provided only for legacy compatibility, use the other Train() methods")] public static void Train(params string[] args) { Parameter parameters; Problem problem; bool crossValidation; int nrfold; string modelFilename; parseCommandLine(args, out parameters, out problem, out crossValidation, out nrfold, out modelFilename); if (crossValidation) PerformCrossValidation(problem, parameters, nrfold); else Model.Write(modelFilename, Train(problem, parameters)); } /// <summary> /// Performs cross validation. /// </summary> /// <param name="problem">The training data</param> /// <param name="parameters">The parameters to test</param> /// <param name="nrfold">The number of cross validations to use</param> /// <returns>The cross validation score</returns> public static double PerformCrossValidation(Problem problem, Parameter parameters, int nrfold) { string error = Procedures.svm_check_parameter(problem, parameters); if (error == null) return doCrossValidation(problem, parameters, nrfold); else throw new Exception(error); } /// <summary> /// Trains a model using the provided training data and parameters. /// </summary> /// <param name="problem">The training data</param> /// <param name="parameters">The parameters to use</param> /// <returns>A trained SVM Model</returns> public static Model Train(Problem problem, Parameter parameters) { string error = Procedures.svm_check_parameter(problem, parameters); if (error == null) return Procedures.svm_train(problem, parameters); else throw new Exception(error); } private static void parseCommandLine(string[] args, out Parameter parameters, out Problem problem, out bool crossValidation, out int nrfold, out string modelFilename) { int i; parameters = new Parameter(); // default values crossValidation = false; nrfold = 0; // parse options for (i = 0; i < args.Length; i++) { if (args[i][0] != '-') break; ++i; switch (args[i - 1][1]) { case 's': parameters.SvmType = (SvmType)int.Parse(args[i]); break; case 't': parameters.KernelType = (KernelType)int.Parse(args[i]); break; case 'd': parameters.Degree = int.Parse(args[i]); break; case 'g': parameters.Gamma = double.Parse(args[i]); break; case 'r': parameters.Coefficient0 = double.Parse(args[i]); break; case 'n': parameters.Nu = double.Parse(args[i]); break; case 'm': parameters.CacheSize = double.Parse(args[i]); break; case 'c': parameters.C = double.Parse(args[i]); break; case 'e': parameters.EPS = double.Parse(args[i]); break; case 'p': parameters.P = double.Parse(args[i]); break; case 'h': parameters.Shrinking = int.Parse(args[i]) == 1; break; case 'b': parameters.Probability = int.Parse(args[i]) == 1; break; case 'v': crossValidation = true; nrfold = int.Parse(args[i]); if (nrfold < 2) { throw new ArgumentException("n-fold cross validation: n must >= 2"); } break; case 'w': parameters.Weights[int.Parse(args[i - 1].Substring(2))] = double.Parse(args[1]); break; default: throw new ArgumentException("Unknown Parameter"); } } // determine filenames if (i >= args.Length) throw new ArgumentException("No input file specified"); problem = Problem.Read(args[i]); if (parameters.Gamma == 0) parameters.Gamma = 1.0 / problem.MaxIndex; if (i < args.Length - 1) modelFilename = args[i + 1]; else { int p = args[i].LastIndexOf('/') + 1; modelFilename = args[i].Substring(p) + ".model"; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; namespace Keen.Core { public static class KeenUtil { private static readonly string SdkVersion; static KeenUtil() { string version = GetAssemblyInformationalVersion(); version = (string.IsNullOrWhiteSpace(version) ? "0.0.0" : version); SdkVersion = string.Format(".net-{0}", version); } /// <summary> /// Retrieve a string representing the current version of the Keen IO SDK, as defined by /// the AssemblyInformationalVersion. /// </summary> /// <returns>The SDK version string.</returns> public static string GetSdkVersion() { return SdkVersion; } private static string GetAssemblyInformationalVersion() { string assemblyInformationalVersion = string.Empty; AssemblyInformationalVersionAttribute attribute = null; try { attribute = (AssemblyInformationalVersionAttribute)(typeof(KeenUtil).Assembly .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) .FirstOrDefault()); } catch (Exception e) { Debug.WriteLine("Caught exception trying to read AssemblyInformationalVersion: {0}", e); } if (null != attribute) { assemblyInformationalVersion = attribute.InformationalVersion; } return assemblyInformationalVersion; } private static HashSet<string> validCollectionNames = new HashSet<string>(); public static string ToSafeString(this object obj) { return (obj ?? string.Empty).ToString(); } /// <summary> /// Apply property name restrictions. Throws KeenException with an /// explanation if a collection name is unacceptable. /// </summary> /// <param name="property"></param> public static void ValidatePropertyName(string property) { if (string.IsNullOrWhiteSpace(property)) throw new KeenException("Property name may not be null or whitespace"); if (property.Length >= 256) throw new KeenException("Property name must be less than 256 characters"); if (property.StartsWith("$")) throw new KeenException("Property name may not start with \"$\""); if (property.Contains(".")) throw new KeenException("Property name may not contain \".\""); } /// <summary> /// Apply the collection name restrictions. Throws KeenException with an /// explanation if a collection name is unacceptable. /// </summary> /// <param name="collection"></param> public static void ValidateEventCollectionName(string collection) { // Avoid cost of re-checking collection names that have already been validated. // There is a race condition here, but it's harmless and does not justify the // overhead of synchronization. if (validCollectionNames.Contains(collection)) return; if (null == collection) throw new KeenException("Event collection name may not be null."); if (string.IsNullOrWhiteSpace(collection)) throw new KeenException("Event collection name may not be blank."); if (collection.Length > 64) throw new KeenException("Event collection name may not be longer than 64 characters."); if (new Regex("[^\x00-\x7F]").Match(collection).Success) throw new KeenException("Event collection name must contain only Ascii characters."); if (collection.Contains("$")) throw new KeenException("Event collection name may not contain \"$\"."); if (collection.StartsWith("_")) throw new KeenException("Event collection name may not begin with \"_\"."); validCollectionNames.Add(collection); } /// <summary> /// Check the 'error' field on a bulk insert operation response and return /// the appropriate exception. /// </summary> /// <param name="apiResponse">Deserialized json response from a Keen API call.</param> public static Exception GetBulkApiError(JObject apiResponse) { var error = apiResponse.SelectToken("$.error"); if (null == error) return null; var errCode = error.SelectToken("$.name").ToString(); var message = error.SelectToken("$.description").ToString(); switch (errCode) { case "InvalidApiKeyError": return new KeenInvalidApiKeyException(message); case "ResourceNotFoundError": return new KeenResourceNotFoundException(message); case "NamespaceTypeError": return new KeenNamespaceTypeException(message); case "InvalidEventError": return new KeenInvalidEventException(message); case "ListsOfNonPrimitivesNotAllowedError": return new KeenListsOfNonPrimitivesNotAllowedException(message); case "InvalidBatchError": return new KeenInvalidBatchException(message); case "InternalServerError": return new KeenInternalServerErrorException(message); case "InvalidKeenNamespaceProperty": return new KeenInvalidKeenNamespacePropertyException(message); case "InvalidPropertyNameError": return new KeenInvalidPropertyNameException(message); default: Debug.WriteLine("Unhandled error_code \"{0}\" : \"{1}\"", errCode, message); return new KeenException(errCode + " : " + message); } } /// <summary> /// Check the 'error_code' field and throw the appropriate exception if non-null. /// </summary> /// <param name="apiResponse">Deserialized json response from a Keen API call.</param> public static void CheckApiErrorCode(dynamic apiResponse) { if (apiResponse is JArray) return; var errorCode = (string)apiResponse.SelectToken("$.error_code"); if (errorCode != null) { var message = (string)apiResponse.SelectToken("$.message"); switch (errorCode) { case "InvalidApiKeyError": throw new KeenInvalidApiKeyException(message); case "ResourceNotFoundError": throw new KeenResourceNotFoundException(message); case "NamespaceTypeError": throw new KeenNamespaceTypeException(message); case "InvalidEventError": throw new KeenInvalidEventException(message); case "ListsOfNonPrimitivesNotAllowedError": throw new KeenListsOfNonPrimitivesNotAllowedException(message); case "InvalidBatchError": throw new KeenInvalidBatchException(message); case "InternalServerError": throw new KeenInternalServerErrorException(message); case "InvalidKeenNamespaceProperty": throw new KeenInvalidKeenNamespacePropertyException(message); default: Debug.WriteLine("Unhandled error_code \"{0}\" : \"{1}\"", errorCode, message); throw new KeenException(errorCode + " : " + message); } } } /// <summary> /// Flatten an AggregateException and if only one exception instance is found /// in the innerexceptions, return it, otherwise return the original /// AggregateException unchanged. /// </summary> /// <param name="ex"></param> /// <returns></returns> internal static Exception TryUnwrap(this AggregateException ex) { if (ex.Flatten().InnerExceptions.Count == 1) return ex.Flatten().InnerExceptions[0]; else return ex; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Serialization; using Fairweather.Service; using Versioning; namespace Common { [global::System.Serializable] public class XSage_Conn : XSage { const string STR_User = "user"; const string STR_Workstation = "workstation"; const string STR_dataset = "dataset"; public XSage_Conn() { } public XSage_Conn(string message) : base(message) { } public XSage_Conn(Sage_Connection_Error error) : base() { this.Connection_Error = error; } public XSage_Conn(string message, Sage_Connection_Error error) : base(message) { this.Connection_Error = error; } public XSage_Conn(COMException comex, Sage_Error error) : base(comex, error) { Connection_Error = errors.Get_Or_Default_(error, (Sage_Connection_Error)0); if (Connection_Error == 0) Connection_Error = Get_From_Message(Message.ToUpper()); } static Sage_Connection_Error Get_From_Message(string trouble) { return (from kvp in messages where trouble.Contains(kvp.Key) select kvp.Value).FirstOrDefault(Sage_Connection_Error.Unspecified); } protected XSage_Conn(SerializationInfo info, StreamingContext context) : base(info, context) { } // **************************** public bool Friendly_Message(out string msg, out bool retry) { H.assign(out msg, out retry); var user = User; if (user.IsNullOrEmpty()) return false; var workstation = Workstation; var on_machine = ""; // if not nullorempty - has leading space and no trailing space if (!workstation.IsNullOrEmpty()) { var same = workstation.ToUpper() == Environment.MachineName.ToUpper(); on_machine = same ? " on your machine" : " on machine '" + Workstation + "'"; } if (this.Connection_Error == Sage_Connection_Error.Username_In_Use_Cant_Remove) { msg = //* "Sage indicates that the username which {1} uses" + " to connect to the data is currently active{2}." + "\n\nPlease make sure that the user '{0}' is logged out before proceeding."; msg = msg.spf(user, Common.Data.App_Name, on_machine); /*/ "User '{0}' is currently logged in{1}.\n\nLogin cannot proceed."; msg = msg.spf(user, on_machine); //*/ } else if (this.Connection_Error == Sage_Connection_Error.Exclusive_Mode) { msg = "Sage indicates that the data set is currently being used in exclusive mode{0}." + "\n\nPlease resolve this before proceeding."; msg = msg.spf(on_machine); } else { return false; } retry = true; return true; } public Sage_Connection_Error Connection_Error { get; set; } string Maybe_Get(string key) { var data = Data; if (data == null) return null; if (!data.Contains(key)) return null; return data[key].strdef(null); } public string Dataset { get { return Maybe_Get(STR_dataset); } set { Data[STR_dataset] = value; } } public string User { get { return Maybe_Get(STR_User); } set { Data[STR_User] = value; } } public string Workstation { get { return Maybe_Get(STR_Workstation); } set { Data[STR_Workstation] = value; } } // **************************** static readonly Dictionary<Sage_Error, Sage_Connection_Error> errors = new Dictionary<Sage_Error, Sage_Connection_Error> { #region {Sage_Error.sdoLogonPassword, Sage_Connection_Error.Invalid_Credentials}, {Sage_Error.sdoBadDataPath, Sage_Connection_Error.Invalid_Folder}, {Sage_Error.sdoLogonNameInUse, Sage_Connection_Error.Username_In_Use_Generic}, {Sage_Error.sdoLogonExclusive, Sage_Connection_Error.Exclusive_Mode}, {Sage_Error.sdoNotRegistered, Sage_Connection_Error.SDO_Not_Registered}, #endregion }; /// TODO: Have a look at the actual error codes static readonly Dictionary<string, Sage_Connection_Error> messages = new Dictionary<string, Sage_Connection_Error> { #region {"INVALID OR INCORRECT USERNAME OR PASSWORD", Sage_Connection_Error.Invalid_Credentials}, {"THE CREDENTIALS YOU HAVE ENTERED APPEAR TO BE INVALID", Sage_Connection_Error.Invalid_Credentials}, {"USERNAME IS ALREADY IN USE", Sage_Connection_Error.Username_In_Use_Generic}, {"EXCLUSIVE MODE", Sage_Connection_Error.Exclusive_Mode}, {"SAGE DATA OBJECTS IS NOT REGISTERED.", Sage_Connection_Error.SDO_Not_Registered}, #endregion }; public override string ToString() { var ret = base.ToString() + "\r\n" + "Connection_Error: " + Connection_Error.ToString(); return ret; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** ** Purpose: Centralized error methods for the IO package. ** Mostly useful for translating Win32 HRESULTs into meaningful ** error strings & exceptions. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; using Win32Native = Microsoft.Win32.Win32Native; using System.Text; using System.Globalization; using System.Security; using System.Security.Permissions; using System.Diagnostics.Contracts; namespace System.IO { [Pure] internal static class __Error { internal static void EndOfFile() { throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF")); } internal static void FileNotOpen() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed")); } internal static void StreamIsClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); } internal static void MemoryStreamNotExpandable() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable")); } internal static void ReaderClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed")); } internal static void ReadNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); } internal static void SeekNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); } internal static void WrongAsyncResult() { throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult")); } internal static void EndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndReadCalledMultiple")); } internal static void EndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndWriteCalledMultiple")); } // Given a possible fully qualified path, ensure that we have path // discovery permission to that path. If we do not, return just the // file name. If we know it is a directory, then don't return the // directory name. [System.Security.SecurityCritical] // auto-generated internal static String GetDisplayablePath(String path, bool isInvalidPath) { if (String.IsNullOrEmpty(path)) return String.Empty; // Is it a fully qualified path? bool isFullyQualified = false; if (path.Length < 2) return path; if (Path.IsDirectorySeparator(path[0]) && Path.IsDirectorySeparator(path[1])) isFullyQualified = true; else if (path[1] == Path.VolumeSeparatorChar) { isFullyQualified = true; } if (!isFullyQualified && !isInvalidPath) return path; bool safeToReturn = false; try { if (!isInvalidPath) { #if !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false).Demand(); #endif safeToReturn = true; } } catch (SecurityException) { } catch (ArgumentException) { // ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters // inside FileIOPermission.AddPathList } catch (NotSupportedException) { // paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown // from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path // beyond string index position 1. } if (!safeToReturn) { if (Path.IsDirectorySeparator(path[path.Length - 1])) path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName"); else path = Path.GetFileName(path); } return path; } [System.Security.SecuritySafeCritical] // auto-generated internal static void WinIOError() { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, String.Empty); } // After calling GetLastWin32Error(), it clears the last error field, // so you must save the HResult and pass it to this method. This method // will determine the appropriate exception to throw dependent on your // error, and depending on the error, insert a string into the message // gotten from the ResourceManager. [System.Security.SecurityCritical] // auto-generated internal static void WinIOError(int errorCode, String maybeFullPath) { // This doesn't have to be perfect, but is a perf optimization. bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME; String str = GetDisplayablePath(maybeFullPath, isInvalidPath); switch (errorCode) { case Win32Native.ERROR_FILE_NOT_FOUND: if (str.Length == 0) throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound")); else throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str); case Win32Native.ERROR_PATH_NOT_FOUND: if (str.Length == 0) throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName")); else throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str)); case Win32Native.ERROR_ACCESS_DENIED: if (str.Length == 0) throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName")); else throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str)); case Win32Native.ERROR_ALREADY_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILENAME_EXCED_RANGE: throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); case Win32Native.ERROR_INVALID_DRIVE: throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str)); case Win32Native.ERROR_INVALID_PARAMETER: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_SHARING_VIOLATION: if (str.Length == 0) throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); else throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILE_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_OPERATION_ABORTED: throw new OperationCanceledException(); default: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); } } // An alternative to WinIOError with friendlier messages for drives [System.Security.SecuritySafeCritical] // auto-generated internal static void WinIODriveError(String driveName) { int errorCode = Marshal.GetLastWin32Error(); WinIODriveError(driveName, errorCode); } [System.Security.SecurityCritical] // auto-generated internal static void WinIODriveError(String driveName, int errorCode) { switch (errorCode) { case Win32Native.ERROR_PATH_NOT_FOUND: case Win32Native.ERROR_INVALID_DRIVE: throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", driveName)); default: WinIOError(errorCode, driveName); break; } } internal static void WriteNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); } internal static void WriterClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_WriterClosed")); } // From WinError.h internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND; internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND; internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED; internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER; } }
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Windows.Input; using Microsoft.VisualStudio.TestTools.UnitTesting; using MVVMBase; using MVVMBase.Extensions; namespace MVVMBaseUnitTest { [TestClass] public class MVVMBaseTest { [TestMethod] public void MyPropertyTest() { var myClass = new ModelClass(); myClass.PropertyChanged += (se, ev) => { Assert.AreEqual(ev.PropertyName, "MyProperty"); }; myClass.MyProperty = "string"; Thread.Sleep(1000); Assert.AreEqual(myClass.MyProperty, "string"); } [TestMethod] public void MyPropertyByMemberNameTest() { var myClass = new ModelClass(); myClass.PropertyChanged += (se, ev) => { Assert.AreEqual(ev.PropertyName, "MyPropertyByMemberName"); }; myClass.MyPropertyByMemberName = "string"; Thread.Sleep(1000); Assert.AreEqual(myClass.MyPropertyByMemberName, "string"); } [TestMethod] public void MyPropertyByNameTest() { var myClass = new ModelClass(); myClass.PropertyChanged += (se, ev) => { Assert.AreEqual(ev.PropertyName, "MyPropertyByName"); }; myClass.MyPropertyByName = "string"; Thread.Sleep(1000); Assert.AreEqual(myClass.MyPropertyByName, "string"); } [TestMethod] public void MyPropertyAutoChangeTest() { var myClass = new ModelClass(); myClass.PropertyChanged += (se, ev) => { Assert.AreEqual(ev.PropertyName, "MyPropertyAutoChange"); }; myClass.MyPropertyAutoChange = "string"; Thread.Sleep(1000); Assert.AreEqual(myClass.MyPropertyAutoChange, "string"); } [TestMethod] public void MyPropertyAutoGetSetTest() { var myClass = new ModelClass(); myClass.PropertyChanged += (se, ev) => { Assert.AreEqual(ev.PropertyName, "MyPropertyAutoGetSet"); }; myClass.MyPropertyAutoGetSet = "string"; Thread.Sleep(1000); Assert.AreEqual(myClass.MyPropertyAutoGetSet, "string"); } [TestMethod] public void MyCommandTest() { var myClass = new ModelClass(); myClass.MyCommandProperty = "1"; Assert.AreEqual(myClass.MyCommand.CanExecute(null), true); myClass.MyCommand.Execute("1"); Assert.AreEqual(myClass.MyPropertyByName, "1"); myClass.MyCommandProperty = "2"; Assert.AreEqual(myClass.MyCommand.CanExecute(null), false); myClass.MyCommand.Execute("2"); Assert.AreEqual(myClass.MyPropertyByName, "2"); myClass.MyCommandProperty = "1"; myClass.MyCommand.Run("3"); Assert.AreEqual(myClass.MyPropertyByName, "3"); myClass.MyCommandProperty = "2"; myClass.MyCommand.Run("4"); Assert.AreEqual(myClass.MyPropertyByName, "3"); } [TestMethod] public void MyAsyncCommandTest() { var myClass = new ModelClass(); myClass.MyCommandProperty = "1"; Assert.AreEqual(myClass.MyAsyncCommand.CanExecute(null), true); myClass.MyCommand.Execute("1"); Assert.AreEqual(myClass.MyPropertyByName, "1"); myClass.MyCommandProperty = "2"; Assert.AreEqual(myClass.MyAsyncCommand.CanExecute(null), false); myClass.MyCommand.Execute("2"); Assert.AreEqual(myClass.MyPropertyByName, "2"); myClass.MyCommandProperty = "1"; myClass.MyCommand.Run("3"); Assert.AreEqual(myClass.MyPropertyByName, "3"); myClass.MyCommandProperty = "2"; myClass.MyCommand.Run("4"); Assert.AreEqual(myClass.MyPropertyByName, "3"); } [TestMethod] public void AllOnPropertyChanged() { var myClass = new ModelClass(); int count = 0; myClass.PropertyChanged += (se, ev) => Interlocked.Increment(ref count); myClass.UpdateAll(); Thread.Sleep(1000); Assert.AreEqual(count, 8); // 5 properties and 3 commands } [TestMethod] public void ChangedObjectNotifyPropertyChangeTest() { var myClass = new BindClass(); List<string> propertyList = new List<string>(); myClass.PropertyChanged += (se, ev) => {propertyList.Add(ev.PropertyName);}; myClass.ChangedObjectNotifyPropertyChange(nameof(myClass.MyProperty), nameof(myClass.MyCommand)); myClass.ChangedObjectNotifyPropertyChange(() => myClass.MyCommand, nameof(myClass.MyPropertyByName)); myClass.MyProperty = "string"; Thread.Sleep(1000); Assert.AreEqual(propertyList.Count,3); } [TestMethod] public void DependsToTest() { var myClass = new BindClass(); List<string> propertyList = new List<string>(); myClass.PropertyChanged += (se, ev) => { propertyList.Add(ev.PropertyName); }; myClass.ChangedObject(nameof(myClass.MyProperty)).Notify(nameof(myClass.MyCommand)); myClass.ChangedObject(() => myClass.MyCommand).Notify(()=> myClass.MyPropertyByName); myClass.MyProperty = "string"; Thread.Sleep(1000); Assert.AreEqual(propertyList.Count, 3); } [TestMethod] public void NotifyToTest() { var myClass = new BindClass(); List<string> propertyList = new List<string>(); myClass.PropertyChanged += (se, ev) => { propertyList.Add(ev.PropertyName); }; myClass.ChangedObject(nameof(myClass.MyProperty)).Notify(nameof(myClass.MyCommand)); myClass.ChangedObject(() => myClass.MyCommand).Notify(() => myClass.MyPropertyByName); myClass.MyProperty = "string"; Thread.Sleep(1000); Assert.AreEqual(propertyList.Count, 3); } [TestMethod] public void DependOnAttributeTest() { var myClass = new BindClass(); List<string> propertyList = new List<string>(); myClass.PropertyChanged += (se, ev) => { propertyList.Add(ev.PropertyName); }; myClass.MyPropertyIntAutoGetSet = 10; Assert.AreEqual(propertyList.Count, 2); Assert.AreEqual(myClass.MyDependedPropertyInt, myClass.MyPropertyIntAutoGetSet * myClass.MyPropertyIntAutoGetSet); } [TestMethod] public void ObservableTest() { var myClass = new BindClass(); List<string> propertyList = new List<string>(); myClass.PropertyChanged += (se, ev) => { propertyList.Add(ev.PropertyName); }; myClass.MyObservableProperty = new ObservableCollection<int>(); myClass.MyObservableProperty.Add(1); myClass.MyObservableProperty.Add(2); Assert.AreEqual(propertyList.Count, 6); Assert.AreEqual(myClass.MyObservablePropertyCount, myClass.MyObservableProperty.Sum()); } } }
// // Copyright (c) 2004-2017 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 System.Globalization; namespace NLog.LayoutRenderers { using System; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Render environmental information related to logging events. /// </summary> [NLogConfigurationItem] public abstract class LayoutRenderer : ISupportsInitialize, IRenderable, IDisposable { private const int MaxInitialRenderBufferLength = 16384; private int _maxRenderedLength; private bool _isInitialized; /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var lra = (LayoutRendererAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(LayoutRendererAttribute)); if (lra != null) { return "Layout Renderer: ${" + lra.Name + "}"; } return this.GetType().Name; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Renders the the value of layout renderer in the context of the specified log event. /// </summary> /// <param name="logEvent">The log event.</param> /// <returns>String representation of a layout renderer.</returns> public string Render(LogEventInfo logEvent) { int initialLength = this._maxRenderedLength; if (initialLength > MaxInitialRenderBufferLength) { initialLength = MaxInitialRenderBufferLength; } var builder = new StringBuilder(initialLength); this.RenderAppendBuilder(logEvent, builder); if (builder.Length > this._maxRenderedLength) { this._maxRenderedLength = builder.Length; } return builder.ToString(); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { this.Initialize(configuration); } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { this.Close(); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { if (this.LoggingConfiguration == null) this.LoggingConfiguration = configuration; if (!this._isInitialized) { this._isInitialized = true; this.InitializeLayoutRenderer(); } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { if (this._isInitialized) { this.LoggingConfiguration = null; this._isInitialized = false; this.CloseLayoutRenderer(); } } /// <summary> /// Renders the the value of layout renderer in the context of the specified log event. /// </summary> /// <param name="logEvent">The log event.</param> /// <param name="builder">The layout render output is appended to builder</param> internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder) { if (!this._isInitialized) { this._isInitialized = true; this.InitializeLayoutRenderer(); } try { this.Append(builder, logEvent); } catch (Exception exception) { InternalLogger.Warn(exception, "Exception in layout renderer."); if (exception.MustBeRethrown()) { throw; } } } /// <summary> /// Renders the specified environmental information and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected abstract void Append(StringBuilder builder, LogEventInfo logEvent); /// <summary> /// Initializes the layout renderer. /// </summary> protected virtual void InitializeLayoutRenderer() { } /// <summary> /// Closes the layout renderer. /// </summary> protected virtual void CloseLayoutRenderer() { } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { this.Close(); } } /// <summary> /// Get the <see cref="IFormatProvider"/> for rendering the messages to a <see cref="string"/> /// </summary> /// <param name="logEvent">LogEvent with culture</param> /// <param name="layoutCulture">Culture in on Layout level</param> /// <returns></returns> protected IFormatProvider GetFormatProvider(LogEventInfo logEvent, IFormatProvider layoutCulture = null) { var culture = logEvent.FormatProvider; if (culture == null) { culture = layoutCulture; } if (culture == null && this.LoggingConfiguration != null) { culture = this.LoggingConfiguration.DefaultCultureInfo; } return culture; } /// <summary> /// Get the <see cref="CultureInfo"/> for rendering the messages to a <see cref="string"/>, needed for date and number formats /// </summary> /// <param name="logEvent">LogEvent with culture</param> /// <param name="layoutCulture">Culture in on Layout level</param> /// <returns></returns> /// <remarks> /// <see cref="GetFormatProvider"/> is preferred /// </remarks> protected CultureInfo GetCulture(LogEventInfo logEvent, CultureInfo layoutCulture = null) { var culture = logEvent.FormatProvider as CultureInfo; if (culture == null) { culture = layoutCulture; } if (culture == null && this.LoggingConfiguration != null) { culture = this.LoggingConfiguration.DefaultCultureInfo; } return culture; } /// <summary> /// Register a custom layout renderer. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T"> Type of the layout renderer.</typeparam> /// <param name="name"> Name of the layout renderer - without ${}.</param> public static void Register<T>(string name) where T: LayoutRenderer { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom layout renderer. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="layoutRendererType"> Type of the layout renderer.</param> /// <param name="name"> Name of the layout renderer - without ${}.</param> public static void Register(string name, Type layoutRendererType) { ConfigurationItemFactory.Default.LayoutRenderers .RegisterDefinition(name, layoutRendererType); } /// <summary> /// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback recieves the logEvent. /// </summary> /// <param name="name">Name of the layout renderer - without ${}.</param> /// <param name="func">Callback that returns the value for the layout renderer.</param> public static void Register(string name, Func<LogEventInfo, object> func) { Register(name, (info, configuration) => func(info)); } /// <summary> /// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback recieves the logEvent and the current configuration. /// </summary> /// <param name="name">Name of the layout renderer - without ${}.</param> /// <param name="func">Callback that returns the value for the layout renderer.</param> public static void Register(string name, Func<LogEventInfo, LoggingConfiguration, object> func) { var layoutRenderer = new FuncLayoutRenderer(name, func); ConfigurationItemFactory.Default.GetLayoutRenderers().RegisterFuncLayout(name, layoutRenderer); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Common.Collections; using Gallio.Common; using Gallio.Common.Reflection; using Gallio.Properties; namespace Gallio.Model.Tree { /// <summary> /// A test object represents a parameterized test case or test /// container. The test parameters are used as placeholders for /// data-binding during test execution. A single test can /// produce multiple steps (<seealso cref="TestStep" />) at runtime. /// </summary> /// <remarks> /// <para> /// A <see cref="Test" /> can be thought of as a declarative /// artifact that describes about what a test "looks like" /// from the outside based on available reflective metadata. /// A <see cref="TestStep" /> is then the runtime counterpart of a /// <see cref="Test" /> that is created to describe different /// parameter bindigns or other characteristics of a test's structure /// that become manifest only at runtime. /// </para> /// <para> /// A test may depend on one or more other tests. When a test /// fails, the tests that depend on it are also automatically /// considered failures. Moreover, the test harness ensures /// that a test will only run once all of its dependencies have /// completed execution successfully. A run-time error will /// occur when the system detects the presence of circular test dependencies /// or attempts to execute a test concurrently with its dependencies. /// </para> /// <para> /// A test contain child tests. The children of a test are executed /// in dependency order within the scope of the parent test. Thus the parent /// test may setup/teardown the execution environment used to execute /// its children. Tests that belong to different subtrees are executed in /// relative isolation within the common environment established by their common parent. /// </para> /// <para> /// The object model distinguishes between tests that represent individual test cases /// and other test containers. Test containers are skipped if they do not /// contain any test cases or if none of their test cases have been selected for execution. /// </para> /// <para> /// The kind of type type of test is set to <see cref="TestKinds.Group" /> by default. /// </para> /// </remarks> public class Test : TestComponent { private List<TestParameter> parameters; private List<Test> children; private List<Test> dependencies; private HashSet<string> assignedChildLocalIds; private Test parent; private bool isTestCase; private int order; private string id; private string cachedId; private string cachedLocalId; private string localIdHint; /// <summary> /// Initializes a test initially without a parent. /// </summary> /// <param name="name">The name of the test.</param> /// <param name="codeElement">The point of definition of the test, or null if unknown.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> is null.</exception> public Test(string name, ICodeElementInfo codeElement) : base(name, codeElement) { Kind = TestKinds.Group; } /// <inheritdoc /> public override string Id { get { if (id != null) return id; // We compute an id using the combined hash of the local ids // from this test up the tree to the root. A hash is used to // keep the ids relatively short and to prevent people from // making undue assumptions about the internal structure of an id. if (cachedId == null) { Hash64 hash = new Hash64(); hash = hash.Add(LocalId); for (Test ancestor = parent; ancestor != null; ancestor = ancestor.Parent) hash = hash.Add(ancestor.LocalId); cachedId = hash.ToString(); } return cachedId; } set { if (value == null) throw new ArgumentNullException("value"); id = value; } } /// <summary> /// Gets or sets a suggested <see cref="LocalId" /> hint, or null if none. /// </summary> /// <remarks> /// <para> /// The value returned by this method will be checked for uniqueness and amended as necessary /// to produce a truly unique <see cref="LocalId" />. /// </para> /// </remarks> /// <value> /// The default value of this property is <c>null</c> which causes the <see cref="TestComponent.Name" /> /// property to be used as the local id hint. /// </value> /// <returns>The local id hint.</returns> public string LocalIdHint { get { return localIdHint; } set { localIdHint = value; } } /// <summary> /// Gets the full name of the test. The full name is derived by concatenating the /// <see cref="FullName" /> of the <see cref="Parent"/> followed by a slash ('/') /// followed by the <see cref="TestComponent.Name" /> of this test. /// </summary> /// <remarks> /// <para> /// The full name of the root test is empty. /// </para> /// </remarks> public string FullName { get { if (parent == null) return @""; if (parent.Parent == null) return Name; return String.Concat(parent.FullName, "/", Name); } } /// <summary> /// Gets or sets the parent of this test, or null if this is the root test. /// </summary> public Test Parent { get { return parent; } set { parent = value; cachedId = null; cachedLocalId = null; } } /// <summary> /// Gets a locally unique identifier for this test that satisfies the following conditions: /// </summary> /// <remarks> /// <para> /// <list type="bullet"> /// <item>The identifier is unique among all siblings of this test belonging to the same parent.</item> /// <item>The identifier is likely to be stable across multiple sessions including /// changes and recompilations of the test projects.</item> /// <item>The identifier is non-null.</item> /// </list> /// </para> /// <para> /// The local identifier may be the same as the test's name. However since the name is /// intended for display to end-users, it may contain irrelevant details (such as version /// numbers) that would reduce its long-term stability. In that case, a different /// local identifier should be selected such as one based on the test's /// <see cref="TestComponent.CodeElement" /> and an ordering condition among siblings /// to guarantee uniqueness. /// </para> /// <para> /// The locally unique <see cref="LocalId" /> property may be used to generate the /// globally unique <see cref="TestComponent.Id" /> property of a test by combining /// it with the locally unique identifiers of its parents. /// </para> /// </remarks> /// <returns>The locally unique identifier.</returns> public string LocalId { get { if (cachedLocalId == null) { string resolvedLocalIdHint = localIdHint ?? Name; if (parent != null) cachedLocalId = parent.GetUniqueLocalIdForChild(resolvedLocalIdHint); else cachedLocalId = resolvedLocalIdHint; } return cachedLocalId; } } /// <summary> /// Gets whether this test represents an individual test case /// as opposed to a test container such as a fixture or suite. /// </summary> /// <remarks> /// <para> /// The value of this property can be used by the test harness to avoid processing /// containers that have no test cases. It can also be used by the reporting infrastructure /// to constrain output statistics to test cases only. /// </para> /// <para> /// Not all test cases are leaf nodes in the test tree and vice-versa. /// </para> /// <para> /// This value is defined as a property rather than as a metadata key because it /// significantly changes the semantics of test execution. /// </para> /// </remarks> public bool IsTestCase { get { return isTestCase; } set { isTestCase = value; } } /// <summary> /// Gets a read-only list of the parameters of this test. /// </summary> /// <remarks> /// <para> /// Each parameter must have a unique name. /// </para> /// <para> /// The order in which the parameters appear is not significant. /// </para> /// </remarks> public IList<TestParameter> Parameters { get { return parameters != null ? (IList<TestParameter>) parameters.AsReadOnly() : EmptyArray<TestParameter>.Instance; } } /// <summary> /// Gets a read-only list of the children of this test. /// </summary> public IList<Test> Children { get { return children != null ? (IList<Test>) children.AsReadOnly() : EmptyArray<Test>.Instance; } } /// <summary> /// Gets a read-only list of the dependencies of this test. /// </summary> /// <remarks> /// <para> /// Some test frameworks may choose to ignore test dependencies or may impose their own dependency schemes. /// </para> /// </remarks> public IList<Test> Dependencies { get { return dependencies != null ? (IList<Test>) dependencies.AsReadOnly() : EmptyArray<Test>.Instance; } } /// <summary> /// Gets or sets a number that defines an ordering for the test with respect to its siblings. /// </summary> /// <remarks> /// <para> /// Unless compelled otherwise by test dependencies, tests with a lower order number than /// their siblings will run before those siblings and tests with the same order number /// as their siblings with run in an arbitrary sequence with respect to those siblings. /// </para> /// <para> /// Some test frameworks may choose to ignore test order or may impose their own ordering schemes. /// </para> /// </remarks> /// <value>The test execution order with respect to siblings, initially zero.</value> public int Order { get { return order; } set { order = value; } } /// <summary> /// Clears the list of test parameters. /// </summary> public void ClearParameters() { GenericCollectionUtils.ForEach(Parameters, x => x.Owner = null); parameters = null; } /// <summary> /// Adds a test parameter and sets its <see cref="TestParameter.Owner" /> property. /// </summary> /// <param name="parameter">The test parameter to add.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="parameter"/> is null.</exception> /// <exception cref="InvalidOperationException">Thrown if <paramref name="parameter"/> is already /// owned by some other test.</exception> public void AddParameter(TestParameter parameter) { if (parameter == null) throw new ArgumentNullException("parameter"); if (parameter.Owner != null) throw new InvalidOperationException("The test parameter to be added is already owned by another test."); parameter.Owner = this; if (parameters == null) parameters = new List<TestParameter>(); parameters.Add(parameter); } /// <summary> /// Removes a test parameter and resets its <see cref="TestParameter.Owner" /> property. /// </summary> /// <param name="parameter">The test parameter to remove.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="parameter"/> is null.</exception> /// <exception cref="InvalidOperationException">Thrown if <paramref name="parameter"/> is not owned by this test.</exception> public void RemoveParameter(TestParameter parameter) { if (parameter == null) throw new ArgumentNullException("parameter"); if (parameter.Owner != this || parameters == null || ! parameters.Contains(parameter)) throw new InvalidOperationException("The test parameter to be removed is not owned by this test."); parameters.Remove(parameter); parameter.Owner = null; } /// <summary> /// Clears the list of children. /// </summary> public void ClearChildren() { GenericCollectionUtils.ForEach(Children, x => x.Parent = null); children = null; } /// <summary> /// Adds a child test and sets its <see cref="Test.Parent" /> property. /// </summary> /// <param name="test">The test to add as a child.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="test"/> is null.</exception> /// <exception cref="InvalidOperationException">Thrown if <paramref name="test"/> is already /// the child of some other test.</exception> public void AddChild(Test test) { if (test == null) throw new ArgumentNullException("test"); if (test.Parent != null) throw new InvalidOperationException(Resources.BaseTest_TestAlreadyHasAParent); test.Parent = this; if (children == null) children = new List<Test>(); children.Add(test); } /// <summary> /// Removes a child test and resets its <see cref="Test.Parent" /> property. /// </summary> /// <param name="test">The child test to remove.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="test"/> is null.</exception> /// <exception cref="InvalidOperationException">Thrown if <paramref name="test"/> is not a child of this test.</exception> public void RemoveChild(Test test) { if (test == null) throw new ArgumentNullException("test"); if (test.Parent != this || children == null || ! children.Contains(test)) throw new InvalidOperationException("The test to be removed is not a child of this test."); children.Remove(test); test.Parent = null; } /// <summary> /// Clears the list of dependencies. /// </summary> public void ClearDependencies() { dependencies = null; } /// <summary> /// Adds a test dependency. /// </summary> /// <param name="test">The test to add as a dependency.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="test"/> is null.</exception> public void AddDependency(Test test) { if (test == null) throw new ArgumentNullException("test"); if (dependencies == null) dependencies = new List<Test>(); if (! dependencies.Contains(test)) dependencies.Add(test); } /// <summary> /// Removes a test dependency. /// </summary> /// <param name="test">The test to remove as a dependency.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="test"/> is null.</exception> public void RemoveDependency(Test test) { if (test == null) throw new ArgumentNullException("test"); if (dependencies != null) dependencies.Remove(test); } /// <summary> /// Obtains a unique local id for a child of this test. /// </summary> /// <param name="localIdHint">A suggested id which will be used if no conflicts occur.</param> /// <returns>The unique local id to use.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="localIdHint"/> is null.</exception> public string GetUniqueLocalIdForChild(string localIdHint) { if (localIdHint == null) throw new ArgumentNullException("localIdHint"); string candidateLocalId = localIdHint; if (assignedChildLocalIds == null) { assignedChildLocalIds = new HashSet<string>(); } else { int index = 2; while (assignedChildLocalIds.Contains(candidateLocalId)) { candidateLocalId = localIdHint + index; index += 1; } } assignedChildLocalIds.Add(candidateLocalId); return candidateLocalId; } /// <inheritdoc /> public override string ToString() { return String.Format("[{0}] {1}", Kind, Name); } } }
// Copyright 2017 Google 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 // // 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. using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using UnityEngine; namespace TiltBrushToolkit { [Serializable] public class GOOGLE_tilt_brush_material { public string guid; } [Serializable] public sealed class Gltf2Root : GltfRootBase { public List<Gltf2Buffer> buffers; public List<Gltf2Accessor> accessors; public List<Gltf2BufferView> bufferViews; public List<Gltf2Mesh> meshes; public List<Gltf2Material> materials; public List<Gltf2Node> nodes; public List<Gltf2Scene> scenes; public List<Gltf2Texture> textures; public List<Gltf2Image> images; public int scene; private bool disposed; [JsonIgnore] public Gltf2Scene scenePtr; public override GltfSceneBase ScenePtr { get { return scenePtr; } } public override IEnumerable<GltfImageBase> Images { get { if (images == null) { return new GltfImageBase[0]; } return images.Cast<GltfImageBase>(); } } public override IEnumerable<GltfTextureBase> Textures { get { if (textures == null) { return new GltfTextureBase[0]; } return textures.Cast<GltfTextureBase>(); } } public override IEnumerable<GltfMaterialBase> Materials { get { if (materials == null) { return new GltfMaterialBase[0]; } return materials.Cast<GltfMaterialBase>(); } } public override IEnumerable<GltfMeshBase> Meshes { get { if (meshes == null) { return new GltfMeshBase[0]; } return meshes.Cast<GltfMeshBase>(); } } // Disposable pattern, with Dispose(void) and Dispose(bool), as recommended by: // https://docs.microsoft.com/en-us/dotnet/api/system.idisposable protected override void Dispose(bool disposing) { if (disposed) return; // Already disposed. if (disposing && buffers != null) { foreach (var buffer in buffers) { if (buffer != null && buffer.data != null) { buffer.data.Dispose(); } } } disposed = true; base.Dispose(disposing); } /// Map gltfIndex values (ie, int indices) names to the objects they refer to public override void Dereference(bool isGlb, IUriLoader uriLoader = null) { // "dereference" all the indices scenePtr = scenes[scene]; for (int i = 0; i < buffers.Count; i++) { Gltf2Buffer buffer = buffers[i]; buffer.gltfIndex = i; if (buffer.uri == null && !(i == 0 && isGlb)) { Debug.LogErrorFormat("Buffer {0} isGlb {1} has null uri", i, isGlb); // leave the data buffer null return; } if (uriLoader != null) { buffer.data = uriLoader.Load(buffer.uri); } } for (int i = 0; i < accessors.Count; i++) { accessors[i].gltfIndex = i; accessors[i].bufferViewPtr = bufferViews[accessors[i].bufferView]; } for (int i = 0; i < bufferViews.Count; i++) { bufferViews[i].gltfIndex = i; bufferViews[i].bufferPtr = buffers[bufferViews[i].buffer]; } for (int i = 0; i < meshes.Count; i++) { meshes[i].gltfIndex = i; foreach (var prim in meshes[i].primitives) { prim.attributePtrs = prim.attributes.ToDictionary( elt => elt.Key, elt => accessors[elt.Value]); prim.indicesPtr = accessors[prim.indices]; prim.materialPtr = materials[prim.material]; } } if (images != null) { for (int i = 0; i < images.Count; i++) { images[i].gltfIndex = i; } } if (textures != null) { for (int i = 0; i < textures.Count; i++) { textures[i].gltfIndex = i; textures[i].sourcePtr = images[textures[i].source]; } } for (int i = 0; i < materials.Count; i++) { Gltf2Material mat = materials[i]; mat.gltfIndex = i; DereferenceTextureInfo(mat.emissiveTexture); DereferenceTextureInfo(mat.normalTexture); if (mat.pbrMetallicRoughness != null) { DereferenceTextureInfo(mat.pbrMetallicRoughness.baseColorTexture); DereferenceTextureInfo(mat.pbrMetallicRoughness.metallicRoughnessTexture); } DereferenceTextureInfo(mat.extensions?.KHR_materials_pbrSpecularGlossiness?.diffuseTexture); } for (int i = 0; i < nodes.Count; i++) { nodes[i].gltfIndex = i; Gltf2Node node = nodes[i]; if (node.mesh >= 0) { node.meshPtr = meshes[node.mesh]; } if (node.children != null) { node.childPtrs = node.children.Select(id => nodes[id]).ToList(); } } for (int i = 0; i < scenes.Count; i++) { scenes[i].gltfIndex = i; var thisScene = scenes[i]; if (thisScene.nodes != null) { thisScene.nodePtrs = thisScene.nodes.Select(index => nodes[index]).ToList(); } } } private void DereferenceTextureInfo(Gltf2Material.TextureInfo texInfo) { if (texInfo == null) return; texInfo.texture = textures[texInfo.index]; } } [Serializable] public class Gltf2Buffer : GltfBufferBase { [JsonIgnore] public int gltfIndex; } [Serializable] public class Gltf2Accessor : GltfAccessorBase { public int bufferView; [JsonIgnore] public int gltfIndex; [JsonIgnore] public Gltf2BufferView bufferViewPtr; public override GltfBufferViewBase BufferViewPtr { get { return bufferViewPtr; } } } [Serializable] public class Gltf2BufferView : GltfBufferViewBase { public int buffer; [JsonIgnore] public int gltfIndex; [JsonIgnore] public Gltf2Buffer bufferPtr; public override GltfBufferBase BufferPtr { get { return bufferPtr; } } } [Serializable] public class Gltf2Primitive : GltfPrimitiveBase { public Dictionary<string, int> attributes; // value is an index into accessors[] public int indices; public int material; [JsonIgnore] public Dictionary<string, Gltf2Accessor> attributePtrs; [JsonIgnore] public Gltf2Accessor indicesPtr; [JsonIgnore] public Gltf2Material materialPtr; public override GltfMaterialBase MaterialPtr { get { return materialPtr; } } public override GltfAccessorBase IndicesPtr { get { return indicesPtr; } } public override GltfAccessorBase GetAttributePtr(string attributeName) { return attributePtrs[attributeName]; } public override void ReplaceAttribute(string original, string replacement) { attributes[replacement] = attributes[original]; attributePtrs[replacement] = attributePtrs[original]; attributes.Remove(original); attributePtrs.Remove(original); } public override HashSet<string> GetAttributeNames() { return new HashSet<string>(attributePtrs.Keys); } } [Serializable] public class Gltf2Material : GltfMaterialBase { // Enum values for alphaMode public const string kAlphaModeOpaque = "OPAQUE"; public const string kAlphaModeMask = "MASK"; public const string kAlphaModeBlend = "BLEND"; public Dictionary<string,string> extras; [JsonIgnore] public int gltfIndex; public override Dictionary<string,string> TechniqueExtras { get { return extras; } } private IEnumerable<TextureInfo> TextureInfos { get { yield return normalTexture; yield return emissiveTexture; if (pbrMetallicRoughness != null) { yield return pbrMetallicRoughness.baseColorTexture; yield return pbrMetallicRoughness.metallicRoughnessTexture; } else if (extensions?.KHR_materials_pbrSpecularGlossiness != null) { var specGloss = extensions.KHR_materials_pbrSpecularGlossiness; yield return specGloss.diffuseTexture; } } } public override IEnumerable<GltfTextureBase> ReferencedTextures { get { foreach (var ti in TextureInfos) { if (ti != null && ti.texture != null) { yield return ti.texture; } } } } public PbrMetallicRoughness pbrMetallicRoughness; public TextureInfo normalTexture; public TextureInfo emissiveTexture; public Vector3 emissiveFactor; public string alphaMode; public bool doubleSided; public Extensions extensions; [Serializable] public class Extensions { public GOOGLE_tilt_brush_material GOOGLE_tilt_brush_material; public KHR_materials_pbrSpecularGlossiness KHR_materials_pbrSpecularGlossiness; } [Serializable] public class PbrMetallicRoughness { public Color baseColorFactor = Color.white; public float metallicFactor = 1.0f; public float roughnessFactor = 1.0f; public TextureInfo baseColorTexture; public TextureInfo metallicRoughnessTexture; } [Serializable] public class KHR_materials_pbrSpecularGlossiness { public Color diffuseFactor = Color.white; public TextureInfo diffuseTexture; // public Vector3 specularFactor; not supported public float glossinessFactor = 1.0f; } [Serializable] public class TextureInfo { public int index; // indexes into root.textures[] public int texCoord = 0; [JsonIgnore] public GltfTextureBase texture; } } [Serializable] public class Gltf2Texture : GltfTextureBase { [JsonIgnore] public int gltfIndex; public int source; // indexes into images[] [JsonIgnore] public Gltf2Image sourcePtr; public override object GltfId { get { return gltfIndex; } } public override GltfImageBase SourcePtr { get { return sourcePtr; } } } [Serializable] public class Gltf2Image : GltfImageBase { [JsonIgnore] public int gltfIndex; public string name; public string mimeType; } [Serializable] public class Gltf2Mesh : GltfMeshBase { public List<Gltf2Primitive> primitives; [JsonIgnore] public int gltfIndex; public override IEnumerable<GltfPrimitiveBase> Primitives { get { foreach (Gltf2Primitive prim in primitives) { yield return prim; } } } public override int PrimitiveCount { get { return primitives.Count(); } } public override GltfPrimitiveBase GetPrimitiveAt(int i) { return primitives[i]; } } [Serializable] public class Gltf2Node : GltfNodeBase { public List<int> children; public int mesh = -1; [JsonIgnore] public int gltfIndex; [JsonIgnore] public Gltf2Mesh meshPtr; [JsonIgnore] public List<Gltf2Node> childPtrs; public override GltfMeshBase Mesh { get { return meshPtr; } } public override IEnumerable<GltfNodeBase> Children { get { if (childPtrs == null) yield break; foreach (Gltf2Node node in childPtrs) { yield return node; } } } } [Serializable] public class Gltf2Scene : GltfSceneBase { public List<int> nodes; [JsonIgnore] public int gltfIndex; [JsonIgnore] public List<Gltf2Node> nodePtrs; public override IEnumerable<GltfNodeBase> Nodes { get { foreach (Gltf2Node node in nodePtrs) { yield return node; } } } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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 Microsoft.Live { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Windows.Security.Authentication.Web; using Microsoft.Live.Operations; public partial class LiveAuthClient { private const string SignInOfferName = LiveScopes.Signin; private List<string> currentScopes; private ThemeType? theme; #region Constructor /// <summary> /// Creates a new instance of the auth client. Takes no parameters. /// The application client id is the same as the application package sid. /// </summary> public LiveAuthClient() : this(null) { } /// <summary> /// Creates a new instance of the auth client. /// The application client id is the same as the application package sid. /// </summary> /// <param name="redirectUri">The application's redirect uri as specified in application management portal.</param> public LiveAuthClient(string redirectUri) { if (!string.IsNullOrEmpty(redirectUri) && !IsValidRedirectDomain(redirectUri)) { throw new ArgumentException( redirectUri, String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "redirectUri")); } this.AuthClient = new TailoredAuthClient(this); if (string.IsNullOrEmpty(redirectUri)) { redirectUri = TailoredAuthClient.Win8ReturnUriScheme; } this.InitializeMembers(string.Empty, redirectUri); } #endregion #region Properties /// <summary> /// Gets and sets the theme used for the consent request. /// </summary> public ThemeType Theme { get { if (!this.theme.HasValue) { this.theme = Platform.GetThemeType(); } return this.theme.Value; } set { this.theme = value; } } /// <summary> /// Gets whether or not sign out is supported for the logged in user. /// </summary> /// <remarks>Sign out is only supported for non-connected user accounts.</remarks> public bool CanLogout { get { return this.AuthClient.CanSignOut; } } #endregion #region Public Methods /// <summary> /// Initializes the auth client. Detects if user is already signed in, /// If user is already signed in, creates a valid Session. /// This call is UI-less. /// </summary> public Task<LiveLoginResult> InitializeAsync() { return this.InitializeAsync(new List<string>()); } /// <summary> /// Initializes the auth client. Detects if user is already signed in, /// If user is already signed in, creates a valid Session. /// This call is UI-less. /// </summary> /// <param name="scopes">The list of offers that the application is requesting user consent for.</param> public Task<LiveLoginResult> InitializeAsync(IEnumerable<string> scopes) { if (scopes != null) { return InitializeAsync(scopes.ToArray()); } else { return InitializeAsync(null); } } /// <summary> /// Initializes the auth client. Detects if user is already signed in, /// If user is already signed in, creates a valid Session. /// This call is UI-less. /// </summary> /// <param name="scopes"></param> /// <returns></returns> public Task<LiveLoginResult> InitializeAsync(params string[] scopes) { if (scopes == null) { throw new ArgumentNullException("scopes"); } return this.ExecuteAuthTaskAsync(scopes, true); } /// <summary> /// Displays the login/consent UI and returns a Session object when user completes the auth flow. /// </summary> /// <param name="scopes">The list of offers that the application is requesting user consent for.</param> public Task<LiveLoginResult> LoginAsync(IEnumerable<string> scopes) { if (scopes != null) { return LoginAsync(scopes.ToArray()); } else { return LoginAsync(null); } } /// <summary> /// Displays the login/consent UI and returns a Session object when user completes the auth flow. /// </summary> /// <param name="scopes">The list of offers that the application is requesting user consent for.</param> public Task<LiveLoginResult> LoginAsync(params string[] scopes) { if (scopes == null && this.scopes == null) { throw new ArgumentNullException("scopes"); } return this.ExecuteAuthTaskAsync(scopes, false); } /// <summary> /// Logs user out of the application. Clears any cached Session data. /// </summary> public void Logout() { if (!this.CanLogout) { throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("CantLogout")); } this.AuthClient.CloseSession(); } #endregion #region Internal/Private Methods /// <summary> /// Creates a LiveConnectSession object based on the parsed response. /// </summary> internal static LiveConnectSession CreateSession(LiveAuthClient client, IDictionary<string, object> result) { var session = new LiveConnectSession(client); Debug.Assert(result.ContainsKey(AuthConstants.AccessToken)); if (result.ContainsKey(AuthConstants.AccessToken)) { session.AccessToken = result[AuthConstants.AccessToken] as string; if (result.ContainsKey(AuthConstants.AuthenticationToken)) { session.AuthenticationToken = result[AuthConstants.AuthenticationToken] as string; } } return session; } /// <summary> /// Gets current user login status. /// </summary> /// <returns></returns> internal async Task<LiveLoginResult> GetLoginStatusAsync() { LiveLoginResult result = await this.AuthClient.AuthenticateAsync( LiveAuthClient.BuildScopeString(this.currentScopes), true); if (result.Status == LiveConnectSessionStatus.NotConnected && this.currentScopes.Count > 1) { // The user might have revoked one of the scopes while the app is running. Try getting a token for the remaining scopes // by passing in only the "wl.signin" scope. The server should return a token that contains all remaining scopes. this.currentScopes = new List<string>(new string[] { LiveAuthClient.SignInOfferName }); result = await this.AuthClient.AuthenticateAsync( LiveAuthClient.BuildScopeString(this.currentScopes), true); } if (result.Status == LiveConnectSessionStatus.Unknown) { // If the auth result indicates that the current account is not connected, we should clear the session this.Session = null; } else if (result.Session != null && !LiveAuthClient.AreSessionsSame(this.Session, result.Session)) { this.Session = result.Session; } return result; } /// <summary> /// Retrieve a new access token based on current session information. /// </summary> internal bool RefreshToken(Action<LiveLoginResult> completionCallback) { this.TryRefreshToken(completionCallback); return true; } private async Task<LiveLoginResult> ExecuteAuthTaskAsync(IEnumerable<string> scopes, bool silent) { if (scopes != null) { this.scopes = new List<string>(scopes); } this.EnsureSignInScope(); this.PrepareForAsync(); LiveLoginResult result = await this.AuthClient.AuthenticateAsync( LiveAuthClient.BuildScopeString(this.scopes), silent); if (result.Session != null && !LiveAuthClient.AreSessionsSame(this.Session, result.Session)) { this.MergeScopes(); this.Session = result.Session; } Interlocked.Decrement(ref this.asyncInProgress); if (result.Error != null) { throw result.Error; } return result; } private static bool AreSessionsSame(LiveConnectSession session1, LiveConnectSession session2) { if (session1 != null && session2 != null) { return session1.AccessToken == session2.AccessToken && session1.AuthenticationToken == session2.AuthenticationToken; } return session1 == session2; } private static bool IsValidRedirectDomain(string redirectDomain) { if (!redirectDomain.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && !redirectDomain.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { return false; } try { var redirectUri = new Uri(redirectDomain, UriKind.Absolute); return redirectUri.IsWellFormedOriginalString(); } catch (FormatException) { return false; } } private void EnsureSignInScope() { Debug.Assert(this.scopes != null); if (string.IsNullOrEmpty(this.scopes.Find(s => string.CompareOrdinal(s, LiveAuthClient.SignInOfferName) == 0))) { this.scopes.Insert(0, LiveAuthClient.SignInOfferName); } } private string GetAppPackageSid() { Uri redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); Debug.Assert(redirectUri != null); return redirectUri.AbsoluteUri; } private void MergeScopes() { Debug.Assert(this.scopes != null); if (this.currentScopes == null) { this.currentScopes = new List<string>(this.scopes); return; } foreach (string newScope in this.scopes) { if (!this.currentScopes.Contains(newScope)) { this.currentScopes.Add(newScope); } } } private async void TryRefreshToken(Action<LiveLoginResult> completionCallback) { LiveLoginResult result = await this.AuthClient.AuthenticateAsync( LiveAuthClient.BuildScopeString(this.currentScopes), true); if (result.Status == LiveConnectSessionStatus.NotConnected && this.currentScopes.Count > 1) { // The user might have revoked one of the scopes while the app is running. Try getting a token for the remaining scopes // by passing in only the "wl.signin" scope. The server should return a token that contains all remaining scopes. this.currentScopes = new List<string>(new string[] { LiveAuthClient.SignInOfferName }); result = await this.AuthClient.AuthenticateAsync( LiveAuthClient.BuildScopeString(this.currentScopes), true); } if (result.Status == LiveConnectSessionStatus.Unknown) { // If the auth result indicates that the current account is not connected, we should clear the session this.Session = null; } else if (result.Session != null && !LiveAuthClient.AreSessionsSame(this.Session, result.Session)) { this.Session = result.Session; } completionCallback(result); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="ComponentEditorForm.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms.Design { using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.Security.Permissions; using System.Windows.Forms; using System.Windows.Forms.Internal; using System.Drawing; using System.Reflection; using System.ComponentModel.Design; using System.Windows.Forms.ComponentModel; using Microsoft.Win32; using Message = System.Windows.Forms.Message; /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm"]/*' /> /// <devdoc> /// <para>Provides a user interface for <see cref='System.Windows.Forms.Design.WindowsFormsComponentEditor'/>.</para> /// </devdoc> [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch) ] [ToolboxItem(false)] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name="FullTrust")] public class ComponentEditorForm : Form { private IComponent component; private Type[] pageTypes; private ComponentEditorPageSite[] pageSites; private Size maxSize = System.Drawing.Size.Empty; private int initialActivePage; private int activePage; private bool dirty; private bool firstActivate; private Panel pageHost = new Panel(); private PageSelector selector; private ImageList selectorImageList; private Button okButton; private Button cancelButton; private Button applyButton; private Button helpButton; // private DesignerTransaction transaction; private const int BUTTON_WIDTH = 80; private const int BUTTON_HEIGHT = 23; private const int BUTTON_PAD = 6; private const int MIN_SELECTOR_WIDTH = 90; private const int SELECTOR_PADDING = 10; private const int STRIP_HEIGHT = 4; /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ComponentEditorForm"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.Design.ComponentEditorForm'/> class. /// </para> /// </devdoc> public ComponentEditorForm(object component, Type[] pageTypes) : base() { if (!(component is IComponent)) { throw new ArgumentException(SR.GetString(SR.ComponentEditorFormBadComponent),"component"); } this.component = (IComponent)component; this.pageTypes = pageTypes; dirty = false; firstActivate = true; activePage = -1; initialActivePage = 0; FormBorderStyle = FormBorderStyle.FixedDialog; MinimizeBox = false; MaximizeBox = false; ShowInTaskbar = false; Icon = null; StartPosition = FormStartPosition.CenterParent; OnNewObjects(); OnConfigureUI(); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ApplyChanges"]/*' /> /// <devdoc> /// Applies any changes in the set of ComponentPageControl to the actual component. /// </devdoc> /// <internalonly/> internal virtual void ApplyChanges(bool lastApply) { if (dirty) { IComponentChangeService changeService = null; if (component.Site != null) { changeService = (IComponentChangeService)component.Site.GetService(typeof(IComponentChangeService)); if (changeService != null) { try { changeService.OnComponentChanging(component, null); } catch (CheckoutException e) { if (e == CheckoutException.Canceled) { return; } throw e; } } } for (int n = 0; n < pageSites.Length; n++) { if (pageSites[n].Dirty) { pageSites[n].GetPageControl().ApplyChanges(); pageSites[n].Dirty = false; } } if (changeService != null) { changeService.OnComponentChanged(component, null, null, null); } applyButton.Enabled = false; cancelButton.Text = SR.GetString(SR.CloseCaption); dirty = false; if (lastApply == false) { for (int n = 0; n < pageSites.Length; n++) { pageSites[n].GetPageControl().OnApplyComplete(); } } /* if (transaction != null) { transaction.Commit(); CreateNewTransaction(); } */ } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.AutoSize"]/*' /> /// <devdoc> /// <para> /// Hide the property /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.AutoSizeChanged"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler AutoSizeChanged { add { base.AutoSizeChanged += value; } remove { base.AutoSizeChanged -= value; } } /* private void CreateNewTransaction() { IDesignerHost host = component.Site.GetService(typeof(IDesignerHost)) as IDesignerHost; transaction = host.CreateTransaction(SR.GetString(SR.ComponentEditorFormEditTransaction, component.Site.Name)); } */ /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.OnButtonClick"]/*' /> /// <devdoc> /// Handles ok/cancel/apply/help button click events /// </devdoc> /// <internalonly/> private void OnButtonClick(object sender, EventArgs e) { if (sender == okButton) { ApplyChanges(true); DialogResult = DialogResult.OK; } else if (sender == cancelButton) { DialogResult = DialogResult.Cancel; } else if (sender == applyButton) { ApplyChanges(false); } else if (sender == helpButton) { ShowPageHelp(); } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.OnConfigureUI"]/*' /> /// <devdoc> /// Lays out the UI of the form. /// </devdoc> /// <internalonly/> private void OnConfigureUI() { Font uiFont = Control.DefaultFont; if (component.Site != null) { IUIService uiService = (IUIService)component.Site.GetService(typeof(IUIService)); if (uiService != null) { uiFont = (Font)uiService.Styles["DialogFont"]; } } this.Font = uiFont; okButton = new Button(); cancelButton = new Button(); applyButton = new Button(); helpButton = new Button(); selectorImageList = new ImageList(); selectorImageList.ImageSize = new Size(16, 16); selector = new PageSelector(); selector.ImageList = selectorImageList; selector.AfterSelect += new TreeViewEventHandler(this.OnSelChangeSelector); Label grayStrip = new Label(); grayStrip.BackColor = SystemColors.ControlDark; int selectorWidth = MIN_SELECTOR_WIDTH; if (pageSites != null) { // Add the nodes corresponding to the pages for (int n = 0; n < pageSites.Length; n++) { ComponentEditorPage page = pageSites[n].GetPageControl(); string title = page.Title; Graphics graphics = CreateGraphicsInternal(); int titleWidth = (int) graphics.MeasureString(title, Font).Width; graphics.Dispose(); selectorImageList.Images.Add(page.Icon.ToBitmap()); selector.Nodes.Add(new TreeNode(title, n, n)); if (titleWidth > selectorWidth) selectorWidth = titleWidth; } } selectorWidth += SELECTOR_PADDING; string caption = String.Empty; ISite site = component.Site; if (site != null) { caption = SR.GetString(SR.ComponentEditorFormProperties, site.Name); } else { caption = SR.GetString(SR.ComponentEditorFormPropertiesNoName); } this.Text = caption; Rectangle pageHostBounds = new Rectangle(2 * BUTTON_PAD + selectorWidth, 2 * BUTTON_PAD + STRIP_HEIGHT, maxSize.Width, maxSize.Height); pageHost.Bounds = pageHostBounds; grayStrip.Bounds = new Rectangle(pageHostBounds.X, BUTTON_PAD, pageHostBounds.Width, STRIP_HEIGHT); if (pageSites != null) { Rectangle pageBounds = new Rectangle(0, 0, pageHostBounds.Width, pageHostBounds.Height); for (int n = 0; n < pageSites.Length; n++) { ComponentEditorPage page = pageSites[n].GetPageControl(); page.GetControl().Bounds = pageBounds; } } int xFrame = SystemInformation.FixedFrameBorderSize.Width; Rectangle bounds = pageHostBounds; Size size = new Size(bounds.Width + 3 * (BUTTON_PAD + xFrame) + selectorWidth, bounds.Height + STRIP_HEIGHT + 4 * BUTTON_PAD + BUTTON_HEIGHT + 2 * xFrame + SystemInformation.CaptionHeight); this.Size = size; selector.Bounds = new Rectangle(BUTTON_PAD, BUTTON_PAD, selectorWidth, bounds.Height + STRIP_HEIGHT + 2 * BUTTON_PAD + BUTTON_HEIGHT); bounds.X = bounds.Width + bounds.X - BUTTON_WIDTH; bounds.Y = bounds.Height + bounds.Y + BUTTON_PAD; bounds.Width = BUTTON_WIDTH; bounds.Height = BUTTON_HEIGHT; helpButton.Bounds = bounds; helpButton.Text = SR.GetString(SR.HelpCaption); helpButton.Click += new EventHandler(this.OnButtonClick); helpButton.Enabled = false; helpButton.FlatStyle = FlatStyle.System; bounds.X -= (BUTTON_WIDTH + BUTTON_PAD); applyButton.Bounds = bounds; applyButton.Text = SR.GetString(SR.ApplyCaption); applyButton.Click += new EventHandler(this.OnButtonClick); applyButton.Enabled = false; applyButton.FlatStyle = FlatStyle.System; bounds.X -= (BUTTON_WIDTH + BUTTON_PAD); cancelButton.Bounds = bounds; cancelButton.Text = SR.GetString(SR.CancelCaption); cancelButton.Click += new EventHandler(this.OnButtonClick); cancelButton.FlatStyle = FlatStyle.System; this.CancelButton = cancelButton; bounds.X -= (BUTTON_WIDTH + BUTTON_PAD); okButton.Bounds = bounds; okButton.Text = SR.GetString(SR.OKCaption); okButton.Click += new EventHandler(this.OnButtonClick); okButton.FlatStyle = FlatStyle.System; this.AcceptButton = okButton; this.Controls.Clear(); this.Controls.AddRange(new Control[] { selector, grayStrip, pageHost, okButton, cancelButton, applyButton, helpButton }); #pragma warning disable 618 // continuing with the old autoscale base size stuff, it works, // and is currently set to a non-standard height AutoScaleBaseSize = new Size(5, 14); ApplyAutoScaling(); #pragma warning restore 618 } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.OnActivated"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // SECREVIEW: This seems safe, but could anything dangerous occur here? protected override void OnActivated(EventArgs e) { base.OnActivated(e); if (firstActivate) { firstActivate = false; selector.SelectedNode = selector.Nodes[initialActivePage]; pageSites[initialActivePage].Active = true; activePage = initialActivePage; helpButton.Enabled = pageSites[activePage].GetPageControl().SupportsHelp(); } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.OnHelpRequested"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // SECREVIEW: This seems safe, but could anything dangerous occur here? protected override void OnHelpRequested(HelpEventArgs e) { base.OnHelpRequested(e); ShowPageHelp(); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.OnNewObjects"]/*' /> /// <devdoc> /// Called to initialize this form with the new component. /// </devdoc> /// <internalonly/> private void OnNewObjects() { pageSites = null; maxSize = new Size(3 * (BUTTON_WIDTH + BUTTON_PAD), 24 * pageTypes.Length); pageSites = new ComponentEditorPageSite[pageTypes.Length]; // create sites for them // for (int n = 0; n < pageTypes.Length; n++) { pageSites[n] = new ComponentEditorPageSite(pageHost, pageTypes[n], component, this); ComponentEditorPage page = pageSites[n].GetPageControl(); Size pageSize = page.Size; if (pageSize.Width > maxSize.Width) maxSize.Width = pageSize.Width; if (pageSize.Height > maxSize.Height) maxSize.Height = pageSize.Height; } // and set them all to an ideal size // for (int n = 0; n < pageSites.Length; n++) { pageSites[n].GetPageControl().Size = maxSize; } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.OnSelChangeSelector"]/*' /> /// <devdoc> /// Handles switching between pages. /// </devdoc> /// <internalonly/> protected virtual void OnSelChangeSelector(object source, TreeViewEventArgs e) { if (firstActivate == true) { // treeview seems to fire a change event when it is first setup before // the form is activated return; } int newPage = selector.SelectedNode.Index; Debug.Assert((newPage >= 0) && (newPage < pageSites.Length), "Invalid page selected"); if (newPage == activePage) return; if (activePage != -1) { if (pageSites[activePage].AutoCommit) ApplyChanges(false); pageSites[activePage].Active = false; } activePage = newPage; pageSites[activePage].Active = true; helpButton.Enabled = pageSites[activePage].GetPageControl().SupportsHelp(); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.PreProcessMessage"]/*' /> /// <devdoc> /// <para>Provides a method to override in order to pre-process input messages before /// they are dispatched.</para> /// </devdoc> [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public override bool PreProcessMessage(ref Message msg) { if (null != pageSites && pageSites[activePage].GetPageControl().IsPageMessage(ref msg)) return true; return base.PreProcessMessage(ref msg); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.SetDirty"]/*' /> /// <devdoc> /// Sets the controls of the form to dirty. This enables the "apply" /// button. /// </devdoc> internal virtual void SetDirty() { dirty = true; applyButton.Enabled = true; cancelButton.Text = SR.GetString(SR.CancelCaption); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ShowForm"]/*' /> /// <devdoc> /// <para>Shows the form. The form will have no owner window.</para> /// </devdoc> public virtual DialogResult ShowForm() { return ShowForm(null, 0); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ShowForm1"]/*' /> /// <devdoc> /// <para> Shows the form and the specified page. The form will have no owner window.</para> /// </devdoc> public virtual DialogResult ShowForm(int page) { return ShowForm(null, page); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ShowForm2"]/*' /> /// <devdoc> /// <para>Shows the form with the specified owner.</para> /// </devdoc> public virtual DialogResult ShowForm(IWin32Window owner) { return ShowForm(owner, 0); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ShowForm3"]/*' /> /// <devdoc> /// <para>Shows the form and the specified page with the specified owner.</para> /// </devdoc> public virtual DialogResult ShowForm(IWin32Window owner, int page) { initialActivePage = page; // CreateNewTransaction(); try { ShowDialog(owner); } finally { /* if (DialogResult == DialogResult.OK) { transaction.Commit(); } else { transaction.Cancel(); } */ } return DialogResult; } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ShowPageHelp"]/*' /> /// <devdoc> /// Shows help for the active page. /// </devdoc> /// <internalonly/> private void ShowPageHelp() { Debug.Assert(activePage != -1); if (pageSites[activePage].GetPageControl().SupportsHelp()) { pageSites[activePage].GetPageControl().ShowHelp(); } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ComponentEditorPageSite"]/*' /> /// <devdoc> /// Implements a standard version of ComponentEditorPageSite for use within a /// ComponentEditorForm. /// </devdoc> /// <internalonly/> private sealed class ComponentEditorPageSite : IComponentEditorPageSite { internal IComponent component; internal ComponentEditorPage pageControl; internal Control parent; internal bool isActive; internal bool isDirty; private ComponentEditorForm form; /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ComponentEditorPageSite.ComponentEditorPageSite"]/*' /> /// <devdoc> /// Creates the page site. /// </devdoc> /// <internalonly/> internal ComponentEditorPageSite(Control parent, Type pageClass, IComponent component, ComponentEditorForm form) { this.component = component; this.parent = parent; this.isActive = false; this.isDirty = false; if (form == null) throw new ArgumentNullException("form"); this.form = form; try { pageControl = (ComponentEditorPage)SecurityUtils.SecureCreateInstance(pageClass); } catch (TargetInvocationException e) { Debug.Fail(e.ToString()); throw new TargetInvocationException(SR.GetString(SR.ExceptionCreatingCompEditorControl, e.ToString()), e.InnerException); } pageControl.SetSite(this); pageControl.SetComponent(component); } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ComponentEditorPageSite.Active"]/*' /> /// <devdoc> /// Called by the ComponentEditorForm to activate / deactivate the page. /// </devdoc> /// <internalonly/> internal bool Active { set { if (value) { // make sure the page has been created pageControl.CreateControl(); // activate it and give it focus pageControl.Activate(); } else { pageControl.Deactivate(); } isActive = value; } } internal bool AutoCommit { get { return pageControl.CommitOnDeactivate; } } internal bool Dirty { get { return isDirty; } set { isDirty = value; } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ComponentEditorPageSite.GetControl"]/*' /> /// <devdoc> /// Called by a page to return a parenting control for itself. /// </devdoc> /// <internalonly/> public Control GetControl() { return parent; } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ComponentEditorPageSite.GetPageControl"]/*' /> /// <devdoc> /// Called by the ComponentEditorForm to get the actual page. /// </devdoc> /// <internalonly/> internal ComponentEditorPage GetPageControl() { return pageControl; } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.ComponentEditorPageSite.SetDirty"]/*' /> /// <devdoc> /// Called by a page to mark it's contents as dirty. /// </devdoc> /// <internalonly/> public void SetDirty() { if (isActive) Dirty = true; form.SetDirty(); } } /// <include file='doc\ComponentEditorForm.uex' path='docs/doc[@for="ComponentEditorForm.PageSelector"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> // internal sealed class PageSelector : TreeView { private const int PADDING_VERT = 3; private const int PADDING_HORZ = 4; private const int SIZE_ICON_X = 16; private const int SIZE_ICON_Y = 16; private const int STATE_NORMAL = 0; private const int STATE_SELECTED = 1; private const int STATE_HOT = 2; private IntPtr hbrushDither; public PageSelector() { this.HotTracking = true; this.HideSelection = false; this.BackColor = SystemColors.Control; this.Indent = 0; this.LabelEdit = false; this.Scrollable = false; this.ShowLines = false; this.ShowPlusMinus = false; this.ShowRootLines = false; this.BorderStyle = BorderStyle.None; this.Indent = 0; this.FullRowSelect = true; } protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_STATICEDGE; return cp; } } private void CreateDitherBrush() { Debug.Assert(hbrushDither == IntPtr.Zero, "Brush should not be recreated."); short[] patternBits = new short[] { unchecked((short)0xAAAA), unchecked((short)0x5555), unchecked((short)0xAAAA), unchecked((short)0x5555), unchecked((short)0xAAAA), unchecked((short)0x5555), unchecked((short)0xAAAA), unchecked((short)0x5555) }; IntPtr hbitmapTemp = SafeNativeMethods.CreateBitmap(8, 8, 1, 1, patternBits); Debug.Assert(hbitmapTemp != IntPtr.Zero, "could not create dither bitmap. Page selector UI will not be correct"); if (hbitmapTemp != IntPtr.Zero) { hbrushDither = SafeNativeMethods.CreatePatternBrush(new HandleRef(null, hbitmapTemp)); Debug.Assert(hbrushDither != IntPtr.Zero, "Unable to created dithered brush. Page selector UI will not be correct"); SafeNativeMethods.DeleteObject(new HandleRef(null, hbitmapTemp)); } } private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMethods.RECT rcIn, int state, int backColor, int textColor) { IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); IntNativeMethods.RECT rc2 = new IntNativeMethods.RECT(); IntNativeMethods.RECT rc = new IntNativeMethods.RECT(rcIn.left, rcIn.top, rcIn.right, rcIn.bottom); ImageList imagelist = this.ImageList; IntPtr hfontOld = IntPtr.Zero; // Select the font of the dialog, so we don't get the underlined font // when the item is being tracked if ((state & STATE_HOT) != 0) hfontOld = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(Parent, ((Control)Parent).FontHandle)); // Fill the background if (((state & STATE_SELECTED) != 0) && (hbrushDither != IntPtr.Zero)) { FillRectDither(dc, rcIn); SafeNativeMethods.SetBkMode(new HandleRef(null, dc), NativeMethods.TRANSPARENT); } else { SafeNativeMethods.SetBkColor(new HandleRef(null, dc), backColor); IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_CLIPPED | NativeMethods.ETO_OPAQUE, ref rc, null, 0, null); } // Get the height of the font IntUnsafeNativeMethods.GetTextExtentPoint32(new HandleRef(null, dc), itemText, size); // Draw the caption rc2.left = rc.left + SIZE_ICON_X + 2 * PADDING_HORZ; rc2.top = rc.top + (((rc.bottom - rc.top) - size.cy) >> 1); rc2.bottom = rc2.top + size.cy; rc2.right = rc.right; SafeNativeMethods.SetTextColor(new HandleRef(null, dc), textColor); IntUnsafeNativeMethods.DrawText(new HandleRef(null, dc), itemText, ref rc2, IntNativeMethods.DT_LEFT | IntNativeMethods.DT_VCENTER | IntNativeMethods.DT_END_ELLIPSIS | IntNativeMethods.DT_NOPREFIX); SafeNativeMethods.ImageList_Draw(new HandleRef(imagelist, imagelist.Handle), imageIndex, new HandleRef(null, dc), PADDING_HORZ, rc.top + (((rc.bottom - rc.top) - SIZE_ICON_Y) >> 1), NativeMethods.ILD_TRANSPARENT); // Draw the hot-tracking border if needed if ((state & STATE_HOT) != 0) { int savedColor; // top left savedColor = SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.ControlLightLight)); rc2.left = rc.left; rc2.top = rc.top; rc2.bottom = rc.top + 1; rc2.right = rc.right; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); rc2.bottom = rc.bottom; rc2.right = rc.left + 1; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); // bottom right SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.ControlDark)); rc2.left = rc.left; rc2.right = rc.right; rc2.top = rc.bottom - 1; rc2.bottom = rc.bottom; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); rc2.left = rc.right - 1; rc2.top = rc.top; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); SafeNativeMethods.SetBkColor(new HandleRef(null, dc), savedColor); } if (hfontOld != IntPtr.Zero) SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(null, hfontOld)); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); int itemHeight; itemHeight = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_GETITEMHEIGHT, 0, 0); itemHeight += 2 * PADDING_VERT; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_SETITEMHEIGHT, itemHeight, 0); if (hbrushDither == IntPtr.Zero) { CreateDitherBrush(); } } private void OnCustomDraw(ref Message m) { NativeMethods.NMTVCUSTOMDRAW nmtvcd = (NativeMethods.NMTVCUSTOMDRAW)m.GetLParam(typeof(NativeMethods.NMTVCUSTOMDRAW)); switch (nmtvcd.nmcd.dwDrawStage) { case NativeMethods.CDDS_PREPAINT: m.Result = (IntPtr)(NativeMethods.CDRF_NOTIFYITEMDRAW | NativeMethods.CDRF_NOTIFYPOSTPAINT); break; case NativeMethods.CDDS_ITEMPREPAINT: { TreeNode itemNode = TreeNode.FromHandle(this, (IntPtr)nmtvcd.nmcd.dwItemSpec); if (itemNode != null) { int state = STATE_NORMAL; int itemState = nmtvcd.nmcd.uItemState; if (((itemState & NativeMethods.CDIS_HOT) != 0) || ((itemState & NativeMethods.CDIS_FOCUS) != 0)) state |= STATE_HOT; if ((itemState & NativeMethods.CDIS_SELECTED) != 0) state |= STATE_SELECTED; DrawTreeItem(itemNode.Text, itemNode.ImageIndex, nmtvcd.nmcd.hdc, nmtvcd.nmcd.rc, state, ColorTranslator.ToWin32(SystemColors.Control), ColorTranslator.ToWin32(SystemColors.ControlText)); } m.Result = (IntPtr)NativeMethods.CDRF_SKIPDEFAULT; } break; case NativeMethods.CDDS_POSTPAINT: m.Result = (IntPtr)NativeMethods.CDRF_SKIPDEFAULT; break; default: m.Result = (IntPtr)NativeMethods.CDRF_DODEFAULT; break; } } protected override void OnHandleDestroyed(EventArgs e) { base.OnHandleDestroyed(e); if (!RecreatingHandle && (hbrushDither != IntPtr.Zero)) { SafeNativeMethods.DeleteObject(new HandleRef(this, hbrushDither)); hbrushDither = IntPtr.Zero; } } private void FillRectDither(IntPtr dc, NativeMethods.RECT rc) { IntPtr hbrushOld = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(this, hbrushDither)); if (hbrushOld != IntPtr.Zero) { int oldTextColor, oldBackColor; oldTextColor = SafeNativeMethods.SetTextColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.ControlLightLight)); oldBackColor = SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.Control)); SafeNativeMethods.PatBlt(new HandleRef(null, dc), rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, NativeMethods.PATCOPY); SafeNativeMethods.SetTextColor(new HandleRef(null, dc), oldTextColor); SafeNativeMethods.SetBkColor(new HandleRef(null, dc), oldBackColor); } } [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (m.Msg == NativeMethods.WM_REFLECT + NativeMethods.WM_NOTIFY) { NativeMethods.NMHDR nmh = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); if (nmh.code == NativeMethods.NM_CUSTOMDRAW) { OnCustomDraw(ref m); return; } } base.WndProc(ref m); } } } }
/* * 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 Apache.Geode.Client; namespace Apache.Geode.Client.Tests { public class PositionPdx : IPdxSerializable { #region Private members private long m_avg20DaysVol; private string m_bondRating; private double m_convRatio; private string m_country; private double m_delta; private long m_industry; private long m_issuer; private double m_mktValue; private double m_qty; private string m_secId; private string m_secLinks; private string m_secType; private int m_sharesOutstanding; private string m_underlyer; private long m_volatility; private int m_pid; private static int m_count = 0; #endregion #region Private methods private void Init() { m_avg20DaysVol = 0; m_bondRating = null; m_convRatio = 0.0; m_country = null; m_delta = 0.0; m_industry = 0; m_issuer = 0; m_mktValue = 0.0; m_qty = 0.0; m_secId = null; m_secLinks = null; m_secType = null; m_sharesOutstanding = 0; m_underlyer = null; m_volatility = 0; m_pid = 0; } private UInt32 GetObjectSize(IGeodeSerializable obj) { return (obj == null ? 0 : obj.ObjectSize); } #endregion #region Public accessors public string secId { get { return m_secId; } } public int Id { get { return m_pid; } } public int getSharesOutstanding { get { return m_sharesOutstanding; } } public static int Count { get { return m_count; } set { m_count = value; } } public override string ToString() { return "Position [secId=" + m_secId + " sharesOutstanding=" + m_sharesOutstanding + " type=" + m_secType + " id=" + m_pid + "]"; } #endregion #region Constructors public PositionPdx() { Init(); } //This ctor is for a data validation test public PositionPdx(Int32 iForExactVal) { Init(); char[] id = new char[iForExactVal + 1]; for (int i = 0; i <= iForExactVal; i++) { id[i] = 'a'; } m_secId = new string(id); m_qty = iForExactVal % 2 == 0 ? 1000 : 100; m_mktValue = m_qty * 2; m_sharesOutstanding = iForExactVal; m_secType = "a"; m_pid = iForExactVal; } public PositionPdx(string id, int shares) { Init(); m_secId = id; m_qty = shares * (m_count % 2 == 0 ? 10.0 : 100.0); m_mktValue = m_qty * 1.2345998; m_sharesOutstanding = shares; m_secType = "a"; m_pid = m_count++; } #endregion /* public UInt32 ClassId { get { return 0x02; } } */ public static IPdxSerializable CreateDeserializable() { return new PositionPdx(); } #region IPdxSerializable Members public void FromData(IPdxReader reader) { m_avg20DaysVol = reader.ReadLong("avg20DaysVol"); m_bondRating = reader.ReadString("bondRating"); m_convRatio = reader.ReadDouble("convRatio"); m_country = reader.ReadString("country"); m_delta = reader.ReadDouble("delta"); m_industry = reader.ReadLong("industry"); m_issuer = reader.ReadLong("issuer"); m_mktValue = reader.ReadDouble("mktValue"); m_qty = reader.ReadDouble("qty"); m_secId = reader.ReadString("secId"); m_secLinks = reader.ReadString("secLinks"); m_secType = reader.ReadString("secType"); m_sharesOutstanding = reader.ReadInt("sharesOutstanding"); m_underlyer = reader.ReadString("underlyer"); m_volatility = reader.ReadLong("volatility"); m_pid = reader.ReadInt("pid"); } public void ToData(IPdxWriter writer) { writer.WriteLong("avg20DaysVol", m_avg20DaysVol) .MarkIdentityField("avg20DaysVol") .WriteString("bondRating", m_bondRating) .MarkIdentityField("bondRating") .WriteDouble("convRatio", m_convRatio) .MarkIdentityField("convRatio") .WriteString("country", m_country) .MarkIdentityField("country") .WriteDouble("delta", m_delta) .MarkIdentityField("delta") .WriteLong("industry", m_industry) .MarkIdentityField("industry") .WriteLong("issuer", m_issuer) .MarkIdentityField("issuer") .WriteDouble("mktValue", m_mktValue) .MarkIdentityField("mktValue") .WriteDouble("qty", m_qty) .MarkIdentityField("qty") .WriteString("secId", m_secId) .MarkIdentityField("secId") .WriteString("secLinks", m_secLinks) .MarkIdentityField("secLinks") .WriteString("secType", m_secType) .MarkIdentityField("secType") .WriteInt("sharesOutstanding", m_sharesOutstanding) .MarkIdentityField("sharesOutstanding") .WriteString("underlyer", m_underlyer) .MarkIdentityField("underlyer") .WriteLong("volatility", m_volatility) .MarkIdentityField("volatility") .WriteInt("pid", m_pid) .MarkIdentityField("pid"); //identity field //writer.MarkIdentityField("pid"); } #endregion } }