context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // XmlSerializer.cs // // Author: // Scott Thomas <lunchtimemama@gmail.com> // // Copyright (c) 2009 Scott Thomas // // 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.IO; using System.Text; using System.Xml; using Mono.Upnp.Internal; using Mono.Upnp.Xml.Compilation; namespace Mono.Upnp.Xml { public sealed class XmlSerializer { struct Nothing { } readonly XmlSerializer<Nothing> serializer = new XmlSerializer<Nothing> (); public void Serialize<TObject> (TObject obj, XmlWriter writer) { serializer.Serialize (obj, writer, new Nothing ()); } public void Serialize<TObject> (TObject obj, Stream stream) { Serialize (obj, stream, null); } public void Serialize<TObject> (TObject obj, Stream stream, XmlSerializationOptions options) { if (options == null) { serializer.Serialize (obj, stream); } else { serializer.Serialize (obj, stream, new XmlSerializationOptions<Nothing> { Encoding = options.Encoding, XmlDeclarationType = options.XmlDeclarationType }); } } public byte[] GetBytes<TObject> (TObject obj) { return GetBytes (obj, null); } public byte[] GetBytes<TObject> (TObject obj, XmlSerializationOptions options) { if (options == null) { return serializer.GetBytes (obj); } else { return serializer.GetBytes (obj, new XmlSerializationOptions<Nothing> { Encoding = options.Encoding, XmlDeclarationType = options.XmlDeclarationType }); } } public string GetString<TObject> (TObject obj) { return GetString (obj, null); } public string GetString<TObject> (TObject obj, XmlSerializationOptions options) { if (options == null) { return serializer.GetString (obj); } else { return serializer.GetString (obj, new XmlSerializationOptions<Nothing> { Encoding = options.Encoding, XmlDeclarationType = options.XmlDeclarationType }); } } } public sealed class XmlSerializer<TContext> { readonly SerializationCompilerProvider<TContext> compiler_provider; readonly Dictionary<Type, SerializationCompiler<TContext>> compilers = new Dictionary<Type, SerializationCompiler<TContext>> (); public XmlSerializer () : this (null) { } public XmlSerializer (SerializationCompilerProvider<TContext> compilerProvider) { if (compilerProvider == null) { compiler_provider = (serializer, type) => new DelegateSerializationCompiler<TContext> (serializer, type); } else { compiler_provider = compilerProvider; } } public void Serialize<TObject> (TObject obj, XmlWriter writer) { Serialize (obj, writer, default (TContext)); } public void Serialize<TObject> (TObject obj, XmlWriter writer, TContext context) { if (writer == null) throw new ArgumentNullException ("writer"); SerializeCore (obj, writer, context); } public void Serialize<TObject> (TObject obj, Stream stream) { Serialize (obj, stream, null); } public void Serialize<TObject> (TObject obj, Stream stream, XmlSerializationOptions<TContext> options) { if (stream == null) throw new ArgumentNullException ("stream"); var serializationOptions = new XmlSerializationOptions(options); using (var writer = XmlWriter.Create (stream, new XmlWriterSettings { Encoding = serializationOptions.Encoding, OmitXmlDeclaration = true })) { WriteXmlDeclaration (writer, serializationOptions); SerializeCore (obj, writer, serializationOptions.Context); } } public byte[] GetBytes<TObject> (TObject obj) { return GetBytes (obj, null); } public byte[] GetBytes<TObject> (TObject obj, XmlSerializationOptions<TContext> options) { var serializationOptions = new XmlSerializationOptions(options); using (var stream = new MemoryStream ()) { using (var writer = XmlWriter.Create (stream, new XmlWriterSettings { Encoding = serializationOptions.Encoding ?? Helper.UTF8Unsigned, OmitXmlDeclaration = serializationOptions.XmlDeclarationType == XmlDeclarationType.None})) { WriteXmlDeclaration (writer, serializationOptions); SerializeCore (obj, writer, serializationOptions.Context); } return stream.ToArray (); } } public string GetString<TObject> (TObject obj) { return GetString (obj, null); } public string GetString<TObject> (TObject obj, XmlSerializationOptions<TContext> options) { if (options == null) { options = new XmlSerializationOptions<TContext> (); } var encoding = options.Encoding ?? Helper.UTF8Unsigned; return encoding.GetString (GetBytes (obj, options)); } void WriteXmlDeclaration (XmlWriter writer, XmlSerializationOptions options) { switch (options.XmlDeclarationType) { case XmlDeclarationType.Version: writer.WriteProcessingInstruction ("xml", @"version=""1.0"""); break; case XmlDeclarationType.VersionAndEncoding: writer.WriteProcessingInstruction ("xml", string.Format( @"version=""1.0"" encoding=""{0}""", options.Encoding.HeaderName)); break; } } void SerializeCore<TObject> (TObject obj, XmlWriter writer, TContext context) { Serialize (obj, new XmlSerializationContext<TContext> (this, writer, context)); } internal void Serialize<TObject> (TObject obj, XmlSerializationContext<TContext> context) { if (obj == null) throw new ArgumentNullException ("obj"); var serializer = GetCompilerForType (typeof (TObject)).TypeSerializer; serializer (obj, context); } internal void AutoSerializeObjectStart<TObject> (TObject obj, XmlSerializationContext<TContext> context) { var serializer = GetCompilerForType (typeof (TObject)).TypeStartAutoSerializer; serializer (obj, context); } internal void AutoSerializeObjectEnd<TObject> (TObject obj, XmlSerializationContext<TContext> context) { var serializer = GetCompilerForType (typeof (TObject)).TypeEndAutoSerializer; serializer (obj, context); } internal void AutoSerializeMembers<TObject> (TObject obj, XmlSerializationContext<TContext> context) { var serialzer = GetCompilerForType (typeof (TObject)).MemberAutoSerializer; serialzer (obj, context); } internal SerializationCompiler<TContext> GetCompilerForType (Type type) { SerializationCompiler<TContext> compiler; if (!compilers.TryGetValue (type, out compiler)) { compiler = compiler_provider (this, type); compilers[type] = compiler; } return compiler; } struct XmlSerializationOptions { public readonly Encoding Encoding; public readonly TContext Context; public readonly XmlDeclarationType XmlDeclarationType; public XmlSerializationOptions (XmlSerializationOptions<TContext> options) { if (options == null) { Encoding = Helper.UTF8Unsigned; Context = default (TContext); XmlDeclarationType = 0; } else { Encoding = options.Encoding ?? Helper.UTF8Unsigned; Context = options.Context; XmlDeclarationType = options.XmlDeclarationType; } } } } }
// Artist.cs // // Copyright (c) 2008 Scott Peterson <lunchtimemama@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Xml; namespace MusicBrainz { public sealed class Artist : MusicBrainzEntity { #region Private const string EXTENSION = "artist"; ArtistReleaseType artist_release_type = DefaultArtistReleaseType; ArtistType? type; ReadOnlyCollection<Release> releases; bool have_all_releases; #endregion #region Constructors Artist (string id) : base (id, null) { } Artist (string id, ArtistReleaseType artist_release_type) : base (id, "&inc=" + artist_release_type.ToString ()) { have_all_releases = true; this.artist_release_type = artist_release_type; } internal Artist (XmlReader reader) : base (reader, false) { } #endregion #region Protected internal override string UrlExtension { get { return EXTENSION; } } internal override void CreateIncCore (StringBuilder builder) { AppendIncParameters (builder, artist_release_type.ToString ()); base.CreateIncCore (builder); } internal override void LoadMissingDataCore () { Artist artist = new Artist (Id); type = artist.GetArtistType (); base.LoadMissingDataCore (artist); } internal override void ProcessAttributes (XmlReader reader) { switch (reader ["type"]) { case "Group": type = ArtistType.Group; break; case "Person": type = ArtistType.Person; break; } } internal override void ProcessXmlCore (XmlReader reader) { switch (reader.Name) { case "release-list": if (reader.ReadToDescendant ("release")) { List<Release> releases = new List<Release> (); do releases.Add (new Release (reader.ReadSubtree ())); while (reader.ReadToNextSibling ("release")); this.releases = releases.AsReadOnly (); } break; default: base.ProcessXmlCore (reader); break; } } #endregion #region Public static ArtistReleaseType default_artist_release_type = new ArtistReleaseType (ReleaseStatus.Official, ReleaseArtistType.SingleArtist); public static ArtistReleaseType DefaultArtistReleaseType { get { return default_artist_release_type; } set { if (value == null) throw new ArgumentNullException ("value"); default_artist_release_type = value; } } public ArtistReleaseType ArtistReleaseType { get { return artist_release_type; } set { if (artist_release_type == value) { return; } artist_release_type = value; releases = null; have_all_releases = false; } } [Queryable ("arid")] public override string Id { get { return base.Id; } } [Queryable ("artist")] public override string GetName () { return base.GetName (); } [Queryable ("artype")] public ArtistType GetArtistType () { return GetPropertyOrDefault (ref type, ArtistType.Unknown); } public ReadOnlyCollection<Release> GetReleases () { return releases ?? (have_all_releases ? releases = new ReadOnlyCollection<Release> (new Release [0]) : new Artist (Id, ArtistReleaseType).GetReleases ()); } public ReadOnlyCollection<Release> GetReleases (ArtistReleaseType artistReleaseType) { return new Artist (Id, artistReleaseType).GetReleases (); } #endregion #region Static public static Artist Get (string id) { if (id == null) throw new ArgumentNullException ("id"); return new Artist (id); } public static Query<Artist> Query (string name) { if (name == null) throw new ArgumentNullException ("name"); return new Query<Artist> (EXTENSION, CreateNameParameter (name)); } public static Query<Artist> QueryLucene (string luceneQuery) { if (luceneQuery == null) throw new ArgumentNullException ("luceneQuery"); return new Query<Artist> (EXTENSION, CreateLuceneParameter (luceneQuery)); } public static implicit operator string (Artist artist) { return artist.ToString (); } #endregion } #region Ancillary Types public enum ArtistType { Unknown, Group, Person } public enum ReleaseArtistType { VariousArtists, SingleArtist } public sealed class ArtistReleaseType { string str; public ArtistReleaseType (ReleaseType type, ReleaseArtistType artistType) : this ((Enum)type, artistType) { } public ArtistReleaseType (ReleaseStatus status, ReleaseArtistType artistType) : this ((Enum)status, artistType) { } public ArtistReleaseType (ReleaseType type, ReleaseStatus status, ReleaseArtistType artistType) { StringBuilder builder = new StringBuilder (); Format (builder, type, artistType); builder.Append ('+'); Format (builder, status, artistType); str = builder.ToString (); } ArtistReleaseType (Enum enumeration, ReleaseArtistType artistType) { StringBuilder builder = new StringBuilder (); Format (builder, enumeration, artistType); str = builder.ToString (); } static void Format (StringBuilder builder, Enum enumeration, ReleaseArtistType artistType) { builder.Append (artistType == ReleaseArtistType.VariousArtists ? "va-" : "sa-"); Utils.EnumToString (builder, enumeration.ToString ()); } public override string ToString () { return str; } public override bool Equals (object o) { return this == o as ArtistReleaseType; } public static bool operator ==(ArtistReleaseType artistReleaseType1, ArtistReleaseType artistReleaseType2) { if (Object.ReferenceEquals (artistReleaseType1, null)) { return Object.ReferenceEquals (artistReleaseType2, null); } return !Object.ReferenceEquals (artistReleaseType2, null) && artistReleaseType1.str == artistReleaseType2.str; } public static bool operator !=(ArtistReleaseType artistReleaseType1, ArtistReleaseType artistReleaseType2) { return !(artistReleaseType1 == artistReleaseType2); } public override int GetHashCode () { return str.GetHashCode (); } } #endregion }
//Credits to Trelli for base using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LeagueSharp; using LeagueSharp.Common; using System.Reflection; namespace Skin_Changer { class Program { public static int currSkinId = 0; public static int tempSkinId = 0; public static Dictionary<string, int> numSkins = new Dictionary<string, int>(); public static Menu Config; public static bool changedForm = false; public static Obj_AI_Hero skinTarget = null; static void Main(string[] args) { CustomEvents.Game.OnGameLoad += Game_OnGameLoad; } public static void Game_OnGameLoad(EventArgs args) { Game.PrintChat( string.Format( "{0} v{1} Skin Changer - Parable of the cheap man by MetaPhorce.", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version )); //Skin Dictionary numSkins.Add("Aatrox", 2); numSkins.Add("Ahri", 4); numSkins.Add("Akali", 6); numSkins.Add("Alistar", 7); numSkins.Add("Amumu", 7); numSkins.Add("Anivia", 5); numSkins.Add("Annie", 8); numSkins.Add("Ashe", 6); numSkins.Add("Azir", 1); numSkins.Add("Blitzcrank", 7); numSkins.Add("Brand", 4); numSkins.Add("Braum", 1); numSkins.Add("Caitlyn", 6); numSkins.Add("Cassiopeia", 4); numSkins.Add("Chogath", 5); numSkins.Add("Corki", 7); numSkins.Add("Darius", 4); numSkins.Add("Diana", 2); numSkins.Add("Draven", 5); numSkins.Add("DrMundo", 7); numSkins.Add("Elise", 2); numSkins.Add("Evelynn", 4); numSkins.Add("Ezreal", 7); numSkins.Add("Fiddlesticks", 8); numSkins.Add("Fiora", 3); numSkins.Add("Fizz", 4); numSkins.Add("Galio", 4); numSkins.Add("Gangplank", 6); numSkins.Add("Garen", 6); numSkins.Add("Gnar", 1); numSkins.Add("Gragas", 8); numSkins.Add("Graves", 5); numSkins.Add("Hecarim", 5); numSkins.Add("Heimerdinger", 7); numSkins.Add("Irelia", 4); numSkins.Add("Janna", 6); numSkins.Add("JarvanIV", 6); numSkins.Add("Jax", 8); numSkins.Add("Jayce", 2); numSkins.Add("Jinx", 1); numSkins.Add("Kalista", 1); numSkins.Add("Karma", 4); numSkins.Add("Karthus", 5); numSkins.Add("Kassadin", 4); numSkins.Add("Katarina", 7); numSkins.Add("Kayle", 7); numSkins.Add("Kennen", 5); numSkins.Add("Khazix", 3); numSkins.Add("KogMaw", 8); numSkins.Add("Leblanc", 4); numSkins.Add("LeeSin", 6); numSkins.Add("Leona", 4); numSkins.Add("Lissandra", 2); numSkins.Add("Lucian", 2); numSkins.Add("Lulu", 4); numSkins.Add("Lux", 5); numSkins.Add("Malphite", 6); numSkins.Add("Malzahar", 4); numSkins.Add("Maokai", 5); numSkins.Add("Masteryi", 5); numSkins.Add("MasterYi", 5); numSkins.Add("MissFortune", 7); numSkins.Add("MonkeyKing", 4); numSkins.Add("Mordekaiser", 4); numSkins.Add("Morgana", 5); numSkins.Add("Nami", 2); numSkins.Add("Nasus", 5); numSkins.Add("Nautilus", 3); numSkins.Add("Nidalee", 6); numSkins.Add("Nocturne", 5); numSkins.Add("Nunu", 6); numSkins.Add("Olaf", 4); numSkins.Add("Orianna", 4); numSkins.Add("Pantheon", 6); numSkins.Add("Poppy", 6); numSkins.Add("Quinn", 2); numSkins.Add("Rammus", 6); numSkins.Add("Renekton", 6); numSkins.Add("Rengar", 2); numSkins.Add("Riven", 5); numSkins.Add("Rumble", 3); numSkins.Add("Ryze", 8); numSkins.Add("Sejuani", 4); numSkins.Add("Shaco", 6); numSkins.Add("Shen", 6); numSkins.Add("Shyvana", 5); numSkins.Add("Singed", 6); numSkins.Add("Sion", 4); numSkins.Add("Sivir", 6); numSkins.Add("Skarner", 3); numSkins.Add("Sona", 5); numSkins.Add("Soraka", 4); numSkins.Add("Swain", 3); numSkins.Add("Syndra", 2); numSkins.Add("Talon", 3); numSkins.Add("Taric", 3); numSkins.Add("Teemo", 7); numSkins.Add("Thresh", 2); numSkins.Add("Tristana", 6); numSkins.Add("Trundle", 4); numSkins.Add("Tryndamere", 6); numSkins.Add("TwistedFate", 8); numSkins.Add("Twitch", 6); numSkins.Add("Udyr", 3); numSkins.Add("Urgot", 3); numSkins.Add("Varus", 3); numSkins.Add("Vayne", 5); numSkins.Add("Veigar", 8); numSkins.Add("Velkoz", 1); numSkins.Add("Viktor", 3); numSkins.Add("Vi", 3); numSkins.Add("Vladimir", 6); numSkins.Add("Volibear", 4); numSkins.Add("Warwick", 7); numSkins.Add("Xerath", 3); numSkins.Add("XinZhao", 5); numSkins.Add("Yasuo", 2); numSkins.Add("Yorick", 2); numSkins.Add("Zac", 1); numSkins.Add("Zed", 3); numSkins.Add("Ziggs", 4); numSkins.Add("Zilean", 4); numSkins.Add("Zyra", 3); Config = new Menu("SkinChanger", "SkinChanger", true); var ChangeSkin = Config.AddItem(new MenuItem("CycleSkins", "CycleSkins!").SetValue(new KeyBind("9".ToCharArray()[0], KeyBindType.Toggle))); Config.AddItem(new MenuItem("cChange", "Select champ to change (LftClk)").SetValue(new KeyBind("I".ToCharArray()[0], KeyBindType.Toggle))); ChangeSkin.ValueChanged += delegate(object sender, OnValueChangeEventArgs EventArgs) { if (skinTarget != null && Config.Item("cChange").GetValue<KeyBind>().Active) { if (numSkins[skinTarget.ChampionName] > tempSkinId) tempSkinId++; else tempSkinId = 0; GenerateSkinPacket(skinTarget.ChampionName, tempSkinId); } else { if (numSkins[ObjectManager.Player.ChampionName] > currSkinId) currSkinId++; else currSkinId = 0; GenerateSkinPacket(ObjectManager.Player.BaseSkinName, currSkinId); } }; Config.AddToMainMenu(); Game.OnGameProcessPacket += OnGameProcessPacket; Game.OnGameUpdate += UpdateGame; Game.OnWndProc += Game_OnWndProc; } public static void GenerateSkinPacket(string currentChampion, int skinNumber) { int netID; if (skinTarget != null && Config.Item("cChange").GetValue<KeyBind>().Active) { netID = skinTarget.NetworkId; } else { netID = ObjectManager.Player.NetworkId; } GamePacket model = Packet.S2C.UpdateModel.Encoded(new Packet.S2C.UpdateModel.Struct(netID, skinNumber, currentChampion)); model.Process(PacketChannel.S2C); } private static void OnGameProcessPacket(GamePacketEventArgs args) { if (PacketChannel.S2C == args.Channel && args.PacketData[0] == Packet.S2C.UpdateModel.Header) // Update Packet recieved. { var decoded = Packet.S2C.UpdateModel.Decoded(args.PacketData); if(decoded.NetworkId == ObjectManager.Player.NetworkId) { changedForm = true; } } } private static void UpdateGame(EventArgs args) { //Game.PrintChat("Base skin is: " + ObjectManager.Player.BaseSkinName); //Game.PrintChat("skin is: " + ObjectManager.Player.SkinName); if (changedForm == true) { if(ObjectManager.Player.ChampionName == "Udyr") { GenerateSkinPacket(ObjectManager.Player.SkinName, currSkinId); } else { GenerateSkinPacket(ObjectManager.Player.BaseSkinName, currSkinId); } changedForm = false; } } private static void Game_OnWndProc(WndEventArgs args) { if (args.Msg != (uint)WindowsMessages.WM_LBUTTONDOWN || !Config.Item("cChange").GetValue<KeyBind>().Active) { //Game.PrintChat("Wasn't true: " + Config.Item("cChange").GetValue<KeyBind>().Active); return; } skinTarget = null; foreach (var hero in ObjectManager.Get<Obj_AI_Hero>()) { if (SharpDX.Vector2.Distance(Game.CursorPos.To2D(), hero.ServerPosition.To2D()) < 300 && !hero.IsMe) { Game.PrintChat(hero.ChampionName + " selected. You may now cycle their skin!"); skinTarget = hero; tempSkinId = 0; //reset for each new champ selected return; } } } } }
using System; /// <summary> /// char.IsUpper(string, int) /// Indicates whether the character at the specified position in a specified string is categorized /// as a uppercase letter character. /// </summary> public class CharIsUpper { private const int c_MIN_STR_LEN = 2; private const int c_MAX_STR_LEN = 256; public static int Main() { CharIsUpper testObj = new CharIsUpper(); TestLibrary.TestFramework.BeginTestCase("for method: char.IsUpper(string, int)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negaitive]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive tests public bool PosTest1() { //Generate the character for validate char ch = 'a'; return this.DoTest("PosTest1: Lowercase letter character", "P001", "001", "002", ch, false); } public bool PosTest2() { //Generate a non character for validate char ch = 'A'; return this.DoTest("PosTest2: Uppercase letter character.", "P002", "003", "004", ch, true); } public bool PosTest3() { //Generate a non character for validate char ch = TestLibrary.Generator.GetCharNumber(-55); return this.DoTest("PosTest3: Non letter character.", "P003", "005", "006", ch, false); } #endregion #region Helper method for positive tests private bool DoTest(string testDesc, string testId, string errorNum1, string errorNum2, char ch, bool expectedResult) { bool retVal = true; string errorDesc; TestLibrary.TestFramework.BeginScenario(testDesc); try { bool actualResult = char.IsUpper(ch); if (expectedResult != actualResult) { if (expectedResult) { errorDesc = string.Format("Character \\u{0:x} should belong to uppercase letter characters.", (int)ch); } else { errorDesc = string.Format("Character \\u{0:x} does not belong to uppercase letter characters.", (int)ch); } TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nCharacter is \\u{0:x}", ch); TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc); retVal = false; } return retVal; } #endregion #region Negative tests //ArgumentNullException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic)."; string errorDesc; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { index = TestLibrary.Generator.GetInt32(-55); char.IsUpper(null, index); errorDesc = "ArgumentNullException is not thrown as expected, index is " + index; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e + "\n Index is " + index; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //ArgumentOutOfRangeException public bool NegTest2() { bool retVal = true; const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: Index is too great."; string errorDesc; string str = string.Empty; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN); index = str.Length + TestLibrary.Generator.GetInt16(-55); index = str.Length; char.IsUpper(str, index); errorDesc = "ArgumentOutOfRangeException is not thrown as expected"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index); TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTest3: Index is a negative value"; string errorDesc; string str = string.Empty; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN); index = -1 * (TestLibrary.Generator.GetInt16(-55)); char.IsUpper(str, index); errorDesc = "ArgumentOutOfRangeException is not thrown as expected"; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index); TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Reflection.Metadata.Ecma335; using Xunit; namespace System.Reflection.Metadata.Tests { public class HandleTests { [Fact] public void HandleKindsMatchSpecAndDoNotChange() { // These are chosen to match their encoding in metadata tokens as specified by the CLI spec Assert.Equal(0x00, (int)HandleKind.ModuleDefinition); Assert.Equal(0x01, (int)HandleKind.TypeReference); Assert.Equal(0x02, (int)HandleKind.TypeDefinition); Assert.Equal(0x04, (int)HandleKind.FieldDefinition); Assert.Equal(0x06, (int)HandleKind.MethodDefinition); Assert.Equal(0x08, (int)HandleKind.Parameter); Assert.Equal(0x09, (int)HandleKind.InterfaceImplementation); Assert.Equal(0x0A, (int)HandleKind.MemberReference); Assert.Equal(0x0B, (int)HandleKind.Constant); Assert.Equal(0x0C, (int)HandleKind.CustomAttribute); Assert.Equal(0x0E, (int)HandleKind.DeclarativeSecurityAttribute); Assert.Equal(0x11, (int)HandleKind.StandaloneSignature); Assert.Equal(0x14, (int)HandleKind.EventDefinition); Assert.Equal(0x17, (int)HandleKind.PropertyDefinition); Assert.Equal(0x19, (int)HandleKind.MethodImplementation); Assert.Equal(0x1A, (int)HandleKind.ModuleReference); Assert.Equal(0x1B, (int)HandleKind.TypeSpecification); Assert.Equal(0x20, (int)HandleKind.AssemblyDefinition); Assert.Equal(0x26, (int)HandleKind.AssemblyFile); Assert.Equal(0x23, (int)HandleKind.AssemblyReference); Assert.Equal(0x27, (int)HandleKind.ExportedType); Assert.Equal(0x2A, (int)HandleKind.GenericParameter); Assert.Equal(0x2B, (int)HandleKind.MethodSpecification); Assert.Equal(0x2C, (int)HandleKind.GenericParameterConstraint); Assert.Equal(0x28, (int)HandleKind.ManifestResource); Assert.Equal(0x70, (int)HandleKind.UserString); // These values were chosen arbitrarily, but must still never change Assert.Equal(0x71, (int)HandleKind.Blob); Assert.Equal(0x72, (int)HandleKind.Guid); Assert.Equal(0x78, (int)HandleKind.String); Assert.Equal(0x7c, (int)HandleKind.NamespaceDefinition); } [Fact] public void HandleConversionGivesCorrectKind() { var expectedKinds = new SortedSet<HandleKind>((HandleKind[])Enum.GetValues(typeof(HandleKind))); Action<Handle, HandleKind> assert = (handle, expectedKind) => { Assert.False(expectedKinds.Count == 0, "Repeat handle in tests below."); Assert.Equal(expectedKind, handle.Kind); expectedKinds.Remove(expectedKind); }; assert(default(ModuleDefinitionHandle), HandleKind.ModuleDefinition); assert(default(AssemblyDefinitionHandle), HandleKind.AssemblyDefinition); assert(default(InterfaceImplementationHandle), HandleKind.InterfaceImplementation); assert(default(MethodDefinitionHandle), HandleKind.MethodDefinition); assert(default(MethodSpecificationHandle), HandleKind.MethodSpecification); assert(default(TypeDefinitionHandle), HandleKind.TypeDefinition); assert(default(ExportedTypeHandle), HandleKind.ExportedType); assert(default(TypeReferenceHandle), HandleKind.TypeReference); assert(default(TypeSpecificationHandle), HandleKind.TypeSpecification); assert(default(MemberReferenceHandle), HandleKind.MemberReference); assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition); assert(default(EventDefinitionHandle), HandleKind.EventDefinition); assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition); assert(default(StandaloneSignatureHandle), HandleKind.StandaloneSignature); assert(default(MemberReferenceHandle), HandleKind.MemberReference); assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition); assert(default(EventDefinitionHandle), HandleKind.EventDefinition); assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition); assert(default(ParameterHandle), HandleKind.Parameter); assert(default(GenericParameterHandle), HandleKind.GenericParameter); assert(default(GenericParameterConstraintHandle), HandleKind.GenericParameterConstraint); assert(default(ModuleReferenceHandle), HandleKind.ModuleReference); assert(default(CustomAttributeHandle), HandleKind.CustomAttribute); assert(default(DeclarativeSecurityAttributeHandle), HandleKind.DeclarativeSecurityAttribute); assert(default(ManifestResourceHandle), HandleKind.ManifestResource); assert(default(ConstantHandle), HandleKind.Constant); assert(default(ManifestResourceHandle), HandleKind.ManifestResource); assert(default(MethodImplementationHandle), HandleKind.MethodImplementation); assert(default(AssemblyFileHandle), HandleKind.AssemblyFile); assert(default(StringHandle), HandleKind.String); assert(default(AssemblyReferenceHandle), HandleKind.AssemblyReference); assert(default(UserStringHandle), HandleKind.UserString); assert(default(GuidHandle), HandleKind.Guid); assert(default(BlobHandle), HandleKind.Blob); assert(default(NamespaceDefinitionHandle), HandleKind.NamespaceDefinition); assert(default(DocumentHandle), HandleKind.Document); assert(default(MethodDebugInformationHandle), HandleKind.MethodDebugInformation); assert(default(LocalScopeHandle), HandleKind.LocalScope); assert(default(LocalConstantHandle), HandleKind.LocalConstant); assert(default(ImportScopeHandle), HandleKind.ImportScope); assert(default(CustomDebugInformationHandle), HandleKind.CustomDebugInformation); Assert.True(expectedKinds.Count == 0, "Some handles are missing from this test: " + string.Join("," + Environment.NewLine, expectedKinds)); } [Fact] public void Conversions_Handles() { Assert.Equal(1, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 0x00ffffff)).RowId); Assert.Equal(1, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 1)).RowId); Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 0x00ffffff)).RowId); Assert.Equal(1, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 1)).RowId); Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId); Assert.Equal(1, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 1)).RowId); Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId); Assert.Equal(1, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 1)).RowId); Assert.Equal(0x00ffffff, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 0x00ffffff)).RowId); Assert.Equal(1, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 0x00ffffff)).RowId); Assert.Equal(1, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 1)).RowId); Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 0x00ffffff)).RowId); Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 1)).RowId); Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId); Assert.Equal(1, ((ConstantHandle)new Handle((byte)HandleType.Constant, 1)).RowId); Assert.Equal(0x00ffffff, ((ConstantHandle)new Handle((byte)HandleType.Constant, 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 0x00ffffff)).RowId); Assert.Equal(1, ((UserStringHandle)new Handle((byte)HandleType.UserString, 1)).GetHeapOffset()); Assert.Equal(0x00ffffff, ((UserStringHandle)new Handle((byte)HandleType.UserString, 0x00ffffff)).GetHeapOffset()); Assert.Equal(1, ((GuidHandle)new Handle((byte)HandleType.Guid, 1)).Index); Assert.Equal(0x1fffffff, ((GuidHandle)new Handle((byte)HandleType.Guid, 0x1fffffff)).Index); Assert.Equal(1, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 0x1fffffff)).GetHeapOffset()); Assert.Equal(1, ((StringHandle)new Handle((byte)HandleType.String, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((StringHandle)new Handle((byte)HandleType.String, 0x1fffffff)).GetHeapOffset()); Assert.Equal(1, ((BlobHandle)new Handle((byte)HandleType.Blob, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((BlobHandle)new Handle((byte)HandleType.Blob, 0x1fffffff)).GetHeapOffset()); } [Fact] public void Conversions_EntityHandles() { Assert.Equal(1, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 0x00ffffff)).RowId); Assert.Equal(1, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 1)).RowId); Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 0x00ffffff)).RowId); Assert.Equal(1, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 1)).RowId); Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId); Assert.Equal(1, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 1)).RowId); Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId); Assert.Equal(1, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 1)).RowId); Assert.Equal(0x00ffffff, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 0x00ffffff)).RowId); Assert.Equal(1, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 0x00ffffff)).RowId); Assert.Equal(1, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 1)).RowId); Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 0x00ffffff)).RowId); Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 1)).RowId); Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId); Assert.Equal(1, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 1)).RowId); Assert.Equal(0x00ffffff, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 0x00ffffff)).RowId); } [Fact] public void Conversions_VirtualHandles() { Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Module ), 1)); Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Assembly ), 1)); Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.InterfaceImpl), 1)); Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodDef ), 1)); Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodSpec), 1)); Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeDef ), 1)); Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ExportedType), 1)); Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeRef), 1)); Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeSpec), 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1)); Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Signature), 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1)); Assert.Throws<InvalidCastException>(() => (ParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ParamDef), 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParam), 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParamConstraint), 1)); Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ModuleRef), 1)); Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.CustomAttribute), 1)); Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.DeclSecurity), 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1)); Assert.Throws<InvalidCastException>(() => (ConstantHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Constant), 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1)); Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.File), 1)); Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodImpl), 1)); Assert.Throws<InvalidCastException>(() => (UserStringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.UserString), 1)); Assert.Throws<InvalidCastException>(() => (GuidHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Guid), 1)); var x1 = (AssemblyReferenceHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.AssemblyRef), 1); var x2 = (StringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.String), 1); var x3 = (BlobHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Blob), 1); var x4 = (NamespaceDefinitionHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Namespace), 1); } [Fact] public void Conversions_VirtualEntityHandles() { Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Module | 1)); Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Assembly | 1)); Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.InterfaceImpl | 1)); Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodDef | 1)); Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodSpec | 1)); Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeDef | 1)); Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ExportedType | 1)); Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeRef | 1)); Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeSpec | 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1)); Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Signature | 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1)); Assert.Throws<InvalidCastException>(() => (ParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ParamDef | 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParam | 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParamConstraint | 1)); Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ModuleRef | 1)); Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.CustomAttribute | 1)); Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.DeclSecurity | 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1)); Assert.Throws<InvalidCastException>(() => (ConstantHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Constant | 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1)); Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.File | 1)); Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodImpl | 1)); var x1 = (AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.AssemblyRef | 1); } [Fact] public void IsNil() { Assert.False(ModuleDefinitionHandle.FromRowId(1).IsNil); Assert.False(AssemblyDefinitionHandle.FromRowId(1).IsNil); Assert.False(InterfaceImplementationHandle.FromRowId(1).IsNil); Assert.False(MethodDefinitionHandle.FromRowId(1).IsNil); Assert.False(MethodSpecificationHandle.FromRowId(1).IsNil); Assert.False(TypeDefinitionHandle.FromRowId(1).IsNil); Assert.False(ExportedTypeHandle.FromRowId(1).IsNil); Assert.False(TypeReferenceHandle.FromRowId(1).IsNil); Assert.False(TypeSpecificationHandle.FromRowId(1).IsNil); Assert.False(MemberReferenceHandle.FromRowId(1).IsNil); Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil); Assert.False(EventDefinitionHandle.FromRowId(1).IsNil); Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil); Assert.False(StandaloneSignatureHandle.FromRowId(1).IsNil); Assert.False(MemberReferenceHandle.FromRowId(1).IsNil); Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil); Assert.False(EventDefinitionHandle.FromRowId(1).IsNil); Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil); Assert.False(ParameterHandle.FromRowId(1).IsNil); Assert.False(GenericParameterHandle.FromRowId(1).IsNil); Assert.False(GenericParameterConstraintHandle.FromRowId(1).IsNil); Assert.False(ModuleReferenceHandle.FromRowId(1).IsNil); Assert.False(CustomAttributeHandle.FromRowId(1).IsNil); Assert.False(DeclarativeSecurityAttributeHandle.FromRowId(1).IsNil); Assert.False(ManifestResourceHandle.FromRowId(1).IsNil); Assert.False(ConstantHandle.FromRowId(1).IsNil); Assert.False(ManifestResourceHandle.FromRowId(1).IsNil); Assert.False(AssemblyFileHandle.FromRowId(1).IsNil); Assert.False(MethodImplementationHandle.FromRowId(1).IsNil); Assert.False(AssemblyReferenceHandle.FromRowId(1).IsNil); Assert.False(((EntityHandle)ModuleDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)InterfaceImplementationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodSpecificationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ExportedTypeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeSpecificationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)StandaloneSignatureHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ParameterHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)GenericParameterHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)GenericParameterConstraintHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ModuleReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)CustomAttributeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ConstantHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyFileHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodImplementationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyReferenceHandle.FromRowId(1)).IsNil); Assert.False(StringHandle.FromOffset(1).IsNil); Assert.False(BlobHandle.FromOffset(1).IsNil); Assert.False(UserStringHandle.FromOffset(1).IsNil); Assert.False(GuidHandle.FromIndex(1).IsNil); Assert.False(DocumentNameBlobHandle.FromOffset(1).IsNil); Assert.False(((Handle)StringHandle.FromOffset(1)).IsNil); Assert.False(((Handle)BlobHandle.FromOffset(1)).IsNil); Assert.False(((Handle)UserStringHandle.FromOffset(1)).IsNil); Assert.False(((Handle)GuidHandle.FromIndex(1)).IsNil); Assert.False(((BlobHandle)DocumentNameBlobHandle.FromOffset(1)).IsNil); Assert.True(ModuleDefinitionHandle.FromRowId(0).IsNil); Assert.True(AssemblyDefinitionHandle.FromRowId(0).IsNil); Assert.True(InterfaceImplementationHandle.FromRowId(0).IsNil); Assert.True(MethodDefinitionHandle.FromRowId(0).IsNil); Assert.True(MethodSpecificationHandle.FromRowId(0).IsNil); Assert.True(TypeDefinitionHandle.FromRowId(0).IsNil); Assert.True(ExportedTypeHandle.FromRowId(0).IsNil); Assert.True(TypeReferenceHandle.FromRowId(0).IsNil); Assert.True(TypeSpecificationHandle.FromRowId(0).IsNil); Assert.True(MemberReferenceHandle.FromRowId(0).IsNil); Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil); Assert.True(EventDefinitionHandle.FromRowId(0).IsNil); Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil); Assert.True(StandaloneSignatureHandle.FromRowId(0).IsNil); Assert.True(MemberReferenceHandle.FromRowId(0).IsNil); Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil); Assert.True(EventDefinitionHandle.FromRowId(0).IsNil); Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil); Assert.True(ParameterHandle.FromRowId(0).IsNil); Assert.True(GenericParameterHandle.FromRowId(0).IsNil); Assert.True(GenericParameterConstraintHandle.FromRowId(0).IsNil); Assert.True(ModuleReferenceHandle.FromRowId(0).IsNil); Assert.True(CustomAttributeHandle.FromRowId(0).IsNil); Assert.True(DeclarativeSecurityAttributeHandle.FromRowId(0).IsNil); Assert.True(ManifestResourceHandle.FromRowId(0).IsNil); Assert.True(ConstantHandle.FromRowId(0).IsNil); Assert.True(ManifestResourceHandle.FromRowId(0).IsNil); Assert.True(AssemblyFileHandle.FromRowId(0).IsNil); Assert.True(MethodImplementationHandle.FromRowId(0).IsNil); Assert.True(AssemblyReferenceHandle.FromRowId(0).IsNil); Assert.True(((EntityHandle)ModuleDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)InterfaceImplementationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodSpecificationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ExportedTypeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeSpecificationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)StandaloneSignatureHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ParameterHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)GenericParameterHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)GenericParameterConstraintHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ModuleReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)CustomAttributeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ConstantHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyFileHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodImplementationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyReferenceHandle.FromRowId(0)).IsNil); // heaps: Assert.True(StringHandle.FromOffset(0).IsNil); Assert.True(BlobHandle.FromOffset(0).IsNil); Assert.True(UserStringHandle.FromOffset(0).IsNil); Assert.True(GuidHandle.FromIndex(0).IsNil); Assert.True(DocumentNameBlobHandle.FromOffset(0).IsNil); Assert.True(((Handle)StringHandle.FromOffset(0)).IsNil); Assert.True(((Handle)BlobHandle.FromOffset(0)).IsNil); Assert.True(((Handle)UserStringHandle.FromOffset(0)).IsNil); Assert.True(((Handle)GuidHandle.FromIndex(0)).IsNil); Assert.True(((BlobHandle)DocumentNameBlobHandle.FromOffset(0)).IsNil); // virtual: Assert.False(AssemblyReferenceHandle.FromVirtualIndex(0).IsNil); Assert.False(StringHandle.FromVirtualIndex(0).IsNil); Assert.False(BlobHandle.FromVirtualIndex(0, 0).IsNil); Assert.False(((Handle)AssemblyReferenceHandle.FromVirtualIndex(0)).IsNil); Assert.False(((Handle)StringHandle.FromVirtualIndex(0)).IsNil); Assert.False(((Handle)BlobHandle.FromVirtualIndex(0, 0)).IsNil); } [Fact] public void IsVirtual() { Assert.False(AssemblyReferenceHandle.FromRowId(1).IsVirtual); Assert.False(StringHandle.FromOffset(1).IsVirtual); Assert.False(BlobHandle.FromOffset(1).IsVirtual); Assert.True(AssemblyReferenceHandle.FromVirtualIndex(0).IsVirtual); Assert.True(StringHandle.FromVirtualIndex(0).IsVirtual); Assert.True(BlobHandle.FromVirtualIndex(0, 0).IsVirtual); } [Fact] public void StringKinds() { var str = StringHandle.FromOffset(123); Assert.Equal(StringKind.Plain, str.StringKind); Assert.False(str.IsVirtual); Assert.Equal(123, str.GetHeapOffset()); var vstr = StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.AttributeTargets); Assert.Equal(StringKind.Virtual, vstr.StringKind); Assert.True(vstr.IsVirtual); Assert.Equal(StringHandle.VirtualIndex.AttributeTargets, vstr.GetVirtualIndex()); var dot = StringHandle.FromOffset(123).WithDotTermination(); Assert.Equal(StringKind.DotTerminated, dot.StringKind); Assert.False(dot.IsVirtual); Assert.Equal(123, dot.GetHeapOffset()); var winrtPrefix = StringHandle.FromOffset(123).WithWinRTPrefix(); Assert.Equal(StringKind.WinRTPrefixed, winrtPrefix.StringKind); Assert.True(winrtPrefix.IsVirtual); Assert.Equal(123, winrtPrefix.GetHeapOffset()); } [Fact] public void NamespaceKinds() { var full = NamespaceDefinitionHandle.FromFullNameOffset(123); Assert.False(full.IsVirtual); Assert.Equal(123, full.GetHeapOffset()); var virtual1 = NamespaceDefinitionHandle.FromVirtualIndex(123); Assert.True(virtual1.IsVirtual); var virtual2 = NamespaceDefinitionHandle.FromVirtualIndex((UInt32.MaxValue >> 3)); Assert.True(virtual2.IsVirtual); Assert.Throws<BadImageFormatException>(() => NamespaceDefinitionHandle.FromVirtualIndex((UInt32.MaxValue >> 3) + 1)); } [Fact] public void HandleKindHidesSpecialStringAndNamespaces() { foreach (int virtualBit in new[] { 0, (int)HandleType.VirtualBit }) { for (int i = 0; i <= sbyte.MaxValue; i++) { Handle handle = new Handle((byte)(virtualBit | i), 0); Assert.True(handle.IsNil ^ handle.IsVirtual); Assert.Equal(virtualBit != 0, handle.IsVirtual); Assert.Equal(handle.EntityHandleType, (uint)i << TokenTypeIds.RowIdBitCount); switch (i) { // String has two extra bits to represent its kind that are hidden from the handle type case (int)HandleKind.String: case (int)HandleKind.String + 1: case (int)HandleKind.String + 2: case (int)HandleKind.String + 3: Assert.Equal(HandleKind.String, handle.Kind); break; // all other types surface token type directly. default: Assert.Equal((int)handle.Kind, i); break; } } } } [Fact] public void MethodDefToDebugInfo() { Assert.Equal( MethodDefinitionHandle.FromRowId(123).ToDebugInformationHandle(), MethodDebugInformationHandle.FromRowId(123)); Assert.Equal( MethodDebugInformationHandle.FromRowId(123).ToDefinitionHandle(), MethodDefinitionHandle.FromRowId(123)); } } }
// 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.Collections.Generic; namespace Microsoft.Test.ModuleCore { //////////////////////////////////////////////////////////////// // KeywordParser // //////////////////////////////////////////////////////////////// public class KeywordParser { //Enum protected enum PARSE { Initial, Keyword, Equal, Value, SingleBegin, SingleEnd, DoubleBegin, DoubleEnd, End } //Accessors //Note: You can override these if you want to leverage our parser (inherit), and change //some of the behavior (without reimplementing it). private static Tokens s_DefaultTokens = new Tokens(); public class Tokens { public string Equal = "="; public string Seperator = ";"; public string SingleQuote = "'"; public string DoubleQuote = "\""; } //Methods static public Dictionary<string, string> ParseKeywords(string str) { return ParseKeywords(str, s_DefaultTokens); } static public Dictionary<string, string> ParseKeywords(string str, Tokens tokens) { PARSE state = PARSE.Initial; int index = 0; int keyStart = 0; InsensitiveDictionary keywords = new InsensitiveDictionary(5); string key = null; if (str != null) { StringBuilder builder = new StringBuilder(str.Length); for (; index < str.Length; index++) { char ch = str[index]; switch (state) { case PARSE.Initial: if (Char.IsLetterOrDigit(ch)) { keyStart = index; state = PARSE.Keyword; } break; case PARSE.Keyword: if (tokens.Seperator.IndexOf(ch) >= 0) { state = PARSE.Initial; } else if (tokens.Equal.IndexOf(ch) >= 0) { //Note: We have a case-insentive hashtable so we don't have to lowercase key = str.Substring(keyStart, index - keyStart).Trim(); state = PARSE.Equal; } break; case PARSE.Equal: if (Char.IsWhiteSpace(ch)) break; builder.Length = 0; //Note: Since we allow you to alter the tokens, these are not //constant values, so we cannot use a switch statement... if (tokens.SingleQuote.IndexOf(ch) >= 0) { state = PARSE.SingleBegin; } else if (tokens.DoubleQuote.IndexOf(ch) >= 0) { state = PARSE.DoubleBegin; } else if (tokens.Seperator.IndexOf(ch) >= 0) { keywords.Update(key, String.Empty); state = PARSE.Initial; } else { state = PARSE.Value; builder.Append(ch); } break; case PARSE.Value: if (tokens.Seperator.IndexOf(ch) >= 0) { keywords.Update(key, (builder.ToString()).Trim()); state = PARSE.Initial; } else { builder.Append(ch); } break; case PARSE.SingleBegin: if (tokens.SingleQuote.IndexOf(ch) >= 0) state = PARSE.SingleEnd; else builder.Append(ch); break; case PARSE.DoubleBegin: if (tokens.DoubleQuote.IndexOf(ch) >= 0) state = PARSE.DoubleEnd; else builder.Append(ch); break; case PARSE.SingleEnd: if (tokens.SingleQuote.IndexOf(ch) >= 0) { state = PARSE.SingleBegin; builder.Append(ch); } else { keywords.Update(key, builder.ToString()); state = PARSE.End; goto case PARSE.End; } break; case PARSE.DoubleEnd: if (tokens.DoubleQuote.IndexOf(ch) >= 0) { state = PARSE.DoubleBegin; builder.Append(ch); } else { keywords.Update(key, builder.ToString()); state = PARSE.End; goto case PARSE.End; } break; case PARSE.End: if (tokens.Seperator.IndexOf(ch) >= 0) { state = PARSE.Initial; } break; default: throw new TestFailedException("Unhandled State: " + StringEx.ToString(state)); } } switch (state) { case PARSE.Initial: case PARSE.Keyword: case PARSE.End: break; case PARSE.Equal: keywords.Update(key, String.Empty); break; case PARSE.Value: keywords.Update(key, (builder.ToString()).Trim()); break; case PARSE.SingleBegin: case PARSE.DoubleBegin: case PARSE.SingleEnd: case PARSE.DoubleEnd: keywords.Update(key, builder.ToString()); break; default: throw new TestFailedException("Unhandled State: " + StringEx.ToString(state)); } } return keywords; } } }
// 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 Xunit; namespace System.Linq.Tests { public class AggregateTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; Assert.Equal(q.Aggregate((x, y) => x + y), q.Aggregate((x, y) => x + y)); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; Assert.Equal(q.Aggregate((x, y) => x + y), q.Aggregate((x, y) => x + y)); } [Fact] public void EmptySource() { int[] source = { }; Assert.Throws<InvalidOperationException>(() => source.RunOnce().Aggregate((x, y) => x + y)); } [Fact] public void SingleElement() { int[] source = { 5 }; int expected = 5; Assert.Equal(expected, source.Aggregate((x, y) => x + y)); } [Fact] public void SingleElementRunOnce() { int[] source = { 5 }; int expected = 5; Assert.Equal(expected, source.RunOnce().Aggregate((x, y) => x + y)); } [Fact] public void TwoElements() { int[] source = { 5, 6 }; int expected = 11; Assert.Equal(expected, source.Aggregate((x, y) => x + y)); } [Fact] public void MultipleElements() { int[] source = { 5, 6, 0, -4 }; int expected = 7; Assert.Equal(expected, source.Aggregate((x, y) => x + y)); } [Fact] public void MultipleElementsRunOnce() { int[] source = { 5, 6, 0, -4 }; int expected = 7; Assert.Equal(expected, source.RunOnce().Aggregate((x, y) => x + y)); } [Fact] public void EmptySourceAndSeed() { int[] source = { }; long seed = 2; long expected = 2; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void SingleElementAndSeed() { int[] source = { 5 }; long seed = 2; long expected = 10; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void TwoElementsAndSeed() { int[] source = { 5, 6 }; long seed = 2; long expected = 60; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void MultipleElementsAndSeed() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -480; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void MultipleElementsAndSeedRunOnce() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -480; Assert.Equal(expected, source.RunOnce().Aggregate(seed, (x, y) => x * y)); } [Fact] public void NoElementsSeedResultSeletor() { int[] source = { }; long seed = 2; double expected = 7; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void SingleElementSeedResultSelector() { int[] source = { 5 }; long seed = 2; long expected = 15; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void TwoElementsSeedResultSelector() { int[] source = { 5, 6 }; long seed = 2; long expected = 65; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void MultipleElementsSeedResultSelector() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -475; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void MultipleElementsSeedResultSelectorRunOnce() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -475; Assert.Equal(expected, source.RunOnce().Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void NullSource() { Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Aggregate((x, y) => x + y)); Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Aggregate(0, (x, y) => x + y)); Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Aggregate(0, (x, y) => x + y, i => i)); } [Fact] public void NullFunc() { Func<int, int, int> func = null; Assert.Throws<ArgumentNullException>("func", () => Enumerable.Range(0, 3).Aggregate(func)); Assert.Throws<ArgumentNullException>("func", () => Enumerable.Range(0, 3).Aggregate(0, func)); Assert.Throws<ArgumentNullException>("func", () => Enumerable.Range(0, 3).Aggregate(0, func, i => i)); } [Fact] public void NullResultSelector() { Func<int, int> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => Enumerable.Range(0, 3).Aggregate(0, (x, y) => x + y, resultSelector)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; using Spect.Net.Assembler.SyntaxTree; using Spect.Net.Assembler.SyntaxTree.Operations; namespace Spect.Net.Assembler.Test.Parser { [TestClass] public class AluOperationTests : ParserTestBed { [TestMethod] public void AddInstructionWorksAsExpected() { AluOpWorksAsExpected("add a,b", "ADD", "B", "A"); AluOpWorksAsExpected("add a,c", "ADD", "C", "A"); AluOpWorksAsExpected("add a,d", "ADD", "D", "A"); AluOpWorksAsExpected("add a,e", "ADD", "E", "A"); AluOpWorksAsExpected("add a,h", "ADD", "H", "A"); AluOpWorksAsExpected("add a,l", "ADD", "L", "A"); AluOpWorksAsExpected("add a,(hl)", "ADD", "(HL)", "A"); AluOpWorksAsExpected("add a,a", "ADD", "A", "A"); AluOpWorksAsExpected("add a,xh", "ADD", "XH", "A"); AluOpWorksAsExpected("add a,xl", "ADD", "XL", "A"); AluOpWorksAsExpected("add a,yh", "ADD", "YH", "A"); AluOpWorksAsExpected("add a,yl", "ADD", "YL", "A"); AluOpWorksAsExpected("add hl,bc", "ADD", "BC", "HL"); AluOpWorksAsExpected("add hl,de", "ADD", "DE", "HL"); AluOpWorksAsExpected("add hl,hl", "ADD", "HL", "HL"); AluOpWorksAsExpected("add hl,sp", "ADD", "SP", "HL"); AluOpWorksAsExpected("add ix,bc", "ADD", "BC", "IX"); AluOpWorksAsExpected("add ix,de", "ADD", "DE", "IX"); AluOpWorksAsExpected("add ix,ix", "ADD", "IX", "IX"); AluOpWorksAsExpected("add ix,sp", "ADD", "SP", "IX"); AluOpWorksAsExpected("add iy,bc", "ADD", "BC", "IY"); AluOpWorksAsExpected("add iy,de", "ADD", "DE", "IY"); AluOpWorksAsExpected("add iy,iy", "ADD", "IY", "IY"); AluOpWorksAsExpected("add iy,sp", "ADD", "SP", "IY"); AluOpWorksAsExpected("add a,(ix)", "ADD", "A", "IX", null); AluOpWorksAsExpected("add a,(ix+#04)", "ADD", "A", "IX", "+"); AluOpWorksAsExpected("add a,(ix-#04)", "ADD", "A", "IX", "-"); AluOpWorksAsExpected("add a,(iy)", "ADD", "A", "IY", null); AluOpWorksAsExpected("add a,(iy+#04)", "ADD", "A", "IY", "+"); AluOpWorksAsExpected("add a,(iy-#04)", "ADD", "A", "IY", "-"); AluOpWorksAsExpected("add a,#12", "ADD", "A"); AluOpWorksAsExpected("add a,Some", "ADD", "A"); } [TestMethod] public void AdcInstructionWorksAsExpected() { AluOpWorksAsExpected("adc hl,bc", "ADC", "BC", "HL"); AluOpWorksAsExpected("adc hl,de", "ADC", "DE", "HL"); AluOpWorksAsExpected("adc hl,hl", "ADC", "HL", "HL"); AluOpWorksAsExpected("adc hl,sp", "ADC", "SP", "HL"); AluOpWorksAsExpected("adc a,b", "ADC", "B", "A"); AluOpWorksAsExpected("adc a,c", "ADC", "C", "A"); AluOpWorksAsExpected("adc a,d", "ADC", "D", "A"); AluOpWorksAsExpected("adc a,e", "ADC", "E", "A"); AluOpWorksAsExpected("adc a,h", "ADC", "H", "A"); AluOpWorksAsExpected("adc a,l", "ADC", "L", "A"); AluOpWorksAsExpected("adc a,(hl)", "ADC", "(HL)", "A"); AluOpWorksAsExpected("adc a,a", "ADC", "A", "A"); AluOpWorksAsExpected("adc a,xh", "ADC", "XH", "A"); AluOpWorksAsExpected("adc a,xl", "ADC", "XL", "A"); AluOpWorksAsExpected("adc a,yh", "ADC", "YH", "A"); AluOpWorksAsExpected("adc a,yl", "ADC", "YL", "A"); AluOpWorksAsExpected("adc a,(ix)", "ADC", "A", "IX", null); AluOpWorksAsExpected("adc a,(ix+#04)", "ADC", "A", "IX", "+"); AluOpWorksAsExpected("adc a,(ix-#04)", "ADC", "A", "IX", "-"); AluOpWorksAsExpected("adc a,(iy)", "ADC", "A", "IY", null); AluOpWorksAsExpected("adc a,(iy+#04)", "ADC", "A", "IY", "+"); AluOpWorksAsExpected("adc a,(iy-#04)", "ADC", "A", "IY", "-"); AluOpWorksAsExpected("adc a,#12", "ADC", "A"); AluOpWorksAsExpected("adc a,Some", "ADC", "A"); } [TestMethod] public void SubInstructionWorksAsExpected() { AluOpWorksAsExpected2("sub b", "SUB", "B"); AluOpWorksAsExpected2("sub c", "SUB", "C"); AluOpWorksAsExpected2("sub d", "SUB", "D"); AluOpWorksAsExpected2("sub e", "SUB", "E"); AluOpWorksAsExpected2("sub h", "SUB", "H"); AluOpWorksAsExpected2("sub l", "SUB", "L"); AluOpWorksAsExpected2("sub (hl)", "SUB", "(HL)"); AluOpWorksAsExpected2("sub a", "SUB", "A"); AluOpWorksAsExpected2("sub xh", "SUB", "XH"); AluOpWorksAsExpected2("sub xl", "SUB", "XL"); AluOpWorksAsExpected2("sub yh", "SUB", "YH"); AluOpWorksAsExpected2("sub yl", "SUB", "YL"); AluOpWorksAsExpected2("sub (ix)", "SUB", null, "IX", null); AluOpWorksAsExpected2("sub (ix+#04)", "SUB", null, "IX", "+"); AluOpWorksAsExpected2("sub (ix-#04)", "SUB", null, "IX", "-"); AluOpWorksAsExpected2("sub (iy)", "SUB", null, "IY", null); AluOpWorksAsExpected2("sub (iy+#04)", "SUB", null, "IY", "+"); AluOpWorksAsExpected2("sub (iy-#04)", "SUB", null, "IY", "-"); AluOpWorksAsExpected2("sub #12", "SUB"); AluOpWorksAsExpected2("sub Some", "SUB"); } [TestMethod] public void SubInstructionWorksWithAlternateSyntaxAsExpected() { AluOpWorksAsExpected("sub a,b", "SUB", "B", "A"); AluOpWorksAsExpected("sub a,c", "SUB", "C", "A"); AluOpWorksAsExpected("sub a,d", "SUB", "D", "A"); AluOpWorksAsExpected("sub a,e", "SUB", "E", "A"); AluOpWorksAsExpected("sub a,h", "SUB", "H", "A"); AluOpWorksAsExpected("sub a,l", "SUB", "L", "A"); AluOpWorksAsExpected("sub a,(hl)", "SUB", "(HL)", "A"); AluOpWorksAsExpected("sub a,a", "SUB", "A", "A"); AluOpWorksAsExpected("sub a,xh", "SUB", "XH", "A"); AluOpWorksAsExpected("sub a,xl", "SUB", "XL", "A"); AluOpWorksAsExpected("sub a,yh", "SUB", "YH", "A"); AluOpWorksAsExpected("sub a,yl", "SUB", "YL", "A"); AluOpWorksAsExpected3("sub a,(ix)", "SUB", "A", "IX", null); AluOpWorksAsExpected3("sub a,(ix+#04)", "SUB", "A", "IX", "+"); AluOpWorksAsExpected3("sub a,(ix-#04)", "SUB", "A", "IX", "-"); AluOpWorksAsExpected3("sub a,(iy)", "SUB", "A", "IY", null); AluOpWorksAsExpected3("sub a,(iy+#04)", "SUB", "A", "IY", "+"); AluOpWorksAsExpected3("sub a,(iy-#04)", "SUB", "A", "IY", "-"); AluOpWorksAsExpected3("sub a,#12", "SUB", "A"); AluOpWorksAsExpected3("sub a,Some", "SUB", "A"); } [TestMethod] public void SbcInstructionWorksAsExpected() { AluOpWorksAsExpected("sbc hl,bc", "SBC", "BC", "HL"); AluOpWorksAsExpected("sbc hl,de", "SBC", "DE", "HL"); AluOpWorksAsExpected("sbc hl,hl", "SBC", "HL", "HL"); AluOpWorksAsExpected("sbc hl,sp", "SBC", "SP", "HL"); AluOpWorksAsExpected("sbc a,b", "SBC", "B", "A"); AluOpWorksAsExpected("sbc a,c", "SBC", "C", "A"); AluOpWorksAsExpected("sbc a,d", "SBC", "D", "A"); AluOpWorksAsExpected("sbc a,e", "SBC", "E", "A"); AluOpWorksAsExpected("sbc a,h", "SBC", "H", "A"); AluOpWorksAsExpected("sbc a,l", "SBC", "L", "A"); AluOpWorksAsExpected("sbc a,(hl)", "SBC", "(HL)", "A"); AluOpWorksAsExpected("sbc a,a", "SBC", "A", "A"); AluOpWorksAsExpected("sbc a,xh", "SBC", "XH", "A"); AluOpWorksAsExpected("sbc a,xl", "SBC", "XL", "A"); AluOpWorksAsExpected("sbc a,yh", "SBC", "YH", "A"); AluOpWorksAsExpected("sbc a,yl", "SBC", "YL", "A"); AluOpWorksAsExpected("sbc a,(ix)", "SBC", "A", "IX", null); AluOpWorksAsExpected("sbc a,(ix+#04)", "SBC", "A", "IX", "+"); AluOpWorksAsExpected("sbc a,(ix-#04)", "SBC", "A", "IX", "-"); AluOpWorksAsExpected("sbc a,(iy)", "SBC", "A", "IY", null); AluOpWorksAsExpected("sbc a,(iy+#04)", "SBC", "A", "IY", "+"); AluOpWorksAsExpected("sbc a,(iy-#04)", "SBC", "A", "IY", "-"); AluOpWorksAsExpected("sbc a,#12", "SBC", "A"); AluOpWorksAsExpected("sbc a,Some", "SBC", "A"); } [TestMethod] public void AndInstructionWorksAsExpected() { AluOpWorksAsExpected2("and b", "AND", "B"); AluOpWorksAsExpected2("and c", "AND", "C"); AluOpWorksAsExpected2("and d", "AND", "D"); AluOpWorksAsExpected2("and e", "AND", "E"); AluOpWorksAsExpected2("and h", "AND", "H"); AluOpWorksAsExpected2("and l", "AND", "L"); AluOpWorksAsExpected2("and (hl)", "AND", "(HL)"); AluOpWorksAsExpected2("and a", "AND", "A"); AluOpWorksAsExpected2("and xh", "AND", "XH"); AluOpWorksAsExpected2("and xl", "AND", "XL"); AluOpWorksAsExpected2("and yh", "AND", "YH"); AluOpWorksAsExpected2("and yl", "AND", "YL"); AluOpWorksAsExpected2("and (ix)", "AND", null, "IX", null); AluOpWorksAsExpected2("and (ix+#04)", "AND", null, "IX", "+"); AluOpWorksAsExpected2("and (ix-#04)", "AND", null, "IX", "-"); AluOpWorksAsExpected2("and (iy)", "AND", null, "IY", null); AluOpWorksAsExpected2("and (iy+#04)", "AND", null, "IY", "+"); AluOpWorksAsExpected2("and (iy-#04)", "AND", null, "IY", "-"); AluOpWorksAsExpected2("and #12", "AND"); AluOpWorksAsExpected2("and Some", "AND"); } [TestMethod] public void AndInstructionWorksWithAlternateSyntaxAsExpected() { AluOpWorksAsExpected("and a,b", "AND", "B", "A"); AluOpWorksAsExpected("and a,c", "AND", "C", "A"); AluOpWorksAsExpected("and a,d", "AND", "D", "A"); AluOpWorksAsExpected("and a,e", "AND", "E", "A"); AluOpWorksAsExpected("and a,h", "AND", "H", "A"); AluOpWorksAsExpected("and a,l", "AND", "L", "A"); AluOpWorksAsExpected("and a,(hl)", "AND", "(HL)", "A"); AluOpWorksAsExpected("and a,a", "AND", "A", "A"); AluOpWorksAsExpected("and a,xh", "AND", "XH", "A"); AluOpWorksAsExpected("and a,xl", "AND", "XL", "A"); AluOpWorksAsExpected("and a,yh", "AND", "YH", "A"); AluOpWorksAsExpected("and a,yl", "AND", "YL", "A"); AluOpWorksAsExpected3("and a,(ix)", "AND", "A", "IX", null); AluOpWorksAsExpected3("and a,(ix+#04)", "AND", "A", "IX", "+"); AluOpWorksAsExpected3("and a,(ix-#04)", "AND", "A", "IX", "-"); AluOpWorksAsExpected3("and a,(iy)", "AND", "A", "IY", null); AluOpWorksAsExpected3("and a,(iy+#04)", "AND", "A", "IY", "+"); AluOpWorksAsExpected3("and a,(iy-#04)", "AND", "A", "IY", "-"); AluOpWorksAsExpected3("and a,#12", "AND", "A"); AluOpWorksAsExpected3("and a,Some", "AND", "A"); } [TestMethod] public void XorInstructionWorksAsExpected() { AluOpWorksAsExpected2("xor b", "XOR", "B"); AluOpWorksAsExpected2("xor c", "XOR", "C"); AluOpWorksAsExpected2("xor d", "XOR", "D"); AluOpWorksAsExpected2("xor e", "XOR", "E"); AluOpWorksAsExpected2("xor h", "XOR", "H"); AluOpWorksAsExpected2("xor l", "XOR", "L"); AluOpWorksAsExpected2("xor (hl)", "XOR", "(HL)"); AluOpWorksAsExpected2("xor a", "XOR", "A"); AluOpWorksAsExpected2("xor xh", "XOR", "XH"); AluOpWorksAsExpected2("xor xl", "XOR", "XL"); AluOpWorksAsExpected2("xor yh", "XOR", "YH"); AluOpWorksAsExpected2("xor yl", "XOR", "YL"); AluOpWorksAsExpected2("xor (ix)", "XOR", null, "IX", null); AluOpWorksAsExpected2("xor (ix+#04)", "XOR", null, "IX", "+"); AluOpWorksAsExpected2("xor (ix-#04)", "XOR", null, "IX", "-"); AluOpWorksAsExpected2("xor (iy)", "XOR", null, "IY", null); AluOpWorksAsExpected2("xor (iy+#04)", "XOR", null, "IY", "+"); AluOpWorksAsExpected2("xor (iy-#04)", "XOR", null, "IY", "-"); AluOpWorksAsExpected2("xor #12", "XOR"); AluOpWorksAsExpected2("xor Some", "XOR"); } [TestMethod] public void XorInstructionWorksWithAlternateSyntaxAsExpected() { AluOpWorksAsExpected("xor a,b", "XOR", "B", "A"); AluOpWorksAsExpected("xor a,c", "XOR", "C", "A"); AluOpWorksAsExpected("xor a,d", "XOR", "D", "A"); AluOpWorksAsExpected("xor a,e", "XOR", "E", "A"); AluOpWorksAsExpected("xor a,h", "XOR", "H", "A"); AluOpWorksAsExpected("xor a,l", "XOR", "L", "A"); AluOpWorksAsExpected("xor a,(hl)", "XOR", "(HL)", "A"); AluOpWorksAsExpected("xor a,a", "XOR", "A", "A"); AluOpWorksAsExpected("xor a,xh", "XOR", "XH", "A"); AluOpWorksAsExpected("xor a,xl", "XOR", "XL", "A"); AluOpWorksAsExpected("xor a,yh", "XOR", "YH", "A"); AluOpWorksAsExpected("xor a,yl", "XOR", "YL", "A"); AluOpWorksAsExpected3("xor a,(ix)", "XOR", "A", "IX", null); AluOpWorksAsExpected3("xor a,(ix+#04)", "XOR", "A", "IX", "+"); AluOpWorksAsExpected3("xor a,(ix-#04)", "XOR", "A", "IX", "-"); AluOpWorksAsExpected3("xor a,(iy)", "XOR", "A", "IY", null); AluOpWorksAsExpected3("xor a,(iy+#04)", "XOR", "A", "IY", "+"); AluOpWorksAsExpected3("xor a,(iy-#04)", "XOR", "A", "IY", "-"); AluOpWorksAsExpected3("xor a,#12", "XOR", "A"); AluOpWorksAsExpected3("xor a,Some", "XOR", "A"); } [TestMethod] public void OrInstructionWorksAsExpected() { AluOpWorksAsExpected2("or b", "OR", "B"); AluOpWorksAsExpected2("or c", "OR", "C"); AluOpWorksAsExpected2("or d", "OR", "D"); AluOpWorksAsExpected2("or e", "OR", "E"); AluOpWorksAsExpected2("or h", "OR", "H"); AluOpWorksAsExpected2("or l", "OR", "L"); AluOpWorksAsExpected2("or (hl)", "OR", "(HL)"); AluOpWorksAsExpected2("or a", "OR", "A"); AluOpWorksAsExpected2("or xh", "OR", "XH"); AluOpWorksAsExpected2("or xl", "OR", "XL"); AluOpWorksAsExpected2("or yh", "OR", "YH"); AluOpWorksAsExpected2("or yl", "OR", "YL"); AluOpWorksAsExpected2("or (ix)", "OR", null, "IX", null); AluOpWorksAsExpected2("or (ix+#04)", "OR", null, "IX", "+"); AluOpWorksAsExpected2("or (ix-#04)", "OR", null, "IX", "-"); AluOpWorksAsExpected2("or (iy)", "OR", null, "IY", null); AluOpWorksAsExpected2("or (iy+#04)", "OR", null, "IY", "+"); AluOpWorksAsExpected2("or (iy-#04)", "OR", null, "IY", "-"); AluOpWorksAsExpected2("or #12", "OR"); AluOpWorksAsExpected2("or Some", "OR"); } [TestMethod] public void OrInstructionWorksWithAlternateSyntaxAsExpected() { AluOpWorksAsExpected("or a,b", "OR", "B", "A"); AluOpWorksAsExpected("or a,c", "OR", "C", "A"); AluOpWorksAsExpected("or a,d", "OR", "D", "A"); AluOpWorksAsExpected("or a,e", "OR", "E", "A"); AluOpWorksAsExpected("or a,h", "OR", "H", "A"); AluOpWorksAsExpected("or a,l", "OR", "L", "A"); AluOpWorksAsExpected("or a,(hl)", "OR", "(HL)", "A"); AluOpWorksAsExpected("or a,a", "OR", "A", "A"); AluOpWorksAsExpected("or a,xh", "OR", "XH", "A"); AluOpWorksAsExpected("or a,xl", "OR", "XL", "A"); AluOpWorksAsExpected("or a,yh", "OR", "YH", "A"); AluOpWorksAsExpected("or a,yl", "OR", "YL", "A"); AluOpWorksAsExpected3("or a,(ix)", "OR", "A", "IX", null); AluOpWorksAsExpected3("or a,(ix+#04)", "OR", "A", "IX", "+"); AluOpWorksAsExpected3("or a,(ix-#04)", "OR", "A", "IX", "-"); AluOpWorksAsExpected3("or a,(iy)", "OR", "A", "IY", null); AluOpWorksAsExpected3("or a,(iy+#04)", "OR", "A", "IY", "+"); AluOpWorksAsExpected3("or a,(iy-#04)", "OR", "A", "IY", "-"); AluOpWorksAsExpected3("or a,#12", "OR", "A"); AluOpWorksAsExpected3("or a,Some", "OR", "A"); } [TestMethod] public void CpInstructionWorksAsExpected() { AluOpWorksAsExpected2("cp b", "CP", "B"); AluOpWorksAsExpected2("cp c", "CP", "C"); AluOpWorksAsExpected2("cp d", "CP", "D"); AluOpWorksAsExpected2("cp e", "CP", "E"); AluOpWorksAsExpected2("cp h", "CP", "H"); AluOpWorksAsExpected2("cp l", "CP", "L"); AluOpWorksAsExpected2("cp (hl)", "CP", "(HL)"); AluOpWorksAsExpected2("cp a", "CP", "A"); AluOpWorksAsExpected2("cp xh", "CP", "XH"); AluOpWorksAsExpected2("cp xl", "CP", "XL"); AluOpWorksAsExpected2("cp yh", "CP", "YH"); AluOpWorksAsExpected2("cp yl", "CP", "YL"); AluOpWorksAsExpected2("cp (ix)", "CP", null, "IX", null); AluOpWorksAsExpected2("cp (ix+#04)", "CP", null, "IX", "+"); AluOpWorksAsExpected2("cp (ix-#04)", "CP", null, "IX", "-"); AluOpWorksAsExpected2("cp (iy)", "CP", null, "IY", null); AluOpWorksAsExpected2("cp (iy+#04)", "CP", null, "IY", "+"); AluOpWorksAsExpected2("cp (iy-#04)", "CP", null, "IY", "-"); AluOpWorksAsExpected2("cp #12", "CP"); AluOpWorksAsExpected2("cp Some", "CP"); } [TestMethod] public void CpInstructionWorksWithAlternateSyntaxAsExpected() { AluOpWorksAsExpected("cp a,b", "CP", "B", "A"); AluOpWorksAsExpected("cp a,c", "CP", "C", "A"); AluOpWorksAsExpected("cp a,d", "CP", "D", "A"); AluOpWorksAsExpected("cp a,e", "CP", "E", "A"); AluOpWorksAsExpected("cp a,h", "CP", "H", "A"); AluOpWorksAsExpected("cp a,l", "CP", "L", "A"); AluOpWorksAsExpected("cp a,(hl)", "CP", "(HL)", "A"); AluOpWorksAsExpected("cp a,a", "CP", "A", "A"); AluOpWorksAsExpected("cp a,xh", "CP", "XH", "A"); AluOpWorksAsExpected("cp a,xl", "CP", "XL", "A"); AluOpWorksAsExpected("cp a,yh", "CP", "YH", "A"); AluOpWorksAsExpected("cp a,yl", "CP", "YL", "A"); AluOpWorksAsExpected3("cp a,(ix)", "CP", "A", "IX", null); AluOpWorksAsExpected3("cp a,(ix+#04)", "CP", "A", "IX", "+"); AluOpWorksAsExpected3("cp a,(ix-#04)", "CP", "A", "IX", "-"); AluOpWorksAsExpected3("cp a,(iy)", "CP", "A", "IY", null); AluOpWorksAsExpected3("cp a,(iy+#04)", "CP", "A", "IY", "+"); AluOpWorksAsExpected3("cp a,(iy-#04)", "CP", "A", "IY", "-"); AluOpWorksAsExpected3("cp a,#12", "CP", "A"); AluOpWorksAsExpected3("cp a,Some", "CP", "A"); } protected void AluOpWorksAsExpected(string instruction, string type, string source, string dest) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand.Register.ShouldBe(dest); line.Operand2.Register.ShouldBe(source); line.Operand2.Sign.ShouldBeNull(); line.Operand2.Expression.ShouldBeNull(); } protected void AluOpWorksAsExpected2(string instruction, string type, string source) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand.Register.ShouldBe(source); line.Operand.Sign.ShouldBeNull(); line.Operand.Expression.ShouldBeNull(); } protected void AluOpWorksAsExpected(string instruction, string type, string dest, string reg, string sign) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand2.Type.ShouldBe(OperandType.IndexedAddress); line.Operand2.Register.ShouldBe(reg); line.Operand2.Sign.ShouldBe(sign); if (line.Operand2.Sign == null) { line.Operand2.Expression.ShouldBeNull(); } else { line.Operand2.Expression.ShouldNotBeNull(); } } protected void AluOpWorksAsExpected2(string instruction, string type, string dest, string reg, string sign) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand.Type.ShouldBe(OperandType.IndexedAddress); line.Operand.Register.ShouldBe(reg); line.Operand.Sign.ShouldBe(sign); if (line.Operand.Sign == null) { line.Operand.Expression.ShouldBeNull(); } else { line.Operand.Expression.ShouldNotBeNull(); } } protected void AluOpWorksAsExpected(string instruction, string type, string dest) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand2.Type.ShouldBe(OperandType.Expr); line.Operand2.Register.ShouldBeNull(); line.Operand2.Sign.ShouldBeNull(); line.Operand2.Expression.ShouldNotBeNull(); } protected void AluOpWorksAsExpected2(string instruction, string type) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand.Type.ShouldBe(OperandType.Expr); line.Operand.Register.ShouldBeNull(); line.Operand.Sign.ShouldBeNull(); line.Operand.Expression.ShouldNotBeNull(); } protected void AluOpWorksAsExpected3(string instruction, string type, string dest, string reg, string sign) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand.Register.ShouldBe(dest); line.Operand2.Type.ShouldBe(OperandType.IndexedAddress); line.Operand2.Register.ShouldBe(reg); line.Operand2.Sign.ShouldBe(sign); if (line.Operand2.Sign == null) { line.Operand2.Expression.ShouldBeNull(); } else { line.Operand2.Expression.ShouldNotBeNull(); } } protected void AluOpWorksAsExpected3(string instruction, string type, string dest) { // --- Act var visitor = Parse(instruction); // --- Assert visitor.Compilation.Lines.Count.ShouldBe(1); var line = visitor.Compilation.Lines[0] as CompoundOperation; line.ShouldNotBeNull(); line.ShouldNotBeNull(); line.Mnemonic.ShouldBe(type); line.Operand.Register.ShouldBe(dest); line.Operand2.Type.ShouldBe(OperandType.Expr); line.Operand2.Register.ShouldBeNull(); line.Operand2.Sign.ShouldBeNull(); line.Operand2.Expression.ShouldNotBeNull(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Index { /// <summary> <p/>Expert: a MergePolicy determines the sequence of /// primitive merge operations to be used for overall merge /// and optimize operations.<p/> /// /// <p/>Whenever the segments in an index have been altered by /// <see cref="IndexWriter" />, either the addition of a newly /// flushed segment, addition of many segments from /// addIndexes* calls, or a previous merge that may now need /// to cascade, <see cref="IndexWriter" /> invokes <see cref="FindMerges" /> /// to give the MergePolicy a chance to pick /// merges that are now required. This method returns a /// <see cref="MergeSpecification" /> instance describing the set of /// merges that should be done, or null if no merges are /// necessary. When IndexWriter.optimize is called, it calls /// <see cref="FindMergesForOptimize" /> and the MergePolicy should /// then return the necessary merges.<p/> /// /// <p/>Note that the policy can return more than one merge at /// a time. In this case, if the writer is using <see cref="SerialMergeScheduler" /> ///, the merges will be run /// sequentially but if it is using <see cref="ConcurrentMergeScheduler" /> /// they will be run concurrently.<p/> /// /// <p/>The default MergePolicy is <see cref="LogByteSizeMergePolicy" /> ///.<p/> /// /// <p/><b>NOTE:</b> This API is new and still experimental /// (subject to change suddenly in the next release)<p/> /// /// <p/><b>NOTE</b>: This class typically requires access to /// package-private APIs (e.g. <c>SegmentInfos</c>) to do its job; /// if you implement your own MergePolicy, you'll need to put /// it in package Lucene.Net.Index in order to use /// these APIs. /// </summary> public abstract class MergePolicy : IDisposable { /// <summary>OneMerge provides the information necessary to perform /// an individual primitive merge operation, resulting in /// a single new segment. The merge spec includes the /// subset of segments to be merged as well as whether the /// new segment should use the compound file format. /// </summary> public class OneMerge { internal SegmentInfo info; // used by IndexWriter internal bool mergeDocStores; // used by IndexWriter internal bool optimize; // used by IndexWriter internal bool registerDone; // used by IndexWriter internal long mergeGen; // used by IndexWriter internal bool isExternal; // used by IndexWriter internal int maxNumSegmentsOptimize; // used by IndexWriter internal SegmentReader[] readers; // used by IndexWriter internal SegmentReader[] readersClone; // used by IndexWriter internal SegmentInfos segments; internal bool useCompoundFile; internal bool aborted; internal System.Exception error; public OneMerge(SegmentInfos segments, bool useCompoundFile) { if (0 == segments.Count) throw new ArgumentException("segments must include at least one segment", "segments"); this.segments = segments; this.useCompoundFile = useCompoundFile; } /// <summary>Record that an exception occurred while executing /// this merge /// </summary> internal virtual void SetException(System.Exception error) { lock (this) { this.error = error; } } /// <summary>Retrieve previous exception set by <see cref="SetException" /> ///. /// </summary> internal virtual System.Exception GetException() { lock (this) { return error; } } /// <summary>Mark this merge as aborted. If this is called /// before the merge is committed then the merge will /// not be committed. /// </summary> internal virtual void Abort() { lock (this) { aborted = true; } } /// <summary>Returns true if this merge was aborted. </summary> internal virtual bool IsAborted() { lock (this) { return aborted; } } internal virtual void CheckAborted(Directory dir) { lock (this) { if (aborted) throw new MergeAbortedException("merge is aborted: " + SegString(dir)); } } internal virtual String SegString(Directory dir) { var b = new System.Text.StringBuilder(); int numSegments = segments.Count; for (int i = 0; i < numSegments; i++) { if (i > 0) b.Append(' '); b.Append(segments.Info(i).SegString(dir)); } if (info != null) b.Append(" into ").Append(info.name); if (optimize) b.Append(" [optimize]"); if (mergeDocStores) { b.Append(" [mergeDocStores]"); } return b.ToString(); } public SegmentInfos segments_ForNUnit { get { return segments; } } } /// <summary> A MergeSpecification instance provides the information /// necessary to perform multiple merges. It simply /// contains a list of <see cref="OneMerge" /> instances. /// </summary> public class MergeSpecification { /// <summary> The subset of segments to be included in the primitive merge.</summary> public IList<OneMerge> merges = new List<OneMerge>(); public virtual void Add(OneMerge merge) { merges.Add(merge); } public virtual String SegString(Directory dir) { var b = new System.Text.StringBuilder(); b.Append("MergeSpec:\n"); int count = merges.Count; for (int i = 0; i < count; i++) b.Append(" ").Append(1 + i).Append(": ").Append(merges[i].SegString(dir)); return b.ToString(); } } /// <summary>Exception thrown if there are any problems while /// executing a merge. /// </summary> [Serializable] public class MergeException:System.SystemException { private readonly Directory dir; public MergeException(System.String message, Directory dir):base(message) { this.dir = dir; } public MergeException(System.Exception exc, Directory dir):base(null, exc) { this.dir = dir; } /// <summary>Returns the <see cref="Directory" /> of the index that hit /// the exception. /// </summary> public virtual Directory Directory { get { return dir; } } } [Serializable] public class MergeAbortedException:System.IO.IOException { public MergeAbortedException():base("merge is aborted") { } public MergeAbortedException(System.String message):base(message) { } } protected internal IndexWriter writer; protected MergePolicy(IndexWriter writer) { this.writer = writer; } /// <summary> Determine what set of merge operations are now necessary on the index. /// <see cref="IndexWriter" /> calls this whenever there is a change to the segments. /// This call is always synchronized on the <see cref="IndexWriter" /> instance so /// only one thread at a time will call this method. /// /// </summary> /// <param name="segmentInfos">the total set of segments in the index /// </param> public abstract MergeSpecification FindMerges(SegmentInfos segmentInfos); /// <summary> Determine what set of merge operations is necessary in order to optimize /// the index. <see cref="IndexWriter" /> calls this when its /// <see cref="IndexWriter.Optimize()" /> method is called. This call is always /// synchronized on the <see cref="IndexWriter" /> instance so only one thread at a /// time will call this method. /// /// </summary> /// <param name="segmentInfos">the total set of segments in the index /// </param> /// <param name="maxSegmentCount">requested maximum number of segments in the index (currently this /// is always 1) /// </param> /// <param name="segmentsToOptimize">contains the specific SegmentInfo instances that must be merged /// away. This may be a subset of all SegmentInfos. /// </param> public abstract MergeSpecification FindMergesForOptimize(SegmentInfos segmentInfos, int maxSegmentCount, ISet<SegmentInfo> segmentsToOptimize); /// <summary> Determine what set of merge operations is necessary in order to expunge all /// deletes from the index. /// /// </summary> /// <param name="segmentInfos">the total set of segments in the index /// </param> public abstract MergeSpecification FindMergesToExpungeDeletes(SegmentInfos segmentInfos); /// <summary> Release all resources for the policy.</summary> [Obsolete("Use Dispose() instead")] public void Close() { Dispose(); } /// <summary> Release all resources for the policy.</summary> public void Dispose() { Dispose(true); } protected abstract void Dispose(bool disposing); /// <summary> Returns true if a newly flushed (not from merge) /// segment should use the compound file format. /// </summary> public abstract bool UseCompoundFile(SegmentInfos segments, SegmentInfo newSegment); /// <summary> Returns true if the doc store files should use the /// compound file format. /// </summary> public abstract bool UseCompoundDocStore(SegmentInfos segments); } }
// WARNING // // This file has been generated automatically by Visual Studio to store outlets and // actions made in the UI designer. If it is removed, they will be lost. // Manual changes to this file may not be handled correctly. // using Foundation; using System.CodeDom.Compiler; namespace Toggl.iOS.ViewControllers { [Register ("StartTimeEntryViewController")] partial class StartTimeEntryViewController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton BillableButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.NSLayoutConstraint BillableButtonWidthConstraint { get; set; } [Outlet] UIKit.UIView BillableTooltip { get; set; } [Outlet] Toggl.iOS.Views.TriangleView BillableTooltipArrow { get; set; } [Outlet] UIKit.UIView BillableTooltipBackground { get; set; } [Outlet] UIKit.UIButton BillableTooltipDetailsButton { get; set; } [Outlet] UIKit.UILabel BillableTooltipMessageLabel { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.NSLayoutConstraint BottomDistanceConstraint { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIView BottomOptionsSheet { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton CloseButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton DateTimeButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITextView DescriptionTextView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton DoneButton { get; set; } [Outlet] Toggl.iOS.Views.AutocompleteTextViewPlaceholder Placeholder { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton ProjectsButton { get; set; } [Outlet] UIKit.UIView ProjectsTooltip { get; set; } [Outlet] Toggl.iOS.Views.TriangleView ProjectsTooltipArrow { get; set; } [Outlet] UIKit.UIView ProjectsTooltipBackground { get; set; } [Outlet] UIKit.UIImageView ProjectsTooltipCloseIcon { get; set; } [Outlet] UIKit.UILabel ProjectsTooltipLabel { get; set; } [Outlet] UIKit.UIButton StartDateButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITableView SuggestionsTableView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton TagsButton { get; set; } [Outlet] Toggl.iOS.Views.EditDuration.DurationField TimeInput { get; set; } [Outlet] UIKit.NSLayoutConstraint TimeInputTrailingConstraint { get; set; } [Outlet] UIKit.UILabel TimeLabel { get; set; } [Outlet] UIKit.NSLayoutConstraint TimeLabelTrailingConstraint { get; set; } void ReleaseDesignerOutlets () { if (BillableButton != null) { BillableButton.Dispose (); BillableButton = null; } if (BillableButtonWidthConstraint != null) { BillableButtonWidthConstraint.Dispose (); BillableButtonWidthConstraint = null; } if (BillableTooltip != null) { BillableTooltip.Dispose (); BillableTooltip = null; } if (BillableTooltipArrow != null) { BillableTooltipArrow.Dispose (); BillableTooltipArrow = null; } if (BillableTooltipBackground != null) { BillableTooltipBackground.Dispose (); BillableTooltipBackground = null; } if (BillableTooltipDetailsButton != null) { BillableTooltipDetailsButton.Dispose (); BillableTooltipDetailsButton = null; } if (BillableTooltipMessageLabel != null) { BillableTooltipMessageLabel.Dispose (); BillableTooltipMessageLabel = null; } if (BottomDistanceConstraint != null) { BottomDistanceConstraint.Dispose (); BottomDistanceConstraint = null; } if (BottomOptionsSheet != null) { BottomOptionsSheet.Dispose (); BottomOptionsSheet = null; } if (CloseButton != null) { CloseButton.Dispose (); CloseButton = null; } if (DateTimeButton != null) { DateTimeButton.Dispose (); DateTimeButton = null; } if (DescriptionTextView != null) { DescriptionTextView.Dispose (); DescriptionTextView = null; } if (DoneButton != null) { DoneButton.Dispose (); DoneButton = null; } if (Placeholder != null) { Placeholder.Dispose (); Placeholder = null; } if (ProjectsButton != null) { ProjectsButton.Dispose (); ProjectsButton = null; } if (ProjectsTooltip != null) { ProjectsTooltip.Dispose (); ProjectsTooltip = null; } if (ProjectsTooltipArrow != null) { ProjectsTooltipArrow.Dispose (); ProjectsTooltipArrow = null; } if (ProjectsTooltipBackground != null) { ProjectsTooltipBackground.Dispose (); ProjectsTooltipBackground = null; } if (ProjectsTooltipCloseIcon != null) { ProjectsTooltipCloseIcon.Dispose (); ProjectsTooltipCloseIcon = null; } if (ProjectsTooltipLabel != null) { ProjectsTooltipLabel.Dispose (); ProjectsTooltipLabel = null; } if (StartDateButton != null) { StartDateButton.Dispose (); StartDateButton = null; } if (SuggestionsTableView != null) { SuggestionsTableView.Dispose (); SuggestionsTableView = null; } if (TagsButton != null) { TagsButton.Dispose (); TagsButton = null; } if (TimeInput != null) { TimeInput.Dispose (); TimeInput = null; } if (TimeInputTrailingConstraint != null) { TimeInputTrailingConstraint.Dispose (); TimeInputTrailingConstraint = null; } if (TimeLabel != null) { TimeLabel.Dispose (); TimeLabel = null; } if (TimeLabelTrailingConstraint != null) { TimeLabelTrailingConstraint.Dispose (); TimeLabelTrailingConstraint = null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Xunit; public static unsafe class DateTimeTests { [Fact] public static void TestConstructors() { DateTime dt = new DateTime(2012, 6, 11); ValidateYearMonthDay(dt, 2012, 6, 11); dt = new DateTime(2012, 12, 31, 13, 50, 10); ValidateYearMonthDay(dt, 2012, 12, 31, 13, 50, 10); dt = new DateTime(1973, 10, 6, 14, 30, 0, 500); ValidateYearMonthDay(dt, 1973, 10, 6, 14, 30, 0, 500); dt = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local); ValidateYearMonthDay(dt, 1986, 8, 15, 10, 20, 5); } [Fact] public static void TestDateTimeLimits() { DateTime dt = DateTime.MaxValue; ValidateYearMonthDay(dt, 9999, 12, 31); dt = DateTime.MinValue; ValidateYearMonthDay(dt, 1, 1, 1); } [Fact] public static void TestLeapYears() { Assert.Equal(true, DateTime.IsLeapYear(2004)); Assert.Equal(false, DateTime.IsLeapYear(2005)); } [Fact] public static void TestAddition() { DateTime dt = new DateTime(1986, 8, 15, 10, 20, 5, 70); Assert.Equal(17, dt.AddDays(2).Day); Assert.Equal(13, dt.AddDays(-2).Day); Assert.Equal(10, dt.AddMonths(2).Month); Assert.Equal(6, dt.AddMonths(-2).Month); Assert.Equal(1996, dt.AddYears(10).Year); Assert.Equal(1976, dt.AddYears(-10).Year); Assert.Equal(13, dt.AddHours(3).Hour); Assert.Equal(7, dt.AddHours(-3).Hour); Assert.Equal(25, dt.AddMinutes(5).Minute); Assert.Equal(15, dt.AddMinutes(-5).Minute); Assert.Equal(35, dt.AddSeconds(30).Second); Assert.Equal(2, dt.AddSeconds(-3).Second); Assert.Equal(80, dt.AddMilliseconds(10).Millisecond); Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond); } [Fact] public static void TestDayOfWeek() { DateTime dt = new DateTime(2012, 6, 18); Assert.Equal(DayOfWeek.Monday, dt.DayOfWeek); } [Fact] public static void TestTimeSpan() { DateTime dt = new DateTime(2012, 6, 18, 10, 5, 1, 0); TimeSpan ts = dt.TimeOfDay; DateTime newDate = dt.Subtract(ts); Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks); Assert.Equal(dt.Ticks, newDate.Add(ts).Ticks); } [Fact] public static void TestToday() { DateTime today = DateTime.Today; DateTime now = DateTime.Now; ValidateYearMonthDay(today, now.Year, now.Month, now.Day); today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc); Assert.Equal(DateTimeKind.Utc, today.Kind); Assert.Equal(false, today.IsDaylightSavingTime()); } [Fact] public static void TestCoversion() { DateTime today = DateTime.Today; long dateTimeRaw = today.ToBinary(); Assert.Equal(today, DateTime.FromBinary(dateTimeRaw)); dateTimeRaw = today.ToFileTime(); Assert.Equal(today, DateTime.FromFileTime(dateTimeRaw)); dateTimeRaw = today.ToFileTimeUtc(); Assert.Equal(today, DateTime.FromFileTimeUtc(dateTimeRaw).ToLocalTime()); } [Fact] public static void TestOperators() { System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0); System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0); System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0); // diff1 gets 185 days, 14 hours, and 47 minutes. System.TimeSpan diff1 = date2.Subtract(date1); Assert.Equal(new TimeSpan(185, 14, 47, 0), diff1); // date4 gets 4/9/1996 5:55:00 PM. System.DateTime date4 = date3.Subtract(diff1); Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date4); // diff2 gets 55 days 4 hours and 20 minutes. System.TimeSpan diff2 = date2 - date3; Assert.Equal(new TimeSpan(55, 4, 20, 0), diff2); // date5 gets 4/9/1996 5:55:00 PM. System.DateTime date5 = date1 - diff2; Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date5); } [Fact] public static void TestParsingDateTimeWithTimeDesignator() { DateTime result; Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(4, result.Month); Assert.Equal(21, result.Day); Assert.Equal(5, result.Hour); Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(4, result.Month); Assert.Equal(21, result.Day); Assert.Equal(17, result.Hour); } public class MyFormater : IFormatProvider { public object GetFormat(Type formatType) { if (typeof(IFormatProvider) == formatType) { return this; } else { return null; } } } [Fact] public static void TestParseWithAdjustToUniversal() { var formater = new MyFormater(); var dateBefore = DateTime.Now.ToString(); var dateAfter = DateTime.ParseExact(dateBefore, "G", formater, DateTimeStyles.AdjustToUniversal); Assert.Equal(dateBefore, dateAfter.ToString()); } [Fact] public static void TestFormatParse() { DateTime dt = new DateTime(2012, 12, 21, 10, 8, 6); CultureInfo ci = new CultureInfo("ja-JP"); string s = string.Format(ci, "{0}", dt); Assert.Equal(dt, DateTime.Parse(s, ci)); } [Fact] public static void TestParse1() { DateTime src = DateTime.MaxValue; String s = src.ToString(); DateTime in_1 = DateTime.Parse(s); String actual = in_1.ToString(); Assert.Equal(s, actual); } [Fact] public static void TestParse2() { DateTime src = DateTime.MaxValue; String s = src.ToString(); DateTime in_1 = DateTime.Parse(s, null); String actual = in_1.ToString(); Assert.Equal(s, actual); } [Fact] public static void TestParse3() { DateTime src = DateTime.MaxValue; String s = src.ToString(); DateTime in_1 = DateTime.Parse(s, null, DateTimeStyles.None); String actual = in_1.ToString(); Assert.Equal(s, actual); } [Fact] public static void TestParseExact3() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1 = DateTime.ParseExact(s, "g", null); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestParseExact4() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1 = DateTime.ParseExact(s, "g", null, DateTimeStyles.None); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestParseExact4a() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); String[] formats = { "g" }; DateTime in_1 = DateTime.ParseExact(s, formats, null, DateTimeStyles.None); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParse2() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1; bool b = DateTime.TryParse(s, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParse4() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1; bool b = DateTime.TryParse(s, null, DateTimeStyles.None, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParseExact() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1; bool b = DateTime.TryParseExact(s, "g", null, DateTimeStyles.None, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParseExactA() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); String[] formats = { "g" }; DateTime in_1; bool b = DateTime.TryParseExact(s, formats, null, DateTimeStyles.None, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestGetDateTimeFormats() { char[] allStandardFormats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); List<string> july28Formats = new List<string>(); foreach (char format in allStandardFormats) { string[] dates = july28.GetDateTimeFormats(format); Assert.True(dates.Length > 0); DateTime parsedDate; Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate)); july28Formats.AddRange(dates); } List<string> actualJuly28Formats = july28.GetDateTimeFormats().ToList(); Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t)); actualJuly28Formats = july28.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList(); Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t)); } [Theory] [InlineData("fi-FI")] [InlineData("nb-NO")] [InlineData("nb-SJ")] public static void TestDateTimeParsingWithSpecialCultures(string cultureName) { // Test DateTime parsing with cultures which has the date separator and time separator are same CultureInfo ci; try { ci = new CultureInfo(cultureName); } catch (CultureNotFoundException) { // ignore un-supported culture in current platform return; } DateTime date = DateTime.Now; // truncate the milliseconds as it is not showing in time formatting patterns date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second); string dateString = date.ToString(ci.DateTimeFormat.ShortDatePattern, ci); DateTime parsedDate; Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); Assert.Equal(date.Date, parsedDate); dateString = date.ToString(ci.DateTimeFormat.LongDatePattern, ci); Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); Assert.Equal(date.Date, parsedDate); dateString = date.ToString(ci.DateTimeFormat.FullDateTimePattern, ci); Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); Assert.Equal(date, parsedDate); dateString = date.ToString(ci.DateTimeFormat.LongTimePattern, ci); Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); Assert.Equal(date.TimeOfDay, parsedDate.TimeOfDay); } [Fact] public static void TestGetDateTimeFormats_FormatSpecifier_InvalidFormat() { DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); Assert.Throws<FormatException>(() => july28.GetDateTimeFormats('x')); } internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day) { Assert.Equal(dt.Year, year); Assert.Equal(dt.Month, month); Assert.Equal(dt.Day, day); } internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second) { ValidateYearMonthDay(dt, year, month, day); Assert.Equal(dt.Hour, hour); Assert.Equal(dt.Minute, minute); Assert.Equal(dt.Second, second); } internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second, int millisecond) { ValidateYearMonthDay(dt, year, month, day, hour, minute, second); Assert.Equal(dt.Millisecond, millisecond); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Xml.Schema; namespace System.Xml.Xsl { /// <summary> /// XmlQueryType contains static type information that describes the structure and possible values of dynamic /// instances of the Xml data model. /// /// Every XmlQueryType is composed of a Prime type and a cardinality. The Prime type itself may be a union /// between several item types. The XmlQueryType IList<XmlQueryType/> implementation allows callers /// to enumerate the item types. Other properties expose other information about the type. /// </summary> internal abstract class XmlQueryType : ListBase<XmlQueryType> { private int _hashCode; //----------------------------------------------- // ItemType, OccurrenceIndicator Properties //----------------------------------------------- /// <summary> /// Static data type code. The dynamic type is guaranteed to be this type or a subtype of this code. /// This type code includes support for XQuery types that are not part of Xsd, such as Item, /// Node, AnyAtomicType, and Comment. /// </summary> public abstract XmlTypeCode TypeCode { get; } /// <summary> /// Set of allowed names for element, document{element}, attribute and PI /// Returns XmlQualifiedName.Wildcard for all other types /// </summary> public abstract XmlQualifiedNameTest NameTest { get; } /// <summary> /// Static Xsd schema type. The dynamic type is guaranteed to be this type or a subtype of this type. /// SchemaType will follow these rules: /// 1. If TypeCode is an atomic type code, then SchemaType will be the corresponding non-null simple type /// 2. If TypeCode is Element or Attribute, then SchemaType will be the non-null content type /// 3. If TypeCode is Item, Node, Comment, PI, Text, Document, Namespace, None, then SchemaType will be AnyType /// </summary> public abstract XmlSchemaType SchemaType { get; } /// <summary> /// Permits the element or document{element} node to have the nilled property. /// Returns false for all other types /// </summary> public abstract bool IsNillable { get; } /// <summary> /// This property is always XmlNodeKindFlags.None unless TypeCode = XmlTypeCode.Node, in which case this /// property lists all node kinds that instances of this type may be. /// </summary> public abstract XmlNodeKindFlags NodeKinds { get; } /// <summary> /// If IsStrict is true, then the dynamic type is guaranteed to be the exact same as the static type, and /// will therefore never be a subtype of the static type. /// </summary> public abstract bool IsStrict { get; } /// <summary> /// This property specifies the possible cardinalities that instances of this type may have. /// </summary> public abstract XmlQueryCardinality Cardinality { get; } /// <summary> /// This property returns this type's Prime type, which is always cardinality One. /// </summary> public abstract XmlQueryType Prime { get; } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be not a subtype of Rtf. /// </summary> public abstract bool IsNotRtf { get; } /// <summary> /// True if items in the sequence are guaranteed to be nodes in document order with no duplicates. /// </summary> public abstract bool IsDod { get; } //----------------------------------------------- // Type Operations //----------------------------------------------- /// <summary> /// Returns true if every possible dynamic instance of this type is also an instance of "baseType". /// </summary> public bool IsSubtypeOf(XmlQueryType baseType) { XmlQueryType thisPrime, basePrime; // Check cardinality sub-typing rules if (!(Cardinality <= baseType.Cardinality) || (!IsDod && baseType.IsDod)) return false; if (!IsDod && baseType.IsDod) return false; // Check early for common case that two types are the same object thisPrime = Prime; basePrime = baseType.Prime; if ((object)thisPrime == (object)basePrime) return true; // Check early for common case that two prime types are item types if (thisPrime.Count == 1 && basePrime.Count == 1) return thisPrime.IsSubtypeOfItemType(basePrime); // Check that each item type in this type is a subtype of some item type in "baseType" foreach (XmlQueryType thisItem in thisPrime) { bool match = false; foreach (XmlQueryType baseItem in basePrime) { if (thisItem.IsSubtypeOfItemType(baseItem)) { match = true; break; } } if (match == false) return false; } return true; } /// <summary> /// Returns true if a dynamic instance (type None never has an instance) of this type can never be a subtype of "baseType". /// </summary> public bool NeverSubtypeOf(XmlQueryType baseType) { // Check cardinalities if (Cardinality.NeverSubset(baseType.Cardinality)) return true; // If both this type and "other" type might be empty, it doesn't matter what the prime types are if (MaybeEmpty && baseType.MaybeEmpty) return false; // None is subtype of every other type if (Count == 0) return false; // Check item types foreach (XmlQueryType typThis in this) { foreach (XmlQueryType typThat in baseType) { if (typThis.HasIntersectionItemType(typThat)) return false; } } return true; } /// <summary> /// Strongly-typed Equals that returns true if this type and "that" type are equivalent. /// </summary> public bool Equals(XmlQueryType that) { if (that == null) return false; // Check cardinality and DocOrderDistinct property if (Cardinality != that.Cardinality || IsDod != that.IsDod) return false; // Check early for common case that two types are the same object XmlQueryType thisPrime = Prime; XmlQueryType thatPrime = that.Prime; if ((object)thisPrime == (object)thatPrime) return true; // Check that count of item types is equal if (thisPrime.Count != thatPrime.Count) return false; // Check early for common case that two prime types are item types if (thisPrime.Count == 1) { return (thisPrime.TypeCode == thatPrime.TypeCode && thisPrime.NameTest == thatPrime.NameTest && thisPrime.SchemaType == thatPrime.SchemaType && thisPrime.IsStrict == thatPrime.IsStrict && thisPrime.IsNotRtf == thatPrime.IsNotRtf); } // Check that each item type in this type is equal to some item type in "baseType" // (string | int) should be the same type as (int | string) foreach (XmlQueryType thisItem in this) { bool match = false; foreach (XmlQueryType thatItem in that) { if (thisItem.TypeCode == thatItem.TypeCode && thisItem.NameTest == thatItem.NameTest && thisItem.SchemaType == thatItem.SchemaType && thisItem.IsStrict == thatItem.IsStrict && thisItem.IsNotRtf == thatItem.IsNotRtf) { // Found match so proceed to next type match = true; break; } } if (match == false) return false; } return true; } /// <summary> /// Overload == operator to call Equals rather than do reference equality. /// </summary> public static bool operator ==(XmlQueryType left, XmlQueryType right) { if ((object)left == null) return ((object)right == null); return left.Equals(right); } /// <summary> /// Overload != operator to call Equals rather than do reference inequality. /// </summary> public static bool operator !=(XmlQueryType left, XmlQueryType right) { if ((object)left == null) return ((object)right != null); return !left.Equals(right); } //----------------------------------------------- // Convenience Properties //----------------------------------------------- /// <summary> /// True if dynamic cardinality of this sequence is guaranteed to be 0. /// </summary> public bool IsEmpty { get { return Cardinality <= XmlQueryCardinality.Zero; } } /// <summary> /// True if dynamic cardinality of this sequence is guaranteed to be 1. /// </summary> public bool IsSingleton { get { return Cardinality <= XmlQueryCardinality.One; } } /// <summary> /// True if dynamic cardinality of this sequence might be 0. /// </summary> public bool MaybeEmpty { get { return XmlQueryCardinality.Zero <= Cardinality; } } /// <summary> /// True if dynamic cardinality of this sequence might be >1. /// </summary> public bool MaybeMany { get { return XmlQueryCardinality.More <= Cardinality; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Node. /// Equivalent to calling IsSubtypeOf(TypeFactory.NodeS). /// </summary> public bool IsNode { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNode) != 0; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of AnyAtomicType. /// Equivalent to calling IsSubtypeOf(TypeFactory.AnyAtomicTypeS). /// </summary> public bool IsAtomicValue { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsAtomicValue) != 0; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Decimal, Double, or Float. /// Equivalent to calling IsSubtypeOf(TypeFactory.NumericS). /// </summary> public bool IsNumeric { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNumeric) != 0; } } //----------------------------------------------- // System.Object implementation //----------------------------------------------- /// <summary> /// True if "obj" is an XmlQueryType, and this type is the exact same static type. /// </summary> public override bool Equals(object obj) { XmlQueryType that = obj as XmlQueryType; if (that == null) return false; return Equals(that); } /// <summary> /// Return hash code of this instance. /// </summary> public override int GetHashCode() { if (_hashCode == 0) { int hash; XmlSchemaType schemaType; hash = (int)TypeCode; schemaType = SchemaType; unchecked { if (schemaType != null) hash += (hash << 7) ^ schemaType.GetHashCode(); hash += (hash << 7) ^ (int)NodeKinds; hash += (hash << 7) ^ Cardinality.GetHashCode(); hash += (hash << 7) ^ (IsStrict ? 1 : 0); // Mix hash code a bit more hash -= hash >> 17; hash -= hash >> 11; hash -= hash >> 5; } // Save hashcode. Don't save 0, so that it won't ever be recomputed. _hashCode = (hash == 0) ? 1 : hash; } return _hashCode; } /// <summary> /// Return a user-friendly string representation of the XmlQueryType. /// </summary> public override string ToString() { return ToString("G"); } /// <summary> /// Return a string representation of the XmlQueryType using the specified format. The following formats are /// supported: /// /// "G" (General): This is the default mode, and is used if no other format is recognized. This format is /// easier to read than the canonical format, since it excludes redundant information. /// (e.g. element instead of element(*, xs:anyType)) /// /// "X" (XQuery): Return the canonical XQuery representation, which excludes Qil specific information and /// includes extra, redundant information, such as fully specified types. /// (e.g. element(*, xs:anyType) instead of element) /// /// "S" (Serialized): This format is used to serialize parts of the type which can be serialized easily, in /// a format that is easy to parse. Only the cardinality, type code, and strictness flag /// are serialized. User-defined type information and element/attribute content types /// are lost. /// (e.g. One;Attribute|String|Int;true) /// /// </summary> public string ToString(string format) { string[] sa; StringBuilder sb; bool isXQ; if (format == "S") { sb = new StringBuilder(); sb.Append(Cardinality.ToString(format)); sb.Append(';'); for (int i = 0; i < Count; i++) { if (i != 0) sb.Append("|"); sb.Append(this[i].TypeCode.ToString()); } sb.Append(';'); sb.Append(IsStrict); return sb.ToString(); } isXQ = (format == "X"); if (Cardinality == XmlQueryCardinality.None) { return "none"; } else if (Cardinality == XmlQueryCardinality.Zero) { return "empty"; } sb = new StringBuilder(); switch (Count) { case 0: // This assert depends on the way we are going to represent None sb.Append("none"); break; case 1: sb.Append(this[0].ItemTypeToString(isXQ)); break; default: sa = new string[Count]; for (int i = 0; i < Count; i++) sa[i] = this[i].ItemTypeToString(isXQ); Array.Sort(sa); sb = new StringBuilder(); sb.Append('('); sb.Append(sa[0]); for (int i = 1; i < sa.Length; i++) { sb.Append(" | "); sb.Append(sa[i]); } sb.Append(')'); break; } sb.Append(Cardinality.ToString()); if (!isXQ && IsDod) sb.Append('#'); return sb.ToString(); } //----------------------------------------------- // Serialization //----------------------------------------------- /// <summary> /// Serialize the object to BinaryWriter. /// </summary> public abstract void GetObjectData(BinaryWriter writer); //----------------------------------------------- // Helpers //----------------------------------------------- /// <summary> /// Returns true if this item type is a subtype of another item type. /// </summary> private bool IsSubtypeOfItemType(XmlQueryType baseType) { Debug.Assert(Count == 1 && IsSingleton, "This method should only be called for item types."); Debug.Assert(baseType.Count == 1 && baseType.IsSingleton, "This method should only be called for item types."); Debug.Assert(!IsDod && !baseType.IsDod, "Singleton types may not have DocOrderDistinct property"); XmlSchemaType baseSchemaType = baseType.SchemaType; if (TypeCode != baseType.TypeCode) { // If "baseType" is strict, then IsSubtypeOf must be false if (baseType.IsStrict) return false; // If type codes are not the same, then IsSubtypeOf can return true *only* if "baseType" is a built-in type XmlSchemaType builtInType = XmlSchemaType.GetBuiltInSimpleType(baseType.TypeCode); if (builtInType != null && baseSchemaType != builtInType) return false; // Now check whether TypeCode is derived from baseType.TypeCode return s_typeCodeDerivation[TypeCode, baseType.TypeCode]; } else if (baseType.IsStrict) { // only atomic values can be strict Debug.Assert(IsAtomicValue && baseType.IsAtomicValue); // If schema types are not the same, then IsSubtype is false if "baseType" is strict return IsStrict && SchemaType == baseSchemaType; } else { // Otherwise, check derivation tree return (IsNotRtf || !baseType.IsNotRtf) && NameTest.IsSubsetOf(baseType.NameTest) && (baseSchemaType == XmlSchemaComplexType.AnyType || XmlSchemaType.IsDerivedFrom(SchemaType, baseSchemaType, /* except:*/XmlSchemaDerivationMethod.Empty)) && (!IsNillable || baseType.IsNillable); } } /// <summary> /// Returns true if the intersection between this item type and "other" item type is not empty. /// </summary> private bool HasIntersectionItemType(XmlQueryType other) { Debug.Assert(this.Count == 1 && this.IsSingleton, "this should be an item"); Debug.Assert(other.Count == 1 && other.IsSingleton, "other should be an item"); if (this.TypeCode == other.TypeCode && (this.NodeKinds & (XmlNodeKindFlags.Document | XmlNodeKindFlags.Element | XmlNodeKindFlags.Attribute)) != 0) { if (this.TypeCode == XmlTypeCode.Node) return true; // Intersect name tests if (!this.NameTest.HasIntersection(other.NameTest)) return false; if (!XmlSchemaType.IsDerivedFrom(this.SchemaType, other.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty) && !XmlSchemaType.IsDerivedFrom(other.SchemaType, this.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty)) { return false; } return true; } else if (this.IsSubtypeOf(other) || other.IsSubtypeOf(this)) { return true; } return false; } /// <summary> /// Return the string representation of an item type (cannot be a union or a sequence). /// </summary> private string ItemTypeToString(bool isXQ) { string s; Debug.Assert(Count == 1, "Do not pass a Union type to this method."); Debug.Assert(IsSingleton, "Do not pass a Sequence type to this method."); if (IsNode) { // Map TypeCode to string s = s_typeNames[(int)TypeCode]; switch (TypeCode) { case XmlTypeCode.Document: if (!isXQ) goto case XmlTypeCode.Element; s += "{(element" + NameAndType(true) + "?&text?&comment?&processing-instruction?)*}"; break; case XmlTypeCode.Element: case XmlTypeCode.Attribute: s += NameAndType(isXQ); break; } } else if (SchemaType != XmlSchemaComplexType.AnyType) { // Get QualifiedName from SchemaType if (SchemaType.QualifiedName.IsEmpty) s = "<:" + s_typeNames[(int)TypeCode]; else s = QNameToString(SchemaType.QualifiedName); } else { // Map TypeCode to string s = s_typeNames[(int)TypeCode]; } if (!isXQ && IsStrict) s += "="; return s; } /// <summary> /// Return "(name-test, type-name)" for this type. If isXQ is false, normalize xs:anySimpleType and /// xs:anyType to "*". /// </summary> private string NameAndType(bool isXQ) { string nodeName = NameTest.ToString(); string typeName = "*"; if (SchemaType.QualifiedName.IsEmpty) { typeName = "typeof(" + nodeName + ")"; } else { if (isXQ || (SchemaType != XmlSchemaComplexType.AnyType && SchemaType != DatatypeImplementation.AnySimpleType)) typeName = QNameToString(SchemaType.QualifiedName); } if (IsNillable) typeName += " nillable"; // Normalize "(*, *)" to "" if (nodeName == "*" && typeName == "*") return ""; return "(" + nodeName + ", " + typeName + ")"; } /// <summary> /// Convert an XmlQualifiedName to a string, using somewhat different rules than XmlQualifiedName.ToString(): /// 1. Empty QNames are assumed to be wildcard names, so return "*" /// 2. Recognize the built-in xs: and xdt: namespaces and print the short prefix rather than the long namespace /// 3. Use brace characters "{", "}" around the namespace portion of the QName /// </summary> private static string QNameToString(XmlQualifiedName name) { if (name.IsEmpty) { return "*"; } else if (name.Namespace.Length == 0) { return name.Name; } else if (name.Namespace == XmlReservedNs.NsXs) { return "xs:" + name.Name; } else if (name.Namespace == XmlReservedNs.NsXQueryDataType) { return "xdt:" + name.Name; } else { return "{" + name.Namespace + "}" + name.Name; } } #region TypeFlags private enum TypeFlags { None = 0, IsNode = 1, IsAtomicValue = 2, IsNumeric = 4, } #endregion #region TypeCodeToFlags private static readonly TypeFlags[] s_typeCodeToFlags = { /* XmlTypeCode.None */ TypeFlags.IsNode | TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Item */ TypeFlags.None, /* XmlTypeCode.Node */ TypeFlags.IsNode, /* XmlTypeCode.Document */ TypeFlags.IsNode, /* XmlTypeCode.Element */ TypeFlags.IsNode, /* XmlTypeCode.Attribute */ TypeFlags.IsNode, /* XmlTypeCode.Namespace */ TypeFlags.IsNode, /* XmlTypeCode.ProcessingInstruction */ TypeFlags.IsNode, /* XmlTypeCode.Comment */ TypeFlags.IsNode, /* XmlTypeCode.Text */ TypeFlags.IsNode, /* XmlTypeCode.AnyAtomicType */ TypeFlags.IsAtomicValue, /* XmlTypeCode.UntypedAtomic */ TypeFlags.IsAtomicValue, /* XmlTypeCode.String */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Boolean */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Decimal */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Float */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Double */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Duration */ TypeFlags.IsAtomicValue, /* XmlTypeCode.DateTime */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Time */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Date */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GYearMonth */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GYear */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GMonthDay */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GDay */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GMonth */ TypeFlags.IsAtomicValue, /* XmlTypeCode.HexBinary */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Base64Binary */ TypeFlags.IsAtomicValue, /* XmlTypeCode.AnyUri */ TypeFlags.IsAtomicValue, /* XmlTypeCode.QName */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Notation */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NormalizedString */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Token */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Language */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NmToken */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Name */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NCName */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Id */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Idref */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Entity */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Integer */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NonPositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Long */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Int */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Short */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Byte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NonNegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedLong */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedInt */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedShort */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedByte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.PositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.YearMonthDuration */ TypeFlags.IsAtomicValue, /* XmlTypeCode.DayTimeDuration */ TypeFlags.IsAtomicValue, }; private static readonly XmlTypeCode[] s_baseTypeCodes = { /* None */ XmlTypeCode.None, /* Item */ XmlTypeCode.Item, /* Node */ XmlTypeCode.Item, /* Document */ XmlTypeCode.Node, /* Element */ XmlTypeCode.Node, /* Attribute */ XmlTypeCode.Node, /* Namespace */ XmlTypeCode.Node, /* ProcessingInstruction */ XmlTypeCode.Node, /* Comment */ XmlTypeCode.Node, /* Text */ XmlTypeCode.Node, /* AnyAtomicType */ XmlTypeCode.Item, /* UntypedAtomic */ XmlTypeCode.AnyAtomicType, /* String */ XmlTypeCode.AnyAtomicType, /* Boolean */ XmlTypeCode.AnyAtomicType, /* Decimal */ XmlTypeCode.AnyAtomicType, /* Float */ XmlTypeCode.AnyAtomicType, /* Double */ XmlTypeCode.AnyAtomicType, /* Duration */ XmlTypeCode.AnyAtomicType, /* DateTime */ XmlTypeCode.AnyAtomicType, /* Time */ XmlTypeCode.AnyAtomicType, /* Date */ XmlTypeCode.AnyAtomicType, /* GYearMonth */ XmlTypeCode.AnyAtomicType, /* GYear */ XmlTypeCode.AnyAtomicType, /* GMonthDay */ XmlTypeCode.AnyAtomicType, /* GDay */ XmlTypeCode.AnyAtomicType, /* GMonth */ XmlTypeCode.AnyAtomicType, /* HexBinary */ XmlTypeCode.AnyAtomicType, /* Base64Binary */ XmlTypeCode.AnyAtomicType, /* AnyUri */ XmlTypeCode.AnyAtomicType, /* QName */ XmlTypeCode.AnyAtomicType, /* Notation */ XmlTypeCode.AnyAtomicType, /* NormalizedString */ XmlTypeCode.String, /* Token */ XmlTypeCode.NormalizedString, /* Language */ XmlTypeCode.Token, /* NmToken */ XmlTypeCode.Token, /* Name */ XmlTypeCode.Token, /* NCName */ XmlTypeCode.Name, /* Id */ XmlTypeCode.NCName, /* Idref */ XmlTypeCode.NCName, /* Entity */ XmlTypeCode.NCName, /* Integer */ XmlTypeCode.Decimal, /* NonPositiveInteger */ XmlTypeCode.Integer, /* NegativeInteger */ XmlTypeCode.NonPositiveInteger, /* Long */ XmlTypeCode.Integer, /* Int */ XmlTypeCode.Long, /* Short */ XmlTypeCode.Int, /* Byte */ XmlTypeCode.Short, /* NonNegativeInteger */ XmlTypeCode.Integer, /* UnsignedLong */ XmlTypeCode.NonNegativeInteger, /* UnsignedInt */ XmlTypeCode.UnsignedLong, /* UnsignedShort */ XmlTypeCode.UnsignedInt, /* UnsignedByte */ XmlTypeCode.UnsignedShort, /* PositiveInteger */ XmlTypeCode.NonNegativeInteger, /* YearMonthDuration */ XmlTypeCode.Duration, /* DayTimeDuration */ XmlTypeCode.Duration, }; private static readonly string[] s_typeNames = { /* None */ "none", /* Item */ "item", /* Node */ "node", /* Document */ "document", /* Element */ "element", /* Attribute */ "attribute", /* Namespace */ "namespace", /* ProcessingInstruction */ "processing-instruction", /* Comment */ "comment", /* Text */ "text", /* AnyAtomicType */ "xdt:anyAtomicType", /* UntypedAtomic */ "xdt:untypedAtomic", /* String */ "xs:string", /* Boolean */ "xs:boolean", /* Decimal */ "xs:decimal", /* Float */ "xs:float", /* Double */ "xs:double", /* Duration */ "xs:duration", /* DateTime */ "xs:dateTime", /* Time */ "xs:time", /* Date */ "xs:date", /* GYearMonth */ "xs:gYearMonth", /* GYear */ "xs:gYear", /* GMonthDay */ "xs:gMonthDay", /* GDay */ "xs:gDay", /* GMonth */ "xs:gMonth", /* HexBinary */ "xs:hexBinary", /* Base64Binary */ "xs:base64Binary", /* AnyUri */ "xs:anyUri", /* QName */ "xs:QName", /* Notation */ "xs:NOTATION", /* NormalizedString */ "xs:normalizedString", /* Token */ "xs:token", /* Language */ "xs:language", /* NmToken */ "xs:NMTOKEN", /* Name */ "xs:Name", /* NCName */ "xs:NCName", /* Id */ "xs:ID", /* Idref */ "xs:IDREF", /* Entity */ "xs:ENTITY", /* Integer */ "xs:integer", /* NonPositiveInteger */ "xs:nonPositiveInteger", /* NegativeInteger */ "xs:negativeInteger", /* Long */ "xs:long", /* Int */ "xs:int", /* Short */ "xs:short", /* Byte */ "xs:byte", /* NonNegativeInteger */ "xs:nonNegativeInteger", /* UnsignedLong */ "xs:unsignedLong", /* UnsignedInt */ "xs:unsignedInt", /* UnsignedShort */ "xs:unsignedShort", /* UnsignedByte */ "xs:unsignedByte", /* PositiveInteger */ "xs:positiveInteger", /* YearMonthDuration */ "xdt:yearMonthDuration", /* DayTimeDuration */ "xdt:dayTimeDuration", }; private static readonly BitMatrix s_typeCodeDerivation = CreateTypeCodeDerivation(); private static BitMatrix CreateTypeCodeDerivation() { var matrix = new BitMatrix(s_baseTypeCodes.Length); for (int i = 0; i < s_baseTypeCodes.Length; i++) { int nextAncestor = i; while (true) { matrix[i, nextAncestor] = true; if ((int)s_baseTypeCodes[nextAncestor] == nextAncestor) break; nextAncestor = (int)s_baseTypeCodes[nextAncestor]; } } return matrix; } #endregion /// <summary> /// Implements an NxN bit matrix. /// </summary> private sealed class BitMatrix { private readonly ulong[] _bits; /// <summary> /// Create NxN bit matrix, where N = count. /// </summary> public BitMatrix(int count) { Debug.Assert(count < 64, "BitMatrix currently only handles up to 64x64 matrix."); _bits = new ulong[count]; } // /// <summary> // /// Return the number of rows and columns in the matrix. // /// </summary> // public int Size { // get { return bits.Length; } // } // /// <summary> /// Get or set a bit in the matrix at position (index1, index2). /// </summary> public bool this[int index1, int index2] { get { Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range."); return (_bits[index1] & ((ulong)1 << index2)) != 0; } set { Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range."); if (value == true) { _bits[index1] |= (ulong)1 << index2; } else { _bits[index1] &= ~((ulong)1 << index2); } } } /// <summary> /// Strongly typed indexer. /// </summary> public bool this[XmlTypeCode index1, XmlTypeCode index2] { get { return this[(int)index1, (int)index2]; } // set { // this[(int)index1, (int)index2] = value; // } } } } }
// 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.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using System.Threading; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal class Signature : ISignature { private const int MaxParamColumnCount = 100; private readonly SignatureHelpItem _signatureHelpItem; public Signature(ITrackingSpan applicableToSpan, SignatureHelpItem signatureHelpItem, int selectedParameterIndex) { if (selectedParameterIndex < -1 || selectedParameterIndex >= signatureHelpItem.Parameters.Length) { throw new ArgumentOutOfRangeException(nameof(selectedParameterIndex)); } this.ApplicableToSpan = applicableToSpan; _signatureHelpItem = signatureHelpItem; _parameterIndex = selectedParameterIndex; } private bool _isInitialized; private void EnsureInitialized() { if (!_isInitialized) { _isInitialized = true; Initialize(); } } private Signature InitializedThis { get { EnsureInitialized(); return this; } } private IList<SymbolDisplayPart> _displayParts; internal IList<SymbolDisplayPart> DisplayParts => InitializedThis._displayParts; public ITrackingSpan ApplicableToSpan { get; } private string _content; public string Content => InitializedThis._content; private int _parameterIndex = -1; public IParameter CurrentParameter { get { EnsureInitialized(); return _parameterIndex >= 0 && _parameters != null ? _parameters[_parameterIndex] : null; } } /// <remarks> /// The documentation is included in <see cref="Content"/> so that it will be classified. /// </remarks> public string Documentation => null; private ReadOnlyCollection<IParameter> _parameters; public ReadOnlyCollection<IParameter> Parameters => InitializedThis._parameters; private string _prettyPrintedContent; public string PrettyPrintedContent => InitializedThis._prettyPrintedContent; // This event is required by the ISignature interface but it's not actually used // (once created the CurrentParameter property cannot change) public event EventHandler<CurrentParameterChangedEventArgs> CurrentParameterChanged { add { } remove { } } private IList<SymbolDisplayPart> _prettyPrintedDisplayParts; internal IList<SymbolDisplayPart> PrettyPrintedDisplayParts { get { return InitializedThis._prettyPrintedDisplayParts; } set { _prettyPrintedDisplayParts = value; } } private void Initialize() { var content = new StringBuilder(); var prettyPrintedContent = new StringBuilder(); var parts = new List<SymbolDisplayPart>(); var prettyPrintedParts = new List<SymbolDisplayPart>(); var parameters = new List<IParameter>(); var signaturePrefixParts = _signatureHelpItem.PrefixDisplayParts; var signaturePrefixContent = _signatureHelpItem.PrefixDisplayParts.GetFullText(); AddRange(signaturePrefixParts, parts, prettyPrintedParts); Append(signaturePrefixContent, content, prettyPrintedContent); var separatorParts = _signatureHelpItem.SeparatorDisplayParts; var separatorContent = separatorParts.GetFullText(); var newLinePart = new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n"); var newLineContent = newLinePart.ToString(); var spacerPart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', signaturePrefixContent.Length)); var spacerContent = spacerPart.ToString(); var paramColumnCount = 0; for (int i = 0; i < _signatureHelpItem.Parameters.Length; i++) { var sigHelpParameter = _signatureHelpItem.Parameters[i]; var parameterPrefixParts = sigHelpParameter.PrefixDisplayParts; var parameterPrefixContext = sigHelpParameter.PrefixDisplayParts.GetFullText(); var parameterParts = AddOptionalBrackets(sigHelpParameter.IsOptional, sigHelpParameter.DisplayParts); var parameterContent = parameterParts.GetFullText(); var parameterSuffixParts = sigHelpParameter.SuffixDisplayParts; var parameterSuffixContext = sigHelpParameter.SuffixDisplayParts.GetFullText(); paramColumnCount += separatorContent.Length + parameterPrefixContext.Length + parameterContent.Length + parameterSuffixContext.Length; if (i > 0) { AddRange(separatorParts, parts, prettyPrintedParts); Append(separatorContent, content, prettyPrintedContent); if (paramColumnCount > MaxParamColumnCount) { prettyPrintedParts.Add(newLinePart); prettyPrintedParts.Add(spacerPart); prettyPrintedContent.Append(newLineContent); prettyPrintedContent.Append(spacerContent); paramColumnCount = 0; } } AddRange(parameterPrefixParts, parts, prettyPrintedParts); Append(parameterPrefixContext, content, prettyPrintedContent); parameters.Add(new Parameter(this, sigHelpParameter, parameterContent, content.Length, prettyPrintedContent.Length)); AddRange(parameterParts, parts, prettyPrintedParts); Append(parameterContent, content, prettyPrintedContent); AddRange(parameterSuffixParts, parts, prettyPrintedParts); Append(parameterSuffixContext, content, prettyPrintedContent); } AddRange(_signatureHelpItem.SuffixDisplayParts, parts, prettyPrintedParts); Append(_signatureHelpItem.SuffixDisplayParts.GetFullText(), content, prettyPrintedContent); if (_parameterIndex >= 0) { var sigHelpParameter = _signatureHelpItem.Parameters[_parameterIndex]; AddRange(sigHelpParameter.SelectedDisplayParts, parts, prettyPrintedParts); Append(sigHelpParameter.SelectedDisplayParts.GetFullText(), content, prettyPrintedContent); } AddRange(_signatureHelpItem.DescriptionParts, parts, prettyPrintedParts); Append(_signatureHelpItem.DescriptionParts.GetFullText(), content, prettyPrintedContent); var documentation = _signatureHelpItem.DocumentationFactory(CancellationToken.None).ToList(); if (documentation.Count > 0) { AddRange(new[] { newLinePart }, parts, prettyPrintedParts); Append(newLineContent, content, prettyPrintedContent); AddRange(documentation, parts, prettyPrintedParts); Append(documentation.GetFullText(), content, prettyPrintedContent); } _content = content.ToString(); _prettyPrintedContent = prettyPrintedContent.ToString(); _displayParts = parts.ToImmutableArrayOrEmpty(); _prettyPrintedDisplayParts = prettyPrintedParts.ToImmutableArrayOrEmpty(); _parameters = parameters.ToReadOnlyCollection(); } private void AddRange(IList<SymbolDisplayPart> values, List<SymbolDisplayPart> parts, List<SymbolDisplayPart> prettyPrintedParts) { parts.AddRange(values); prettyPrintedParts.AddRange(values); } private void Append(string text, StringBuilder content, StringBuilder prettyPrintedContent) { content.Append(text); prettyPrintedContent.Append(text); } private IList<SymbolDisplayPart> AddOptionalBrackets(bool isOptional, IList<SymbolDisplayPart> list) { if (isOptional) { var result = new List<SymbolDisplayPart>(); result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "[")); result.AddRange(list); result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "]")); return result; } return list; } } }
// 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.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Text; namespace System.Reflection.Metadata { /// <summary> /// Reads metadata as defined byte the ECMA 335 CLI specification. /// </summary> public sealed partial class MetadataReader { internal readonly NamespaceCache NamespaceCache; internal readonly MemoryBlock Block; // A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference). internal readonly int WinMDMscorlibRef; // Keeps the underlying memory alive. private readonly object _memoryOwnerObj; private readonly MetadataReaderOptions _options; private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> _lazyNestedTypesMap; #region Constructors /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// </remarks> public unsafe MetadataReader(byte* metadata, int length) : this(metadata, length, MetadataReaderOptions.Default, utf8Decoder: null, memoryOwner: null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain /// metadata from a PE image. /// </remarks> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options) : this(metadata, length, options, utf8Decoder: null, memoryOwner: null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain /// metadata from a PE image. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is not positive.</exception> /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception> /// <exception cref="ArgumentException">The encoding of <paramref name="utf8Decoder"/> is not <see cref="UTF8Encoding"/>.</exception> /// <exception cref="PlatformNotSupportedException">The current platform is big-endian.</exception> /// <exception cref="BadImageFormatException">Bad metadata header.</exception> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder) : this(metadata, length, options, utf8Decoder, memoryOwner: null) { } internal unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder, object memoryOwner) { // Do not throw here when length is 0. We'll throw BadImageFormatException later on, so that the caller doesn't need to // worry about the image (stream) being empty and can handle all image errors by catching BadImageFormatException. if (length < 0) { Throw.ArgumentOutOfRange(nameof(length)); } if (metadata == null) { Throw.ArgumentNull(nameof(metadata)); } if (utf8Decoder == null) { utf8Decoder = MetadataStringDecoder.DefaultUTF8; } if (!(utf8Decoder.Encoding is UTF8Encoding)) { Throw.InvalidArgument(SR.MetadataStringDecoderEncodingMustBeUtf8, nameof(utf8Decoder)); } Block = new MemoryBlock(metadata, length); _memoryOwnerObj = memoryOwner; _options = options; UTF8Decoder = utf8Decoder; var headerReader = new BlobReader(Block); ReadMetadataHeader(ref headerReader, out _versionString); _metadataKind = GetMetadataKind(_versionString); var streamHeaders = ReadStreamHeaders(ref headerReader); // storage header and stream headers: InitializeStreamReaders(Block, streamHeaders, out _metadataStreamKind, out var metadataTableStream, out var pdbStream); int[] externalTableRowCountsOpt; if (pdbStream.Length > 0) { int pdbStreamOffset = (int)(pdbStream.Pointer - metadata); ReadStandalonePortablePdbStream(pdbStream, pdbStreamOffset, out _debugMetadataHeader, out externalTableRowCountsOpt); } else { externalTableRowCountsOpt = null; } var tableReader = new BlobReader(metadataTableStream); ReadMetadataTableHeader(ref tableReader, out var heapSizes, out var metadataTableRowCounts, out _sortedTables); InitializeTableReaders(tableReader.GetMemoryBlockAt(0, tableReader.RemainingBytes), heapSizes, metadataTableRowCounts, externalTableRowCountsOpt); // This previously could occur in obfuscated assemblies but a check was added to prevent // it getting to this point Debug.Assert(AssemblyTable.NumberOfRows <= 1); // Although the specification states that the module table will have exactly one row, // the native metadata reader would successfully read files containing more than one row. // Such files exist in the wild and may be produced by obfuscators. if (pdbStream.Length == 0 && ModuleTable.NumberOfRows < 1) { throw new BadImageFormatException(SR.Format(SR.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows)); } // read NamespaceCache = new NamespaceCache(this); if (_metadataKind != MetadataKind.Ecma335) { WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection(); } } #endregion #region Metadata Headers private readonly string _versionString; private readonly MetadataKind _metadataKind; private readonly MetadataStreamKind _metadataStreamKind; private readonly DebugMetadataHeader _debugMetadataHeader; internal StringHeap StringHeap; internal BlobHeap BlobHeap; internal GuidHeap GuidHeap; internal UserStringHeap UserStringHeap; /// <summary> /// True if the metadata stream has minimal delta format. Used for EnC. /// </summary> /// <remarks> /// The metadata stream has minimal delta format if "#JTD" stream is present. /// Minimal delta format uses large size (4B) when encoding table/heap references. /// The heaps in minimal delta only contain data of the delta, /// there is no padding at the beginning of the heaps that would align them /// with the original full metadata heaps. /// </remarks> internal bool IsMinimalDelta; /// <summary> /// Looks like this function reads beginning of the header described in /// ECMA-335 24.2.1 Metadata root /// </summary> private void ReadMetadataHeader(ref BlobReader memReader, out string versionString) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader) { throw new BadImageFormatException(SR.MetadataHeaderTooSmall); } uint signature = memReader.ReadUInt32(); if (signature != COR20Constants.COR20MetadataSignature) { throw new BadImageFormatException(SR.MetadataSignature); } // major version memReader.ReadUInt16(); // minor version memReader.ReadUInt16(); // reserved: memReader.ReadUInt32(); int versionStringSize = memReader.ReadInt32(); if (memReader.RemainingBytes < versionStringSize) { throw new BadImageFormatException(SR.NotEnoughSpaceForVersionString); } int numberOfBytesRead; versionString = memReader.GetMemoryBlockAt(0, versionStringSize).PeekUtf8NullTerminated(0, null, UTF8Decoder, out numberOfBytesRead, '\0'); memReader.Offset += versionStringSize; } private MetadataKind GetMetadataKind(string versionString) { // Treat metadata as CLI raw metadata if the client doesn't want to see projections. if ((_options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0) { return MetadataKind.Ecma335; } if (!versionString.Contains("WindowsRuntime")) { return MetadataKind.Ecma335; } else if (versionString.Contains("CLR")) { return MetadataKind.ManagedWindowsMetadata; } else { return MetadataKind.WindowsMetadata; } } /// <summary> /// Reads stream headers described in ECMA-335 24.2.2 Stream header /// </summary> private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) { // storage header: memReader.ReadUInt16(); int streamCount = memReader.ReadInt16(); var streamHeaders = new StreamHeader[streamCount]; for (int i = 0; i < streamHeaders.Length; i++) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader) { throw new BadImageFormatException(SR.StreamHeaderTooSmall); } streamHeaders[i].Offset = memReader.ReadUInt32(); streamHeaders[i].Size = memReader.ReadInt32(); streamHeaders[i].Name = memReader.ReadUtf8NullTerminated(); bool aligned = memReader.TryAlign(4); if (!aligned || memReader.RemainingBytes == 0) { throw new BadImageFormatException(SR.NotEnoughSpaceForStreamHeaderName); } } return streamHeaders; } private void InitializeStreamReaders( in MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MetadataStreamKind metadataStreamKind, out MemoryBlock metadataTableStream, out MemoryBlock standalonePdbStream) { metadataTableStream = default; standalonePdbStream = default; metadataStreamKind = MetadataStreamKind.Illegal; foreach (StreamHeader streamHeader in streamHeaders) { switch (streamHeader.Name) { case COR20Constants.StringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForStringStream); } this.StringHeap = new StringHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.BlobStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.BlobHeap = new BlobHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.GUIDStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForGUIDStream); } this.GuidHeap = new GuidHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.UserStringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.UserStringHeap = new UserStringHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.CompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Compressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.UncompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Uncompressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.MinimalDeltaMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } // the content of the stream is ignored this.IsMinimalDelta = true; break; case COR20Constants.StandalonePdbStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } standalonePdbStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; default: // Skip unknown streams. Some obfuscators insert invalid streams. continue; } } if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed) { throw new BadImageFormatException(SR.InvalidMetadataStreamFormat); } } #endregion #region Tables and Heaps private readonly TableMask _sortedTables; /// <summary> /// A row count for each possible table. May be indexed by <see cref="TableIndex"/>. /// </summary> internal int[] TableRowCounts; internal ModuleTableReader ModuleTable; internal TypeRefTableReader TypeRefTable; internal TypeDefTableReader TypeDefTable; internal FieldPtrTableReader FieldPtrTable; internal FieldTableReader FieldTable; internal MethodPtrTableReader MethodPtrTable; internal MethodTableReader MethodDefTable; internal ParamPtrTableReader ParamPtrTable; internal ParamTableReader ParamTable; internal InterfaceImplTableReader InterfaceImplTable; internal MemberRefTableReader MemberRefTable; internal ConstantTableReader ConstantTable; internal CustomAttributeTableReader CustomAttributeTable; internal FieldMarshalTableReader FieldMarshalTable; internal DeclSecurityTableReader DeclSecurityTable; internal ClassLayoutTableReader ClassLayoutTable; internal FieldLayoutTableReader FieldLayoutTable; internal StandAloneSigTableReader StandAloneSigTable; internal EventMapTableReader EventMapTable; internal EventPtrTableReader EventPtrTable; internal EventTableReader EventTable; internal PropertyMapTableReader PropertyMapTable; internal PropertyPtrTableReader PropertyPtrTable; internal PropertyTableReader PropertyTable; internal MethodSemanticsTableReader MethodSemanticsTable; internal MethodImplTableReader MethodImplTable; internal ModuleRefTableReader ModuleRefTable; internal TypeSpecTableReader TypeSpecTable; internal ImplMapTableReader ImplMapTable; internal FieldRVATableReader FieldRvaTable; internal EnCLogTableReader EncLogTable; internal EnCMapTableReader EncMapTable; internal AssemblyTableReader AssemblyTable; internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused internal AssemblyOSTableReader AssemblyOSTable; // unused internal AssemblyRefTableReader AssemblyRefTable; internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused internal FileTableReader FileTable; internal ExportedTypeTableReader ExportedTypeTable; internal ManifestResourceTableReader ManifestResourceTable; internal NestedClassTableReader NestedClassTable; internal GenericParamTableReader GenericParamTable; internal MethodSpecTableReader MethodSpecTable; internal GenericParamConstraintTableReader GenericParamConstraintTable; // debug tables internal DocumentTableReader DocumentTable; internal MethodDebugInformationTableReader MethodDebugInformationTable; internal LocalScopeTableReader LocalScopeTable; internal LocalVariableTableReader LocalVariableTable; internal LocalConstantTableReader LocalConstantTable; internal ImportScopeTableReader ImportScopeTable; internal StateMachineMethodTableReader StateMachineMethodTable; internal CustomDebugInformationTableReader CustomDebugInformationTable; private void ReadMetadataTableHeader(ref BlobReader reader, out HeapSizes heapSizes, out int[] metadataTableRowCounts, out TableMask sortedTables) { if (reader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader) { throw new BadImageFormatException(SR.MetadataTableHeaderTooSmall); } // reserved (shall be ignored): reader.ReadUInt32(); // major version (shall be ignored): reader.ReadByte(); // minor version (shall be ignored): reader.ReadByte(); // heap sizes: heapSizes = (HeapSizes)reader.ReadByte(); // reserved (shall be ignored): reader.ReadByte(); ulong presentTables = reader.ReadUInt64(); sortedTables = (TableMask)reader.ReadUInt64(); // According to ECMA-335, MajorVersion and MinorVersion have fixed values and, // based on recommendation in 24.1 Fixed fields: When writing these fields it // is best that they be set to the value indicated, on reading they should be ignored. // We will not be checking version values. We will continue checking that the set of // present tables is within the set we understand. ulong validTables = (ulong)(TableMask.TypeSystemTables | TableMask.DebugTables); if ((presentTables & ~validTables) != 0) { throw new BadImageFormatException(SR.Format(SR.UnknownTables, presentTables)); } if (_metadataStreamKind == MetadataStreamKind.Compressed) { // In general Ptr tables and EnC tables are not allowed in a compressed stream. // However when asked for a snapshot of the current metadata after an EnC change has been applied // the CLR includes the EnCLog table into the snapshot. We need to be able to read the image, // so we'll allow the table here but pretend it's empty later. if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0) { throw new BadImageFormatException(SR.IllegalTablesInCompressedMetadataStream); } } metadataTableRowCounts = ReadMetadataTableRowCounts(ref reader, presentTables); if ((heapSizes & HeapSizes.ExtraData) == HeapSizes.ExtraData) { // Skip "extra data" used by some obfuscators. Although it is not mentioned in the CLI spec, // it is honored by the native metadata reader. reader.ReadUInt32(); } } private static int[] ReadMetadataTableRowCounts(ref BlobReader memReader, ulong presentTableMask) { ulong currentTableBit = 1; var rowCounts = new int[MetadataTokens.TableCount]; for (int i = 0; i < rowCounts.Length; i++) { if ((presentTableMask & currentTableBit) != 0) { if (memReader.RemainingBytes < sizeof(uint)) { throw new BadImageFormatException(SR.TableRowCountSpaceTooSmall); } uint rowCount = memReader.ReadUInt32(); if (rowCount > TokenTypeIds.RIDMask) { throw new BadImageFormatException(SR.Format(SR.InvalidRowCount, rowCount)); } rowCounts[i] = (int)rowCount; } currentTableBit <<= 1; } return rowCounts; } // internal for testing internal static void ReadStandalonePortablePdbStream(MemoryBlock pdbStreamBlock, int pdbStreamOffset, out DebugMetadataHeader debugMetadataHeader, out int[] externalTableRowCounts) { var reader = new BlobReader(pdbStreamBlock); const int PdbIdSize = 20; byte[] pdbId = reader.ReadBytes(PdbIdSize); // ECMA-335 15.4.1.2: // The entry point to an application shall be static. // This entry point method can be a global method or it can appear inside a type. // The entry point method shall either accept no arguments or a vector of strings. // The return type of the entry point method shall be void, int32, or unsigned int32. // The entry point method cannot be defined in a generic class. uint entryPointToken = reader.ReadUInt32(); int entryPointRowId = (int)(entryPointToken & TokenTypeIds.RIDMask); if (entryPointToken != 0 && ((entryPointToken & TokenTypeIds.TypeMask) != TokenTypeIds.MethodDef || entryPointRowId == 0)) { throw new BadImageFormatException(SR.Format(SR.InvalidEntryPointToken, entryPointToken)); } ulong externalTableMask = reader.ReadUInt64(); // EnC & Ptr tables can't be referenced from standalone PDB metadata: const ulong validTables = (ulong)TableMask.ValidPortablePdbExternalTables; if ((externalTableMask & ~validTables) != 0) { throw new BadImageFormatException(SR.Format(SR.UnknownTables, externalTableMask)); } externalTableRowCounts = ReadMetadataTableRowCounts(ref reader, externalTableMask); debugMetadataHeader = new DebugMetadataHeader( ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref pdbId), MethodDefinitionHandle.FromRowId(entryPointRowId), idStartOffset: pdbStreamOffset); } private const int SmallIndexSize = 2; private const int LargeIndexSize = 4; private int GetReferenceSize(int[] rowCounts, TableIndex index) { return (rowCounts[(int)index] < MetadataStreamConstants.LargeTableRowCount && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize; } private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, HeapSizes heapSizes, int[] rowCounts, int[] externalRowCountsOpt) { // Size of reference tags in each table. this.TableRowCounts = rowCounts; // TODO (https://github.com/dotnet/corefx/issues/2061): // Shouldn't XxxPtr table be always the same size or smaller than the corresponding Xxx table? // Compute ref sizes for tables that can have pointer tables int fieldRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.FieldPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Field); int methodRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.MethodPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.MethodDef); int paramRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.ParamPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Param); int eventRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.EventPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Event); int propertyRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.PropertyPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Property); // Compute the coded token ref sizes int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced); int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced); int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced); int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced); int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced); int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced); int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced); int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced); int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced); int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced); int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced); int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced); int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced); // Compute HeapRef Sizes int stringHeapRefSize = (heapSizes & HeapSizes.StringHeapLarge) == HeapSizes.StringHeapLarge ? LargeIndexSize : SmallIndexSize; int guidHeapRefSize = (heapSizes & HeapSizes.GuidHeapLarge) == HeapSizes.GuidHeapLarge ? LargeIndexSize : SmallIndexSize; int blobHeapRefSize = (heapSizes & HeapSizes.BlobHeapLarge) == HeapSizes.BlobHeapLarge ? LargeIndexSize : SmallIndexSize; // Populate the Table blocks int totalRequiredSize = 0; this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleTable.Block.Length; this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeRefTable.Block.Length; this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSizeSorted, methodRefSizeSorted, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeDefTable.Block.Length; this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldPtrTable.Block.Length; this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldTable.Block.Length; this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], GetReferenceSize(rowCounts, TableIndex.MethodDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodPtrTable.Block.Length; this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSizeSorted, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDefTable.Block.Length; this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], GetReferenceSize(rowCounts, TableIndex.Param), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamPtrTable.Block.Length; this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamTable.Block.Length; this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.InterfaceImplTable.Block.Length; this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MemberRefTable.Block.Length; this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ConstantTable.Block.Length; this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute], IsDeclaredSorted(TableMask.CustomAttribute), hasCustomAttributeRefSize, customAttributeTypeRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomAttributeTable.Block.Length; this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldMarshalTable.Block.Length; this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DeclSecurityTable.Block.Length; this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ClassLayoutTable.Block.Length; this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldLayoutTable.Block.Length; this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StandAloneSigTable.Block.Length; this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), eventRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventMapTable.Block.Length; this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], GetReferenceSize(rowCounts, TableIndex.Event), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventPtrTable.Block.Length; this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventTable.Block.Length; this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), propertyRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyMapTable.Block.Length; this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], GetReferenceSize(rowCounts, TableIndex.Property), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyPtrTable.Block.Length; this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyTable.Block.Length; this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), GetReferenceSize(rowCounts, TableIndex.MethodDef), hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSemanticsTable.Block.Length; this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodImplTable.Block.Length; this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleRefTable.Block.Length; this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeSpecTable.Block.Length; this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), GetReferenceSize(rowCounts, TableIndex.ModuleRef), memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImplMapTable.Block.Length; this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldRvaTable.Block.Length; this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, _metadataStreamKind); totalRequiredSize += this.EncLogTable.Block.Length; this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EncMapTable.Block.Length; this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyTable.Block.Length; this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyProcessorTable.Block.Length; this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyOSTable.Block.Length; this.AssemblyRefTable = new AssemblyRefTableReader(rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, _metadataKind); totalRequiredSize += this.AssemblyRefTable.Block.Length; this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length; this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefOSTable.Block.Length; this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FileTable.Block.Length; this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ExportedTypeTable.Block.Length; this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ManifestResourceTable.Block.Length; this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.NestedClassTable.Block.Length; this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamTable.Block.Length; this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSpecTable.Block.Length; this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), GetReferenceSize(rowCounts, TableIndex.GenericParam), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamConstraintTable.Block.Length; // debug tables: // Type-system metadata tables may be stored in a separate (external) metadata file. // We need to use the row counts of the external tables when referencing them. // Debug tables are local to the current metadata image and type system metadata tables are external and precede all debug tables. var combinedRowCounts = (externalRowCountsOpt != null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, firstLocalTableIndex: TableIndex.Document) : rowCounts; int methodRefSizeCombined = GetReferenceSize(combinedRowCounts, TableIndex.MethodDef); int hasCustomDebugInformationRefSizeCombined = ComputeCodedTokenSize(HasCustomDebugInformationTag.LargeRowSize, combinedRowCounts, HasCustomDebugInformationTag.TablesReferenced); this.DocumentTable = new DocumentTableReader(rowCounts[(int)TableIndex.Document], guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DocumentTable.Block.Length; this.MethodDebugInformationTable = new MethodDebugInformationTableReader(rowCounts[(int)TableIndex.MethodDebugInformation], GetReferenceSize(rowCounts, TableIndex.Document), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDebugInformationTable.Block.Length; this.LocalScopeTable = new LocalScopeTableReader(rowCounts[(int)TableIndex.LocalScope], IsDeclaredSorted(TableMask.LocalScope), methodRefSizeCombined, GetReferenceSize(rowCounts, TableIndex.ImportScope), GetReferenceSize(rowCounts, TableIndex.LocalVariable), GetReferenceSize(rowCounts, TableIndex.LocalConstant), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalScopeTable.Block.Length; this.LocalVariableTable = new LocalVariableTableReader(rowCounts[(int)TableIndex.LocalVariable], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalVariableTable.Block.Length; this.LocalConstantTable = new LocalConstantTableReader(rowCounts[(int)TableIndex.LocalConstant], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalConstantTable.Block.Length; this.ImportScopeTable = new ImportScopeTableReader(rowCounts[(int)TableIndex.ImportScope], GetReferenceSize(rowCounts, TableIndex.ImportScope), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImportScopeTable.Block.Length; this.StateMachineMethodTable = new StateMachineMethodTableReader(rowCounts[(int)TableIndex.StateMachineMethod], IsDeclaredSorted(TableMask.StateMachineMethod), methodRefSizeCombined, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StateMachineMethodTable.Block.Length; this.CustomDebugInformationTable = new CustomDebugInformationTableReader(rowCounts[(int)TableIndex.CustomDebugInformation], IsDeclaredSorted(TableMask.CustomDebugInformation), hasCustomDebugInformationRefSizeCombined, guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomDebugInformationTable.Block.Length; if (totalRequiredSize > metadataTablesMemoryBlock.Length) { throw new BadImageFormatException(SR.MetadataTablesTooSmall); } } private static int[] CombineRowCounts(int[] local, int[] external, TableIndex firstLocalTableIndex) { Debug.Assert(local.Length == external.Length); var rowCounts = new int[local.Length]; for (int i = 0; i < (int)firstLocalTableIndex; i++) { rowCounts[i] = external[i]; } for (int i = (int)firstLocalTableIndex; i < rowCounts.Length; i++) { rowCounts[i] = local[i]; } return rowCounts; } private int ComputeCodedTokenSize(int largeRowSize, int[] rowCounts, TableMask tablesReferenced) { if (IsMinimalDelta) { return LargeIndexSize; } bool isAllReferencedTablesSmall = true; ulong tablesReferencedMask = (ulong)tablesReferenced; for (int tableIndex = 0; tableIndex < MetadataTokens.TableCount; tableIndex++) { if ((tablesReferencedMask & 1) != 0) { isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCounts[tableIndex] < largeRowSize); } tablesReferencedMask >>= 1; } return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize; } private bool IsDeclaredSorted(TableMask index) { return (_sortedTables & index) != 0; } #endregion #region Helpers internal bool UseFieldPtrTable => FieldPtrTable.NumberOfRows > 0; internal bool UseMethodPtrTable => MethodPtrTable.NumberOfRows > 0; internal bool UseParamPtrTable => ParamPtrTable.NumberOfRows > 0; internal bool UseEventPtrTable => EventPtrTable.NumberOfRows > 0; internal bool UsePropertyPtrTable => PropertyPtrTable.NumberOfRows > 0; internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId) { int typeDefRowId = typeDef.RowId; firstFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId); if (firstFieldRowId == 0) { firstFieldRowId = 1; lastFieldRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastFieldRowId = (this.UseFieldPtrTable) ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows; } else { lastFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1; } } internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId) { int typeDefRowId = typeDef.RowId; firstMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId); if (firstMethodRowId == 0) { firstMethodRowId = 1; lastMethodRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastMethodRowId = (this.UseMethodPtrTable) ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows; } else { lastMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1; } } internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId) { int eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef); if (eventMapRowId == 0) { firstEventRowId = 1; lastEventRowId = 0; return; } firstEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId); if (eventMapRowId == this.EventMapTable.NumberOfRows) { lastEventRowId = this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows; } else { lastEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1; } } internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId) { int propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef); if (propertyMapRowId == 0) { firstPropertyRowId = 1; lastPropertyRowId = 0; return; } firstPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId); if (propertyMapRowId == this.PropertyMapTable.NumberOfRows) { lastPropertyRowId = (this.UsePropertyPtrTable) ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows; } else { lastPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1; } } internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId) { int rid = methodDef.RowId; firstParamRowId = this.MethodDefTable.GetParamStart(rid); if (firstParamRowId == 0) { firstParamRowId = 1; lastParamRowId = 0; } else if (rid == this.MethodDefTable.NumberOfRows) { lastParamRowId = (this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows); } else { lastParamRowId = this.MethodDefTable.GetParamStart(rid + 1) - 1; } } internal void GetLocalVariableRange(LocalScopeHandle scope, out int firstVariableRowId, out int lastVariableRowId) { int scopeRowId = scope.RowId; firstVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId); if (firstVariableRowId == 0) { firstVariableRowId = 1; lastVariableRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastVariableRowId = this.LocalVariableTable.NumberOfRows; } else { lastVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId + 1) - 1; } } internal void GetLocalConstantRange(LocalScopeHandle scope, out int firstConstantRowId, out int lastConstantRowId) { int scopeRowId = scope.RowId; firstConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId); if (firstConstantRowId == 0) { firstConstantRowId = 1; lastConstantRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastConstantRowId = this.LocalConstantTable.NumberOfRows; } else { lastConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId + 1) - 1; } } #endregion #region Public APIs /// <summary> /// Pointer to the underlying data. /// </summary> public unsafe byte* MetadataPointer => Block.Pointer; /// <summary> /// Length of the underlying data. /// </summary> public int MetadataLength => Block.Length; /// <summary> /// Options passed to the constructor. /// </summary> public MetadataReaderOptions Options => _options; /// <summary> /// Version string read from metadata header. /// </summary> public string MetadataVersion => _versionString; /// <summary> /// Information decoded from #Pdb stream, or null if the stream is not present. /// </summary> public DebugMetadataHeader DebugMetadataHeader => _debugMetadataHeader; /// <summary> /// The kind of the metadata (plain ECMA335, WinMD, etc.). /// </summary> public MetadataKind MetadataKind => _metadataKind; /// <summary> /// Comparer used to compare strings stored in metadata. /// </summary> public MetadataStringComparer StringComparer => new MetadataStringComparer(this); /// <summary> /// The decoder used by the reader to produce <see cref="string"/> instances from UTF8 encoded byte sequences. /// </summary> public MetadataStringDecoder UTF8Decoder { get; } /// <summary> /// Returns true if the metadata represent an assembly. /// </summary> public bool IsAssembly => AssemblyTable.NumberOfRows == 1; public AssemblyReferenceHandleCollection AssemblyReferences => new AssemblyReferenceHandleCollection(this); public TypeDefinitionHandleCollection TypeDefinitions => new TypeDefinitionHandleCollection(TypeDefTable.NumberOfRows); public TypeReferenceHandleCollection TypeReferences => new TypeReferenceHandleCollection(TypeRefTable.NumberOfRows); public CustomAttributeHandleCollection CustomAttributes => new CustomAttributeHandleCollection(this); public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes => new DeclarativeSecurityAttributeHandleCollection(this); public MemberReferenceHandleCollection MemberReferences => new MemberReferenceHandleCollection(MemberRefTable.NumberOfRows); public ManifestResourceHandleCollection ManifestResources => new ManifestResourceHandleCollection(ManifestResourceTable.NumberOfRows); public AssemblyFileHandleCollection AssemblyFiles => new AssemblyFileHandleCollection(FileTable.NumberOfRows); public ExportedTypeHandleCollection ExportedTypes => new ExportedTypeHandleCollection(ExportedTypeTable.NumberOfRows); public MethodDefinitionHandleCollection MethodDefinitions => new MethodDefinitionHandleCollection(this); public FieldDefinitionHandleCollection FieldDefinitions => new FieldDefinitionHandleCollection(this); public EventDefinitionHandleCollection EventDefinitions => new EventDefinitionHandleCollection(this); public PropertyDefinitionHandleCollection PropertyDefinitions => new PropertyDefinitionHandleCollection(this); public DocumentHandleCollection Documents => new DocumentHandleCollection(this); public MethodDebugInformationHandleCollection MethodDebugInformation => new MethodDebugInformationHandleCollection(this); public LocalScopeHandleCollection LocalScopes => new LocalScopeHandleCollection(this, 0); public LocalVariableHandleCollection LocalVariables => new LocalVariableHandleCollection(this, default(LocalScopeHandle)); public LocalConstantHandleCollection LocalConstants => new LocalConstantHandleCollection(this, default(LocalScopeHandle)); public ImportScopeCollection ImportScopes => new ImportScopeCollection(this); public CustomDebugInformationHandleCollection CustomDebugInformation => new CustomDebugInformationHandleCollection(this); public AssemblyDefinition GetAssemblyDefinition() { if (!IsAssembly) { throw new InvalidOperationException(SR.MetadataImageDoesNotRepresentAnAssembly); } return new AssemblyDefinition(this); } public string GetString(StringHandle handle) { return StringHeap.GetString(handle, UTF8Decoder); } public string GetString(NamespaceDefinitionHandle handle) { if (handle.HasFullName) { return StringHeap.GetString(handle.GetFullName(), UTF8Decoder); } return NamespaceCache.GetFullName(handle); } public byte[] GetBlobBytes(BlobHandle handle) { return BlobHeap.GetBytes(handle); } public ImmutableArray<byte> GetBlobContent(BlobHandle handle) { // TODO: We can skip a copy for virtual blobs. byte[] bytes = GetBlobBytes(handle); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetBlobReader(BlobHandle handle) { return BlobHeap.GetBlobReader(handle); } public BlobReader GetBlobReader(StringHandle handle) { return StringHeap.GetBlobReader(handle); } public string GetUserString(UserStringHandle handle) { return UserStringHeap.GetString(handle); } public Guid GetGuid(GuidHandle handle) { return GuidHeap.GetGuid(handle); } public ModuleDefinition GetModuleDefinition() { if (_debugMetadataHeader != null) { throw new InvalidOperationException(SR.StandaloneDebugMetadataImageDoesNotContainModuleTable); } return new ModuleDefinition(this); } public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle) { return new AssemblyReference(this, handle.Value); } public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle)); } public NamespaceDefinition GetNamespaceDefinitionRoot() { NamespaceData data = NamespaceCache.GetRootNamespace(); return new NamespaceDefinition(data); } public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle) { NamespaceData data = NamespaceCache.GetNamespaceData(handle); return new NamespaceDefinition(data); } private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeDefTreatmentAndRowId(handle); } public TypeReference GetTypeReference(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle)); } private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeRefTreatmentAndRowId(handle); } public ExportedType GetExportedType(ExportedTypeHandle handle) { return new ExportedType(this, handle.RowId); } public CustomAttributeHandleCollection GetCustomAttributes(EntityHandle handle) { return new CustomAttributeHandleCollection(this, handle); } public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle)); } private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId); } public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new DeclarativeSecurityAttribute(this, handle.RowId); } public Constant GetConstant(ConstantHandle handle) { return new Constant(this, handle.RowId); } public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle)); } private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMethodDefTreatmentAndRowId(handle); } public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle)); } private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateFieldDefTreatmentAndRowId(handle); } public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle) { return new PropertyDefinition(this, handle); } public EventDefinition GetEventDefinition(EventDefinitionHandle handle) { return new EventDefinition(this, handle); } public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle) { return new MethodImplementation(this, handle); } public MemberReference GetMemberReference(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle)); } private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMemberRefTreatmentAndRowId(handle); } public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle) { return new MethodSpecification(this, handle); } public Parameter GetParameter(ParameterHandle handle) { return new Parameter(this, handle); } public GenericParameter GetGenericParameter(GenericParameterHandle handle) { return new GenericParameter(this, handle); } public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle) { return new GenericParameterConstraint(this, handle); } public ManifestResource GetManifestResource(ManifestResourceHandle handle) { return new ManifestResource(this, handle); } public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle) { return new AssemblyFile(this, handle); } public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle) { return new StandaloneSignature(this, handle); } public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle) { return new TypeSpecification(this, handle); } public ModuleReference GetModuleReference(ModuleReferenceHandle handle) { return new ModuleReference(this, handle); } public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle) { return new InterfaceImplementation(this, handle); } internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef) { int methodRowId; if (UseMethodPtrTable) { methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId); } else { methodRowId = methodDef.RowId; } return TypeDefTable.FindTypeContainingMethod(methodRowId, MethodDefTable.NumberOfRows); } internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef) { int fieldRowId; if (UseFieldPtrTable) { fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId); } else { fieldRowId = fieldDef.RowId; } return TypeDefTable.FindTypeContainingField(fieldRowId, FieldTable.NumberOfRows); } public string GetString(DocumentNameBlobHandle handle) { return BlobHeap.GetDocumentName(handle); } public Document GetDocument(DocumentHandle handle) { return new Document(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDebugInformationHandle handle) { return new MethodDebugInformation(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDefinitionHandle handle) { return new MethodDebugInformation(this, MethodDebugInformationHandle.FromRowId(handle.RowId)); } public LocalScope GetLocalScope(LocalScopeHandle handle) { return new LocalScope(this, handle); } public LocalVariable GetLocalVariable(LocalVariableHandle handle) { return new LocalVariable(this, handle); } public LocalConstant GetLocalConstant(LocalConstantHandle handle) { return new LocalConstant(this, handle); } public ImportScope GetImportScope(ImportScopeHandle handle) { return new ImportScope(this, handle); } public CustomDebugInformation GetCustomDebugInformation(CustomDebugInformationHandle handle) { return new CustomDebugInformation(this, handle); } public CustomDebugInformationHandleCollection GetCustomDebugInformation(EntityHandle handle) { return new CustomDebugInformationHandleCollection(this, handle); } public LocalScopeHandleCollection GetLocalScopes(MethodDefinitionHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } public LocalScopeHandleCollection GetLocalScopes(MethodDebugInformationHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } #endregion #region Nested Types private void InitializeNestedTypesMap() { var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>(); int numberOfNestedTypes = NestedClassTable.NumberOfRows; ImmutableArray<TypeDefinitionHandle>.Builder builder = null; TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle); for (int i = 1; i <= numberOfNestedTypes; i++) { TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i); Debug.Assert(!enclosingClass.IsNil); if (enclosingClass != previousEnclosingClass) { if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder)) { builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); groupedNestedTypes.Add(enclosingClass, builder); } previousEnclosingClass = enclosingClass; } else { Debug.Assert(builder == groupedNestedTypes[enclosingClass]); } builder.Add(NestedClassTable.GetNestedClass(i)); } var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>(); foreach (var group in groupedNestedTypes) { nestedTypesMap.Add(group.Key, group.Value.ToImmutable()); } _lazyNestedTypesMap = nestedTypesMap; } /// <summary> /// Returns an array of types nested in the specified type. /// </summary> internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef) { if (_lazyNestedTypesMap == null) { InitializeNestedTypesMap(); } ImmutableArray<TypeDefinitionHandle> nestedTypes; if (_lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes)) { return nestedTypes; } return ImmutableArray<TypeDefinitionHandle>.Empty; } #endregion } }
using System; using GuruComponents.Netrix.HtmlFormatting.Elements; namespace GuruComponents.Netrix.WebEditing.Elements { /// <summary> /// This class is used to store information about the kind of element. /// </summary> /// <remarks> /// It is used internally to control the formatting behavior. Externally it is used to provide such information for plug-in modules. /// </remarks> public class AspTagInfo : ITagInfo { private string _tagName; private WhiteSpaceType _inner; private WhiteSpaceType _following; private FormattingFlags _flags; private ElementType _type; private string _alias; /// <summary> /// The type of element controls the generel formatting behavior. /// </summary> public ElementType Type { get { return _type; } } /// <summary> /// Determines how to format this kind of element. /// </summary> public FormattingFlags Flags { get { return _flags; } } /// <summary> /// Determines how significant are whitespaces following this element. /// </summary> public WhiteSpaceType FollowingWhiteSpaceType { get { return _following; } } /// <summary> /// Determines how significant are whitespaces within this element. /// </summary> public WhiteSpaceType InnerWhiteSpaceType { get { return _inner; } } /// <summary> /// The element has to treated as comment. /// </summary> public bool IsComment { get { return (_flags & FormattingFlags.Comment) == 0 == false; } } /// <summary> /// The element is an inline element. /// </summary> public bool IsInline { get { return (_flags & FormattingFlags.Inline) == 0 == false; } } /// <summary> /// The element has to be treated as pure XML. /// </summary> public bool IsXml { get { return (_flags & FormattingFlags.Xml) == 0 == false; } } /// <summary> /// The element does not has an end tag, e.g. it is not a container. /// </summary> public bool NoEndTag { get { return (_flags & FormattingFlags.NoEndTag) == 0 == false; } } /// <summary> /// The element does not being indented, even if it starts at a new line. /// </summary> public bool NoIndent { get { if ((_flags & FormattingFlags.NoIndent) == 0) { return NoEndTag; } else { return true; } } } /// <summary> /// The element is supposed to preserve its content. /// </summary> public bool PreserveContent { get { return (_flags & FormattingFlags.PreserveContent) == 0 == false; } } /// <summary> /// The tag name of the element. /// </summary> public string TagName { get { return String.Concat(_alias, ":", _tagName); } } /// <overloads/> /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> public AspTagInfo(string tagName, FormattingFlags flags) : this(tagName, flags, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, ElementType.Other) { } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> /// <param name="type"></param> public AspTagInfo(string tagName, FormattingFlags flags, ElementType type) : this(tagName, flags, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, type) { } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> /// <param name="innerWhiteSpace"></param> /// <param name="followingWhiteSpace"></param> public AspTagInfo(string tagName, FormattingFlags flags, WhiteSpaceType innerWhiteSpace, WhiteSpaceType followingWhiteSpace) : this(tagName, flags, innerWhiteSpace, followingWhiteSpace, ElementType.Other) { } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> /// <param name="innerWhiteSpace"></param> /// <param name="followingWhiteSpace"></param> /// <param name="type"></param> public AspTagInfo(string tagName, FormattingFlags flags, WhiteSpaceType innerWhiteSpace, WhiteSpaceType followingWhiteSpace, ElementType type) { SetTagName(tagName); _inner = innerWhiteSpace; _following = followingWhiteSpace; _flags = flags; _type = type; } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="newTagName"></param> /// <param name="info"></param> public AspTagInfo(string newTagName, ITagInfo info) { SetTagName(newTagName); _inner = info.InnerWhiteSpaceType; _following = info.FollowingWhiteSpaceType; _flags = info.Flags; _type = info.Type; } private void SetTagName(string tagName) { if (tagName.IndexOf(":") != -1) { string[] ns = tagName.Split(':'); _alias = ns[0]; _tagName = ns[1]; } else { _alias = "asp"; _tagName = tagName; } } /// <summary> /// Informs that a element can carry another one. /// </summary> /// <remarks> /// This method always returns true. Classes derive from <see cref="TagInfo"/> may /// overwrite it to control the behavior of complex elements. /// </remarks> /// <param name="info"></param> /// <returns></returns> public virtual bool CanContainTag(ITagInfo info) { return true; } } }
// // tabcontrol2.cs: sample user control. // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // Licensed under the terms of the MIT X11 license // // (C) 2002 Ximian, Inc (http://www.ximian.com) // using System; using System.Collections; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace Mono.Controls { [ParseChildren(false)] public class TabContent : Control { string label; public TabContent () { } protected override void Render (HtmlTextWriter writer) { if (this.Parent.GetType () != typeof (Tabs2)) throw new ApplicationException ("TabContent can only be rendered inside Tabs2"); base.Render (writer); } public string Label { get { if (label == null) return "* You did not set a label for this control *"; return label; } set { label = value; } } } [ParseChildren(false)] public class Tabs2 : UserControl, IPostBackEventHandler, IParserAccessor { Hashtable localValues; ArrayList titles; public Tabs2 () { titles = new ArrayList (); localValues = new Hashtable (); } private void AddTab (TabContent tabContent) { string title = tabContent.Label; Controls.Add (tabContent); titles.Add (title); if (Controls.Count == 1) CurrentTabName = title; } protected override object SaveViewState () { return new Triplet (base.SaveViewState (), localValues, titles); } protected override void LoadViewState (object savedState) { if (savedState != null) { Triplet saved = (Triplet) savedState; base.LoadViewState (saved.First); localValues = saved.Second as Hashtable; titles = saved.Third as ArrayList; } } protected override void OnPreRender (EventArgs e) { base.OnPreRender (e); Page.GetPostBackEventReference (this); foreach (TabContent content in Controls) { if (content.Label == CurrentTabName) content.Visible = true; else content.Visible = false; } } void IPostBackEventHandler.RaisePostBackEvent (string argument) { if (argument == null) return; if (CurrentTabName != argument) CurrentTabName = argument; } protected override ControlCollection CreateControlCollection () { return new ControlCollection (this); } protected override void AddParsedSubObject (object obj) { if (obj is LiteralControl) return; // Ignore plain text if (!(obj is TabContent)) throw new ArgumentException ("Tabs2 Only allows TabContent controls inside.", "obj"); AddTab ((TabContent) obj); } void IParserAccessor.AddParsedSubObject (object obj) { AddParsedSubObject (obj); } private void RenderBlank (HtmlTextWriter writer) { writer.WriteBeginTag ("td"); writer.WriteAttribute ("bgcolor", TabBackColor); writer.WriteAttribute ("width", BlankWidth.ToString ()); writer.Write (">"); writer.Write ("&nbsp;"); writer.WriteEndTag ("td"); } private void RenderTabs (HtmlTextWriter writer) { writer.WriteBeginTag ("tr"); writer.Write (">"); writer.WriteLine (); if (titles.Count > 0) RenderBlank (writer); string currentTab = CurrentTabName; string key; int end = titles.Count; for (int i = 0; i < end; i++) { key = (string) titles [i]; writer.WriteBeginTag ("td"); writer.WriteAttribute ("width", Width.ToString ()); writer.WriteAttribute ("align", Align.ToString ()); if (key == currentTab) { writer.WriteAttribute ("bgcolor", CurrentTabBackColor); writer.Write (">"); writer.WriteBeginTag ("font"); writer.WriteAttribute ("color", CurrentTabColor); writer.Write (">"); writer.Write (key); writer.WriteEndTag ("font"); } else { writer.WriteAttribute ("bgcolor", TabBackColor); writer.Write (">"); writer.WriteBeginTag ("a"); string postbackEvent = String.Empty; if (Page != null) postbackEvent = Page.ClientScript.GetPostBackClientHyperlink ( this, key); writer.WriteAttribute ("href", postbackEvent); writer.Write (">"); writer.Write (key); writer.WriteEndTag ("a"); } writer.WriteEndTag ("td"); RenderBlank (writer); writer.WriteLine (); } writer.WriteEndTag ("tr"); writer.WriteBeginTag ("tr"); writer.Write (">"); writer.WriteLine (); writer.WriteBeginTag ("td"); writer.WriteAttribute ("colspan", "10"); writer.WriteAttribute ("bgcolor", CurrentTabBackColor); writer.Write (">"); writer.WriteBeginTag ("img"); writer.WriteAttribute ("width", "1"); writer.WriteAttribute ("height", "1"); writer.WriteAttribute ("alt", ""); writer.Write (">"); writer.WriteEndTag ("td"); writer.WriteEndTag ("tr"); } protected override void Render (HtmlTextWriter writer) { if (Page != null) Page.VerifyRenderingInServerForm (this); if (Controls.Count == 0) return; writer.WriteBeginTag ("table"); writer.WriteAttribute ("border", "0"); writer.WriteAttribute ("cellpadding", "0"); writer.WriteAttribute ("cellspacing", "0"); writer.Write (">"); writer.WriteBeginTag ("tbody"); writer.Write (">"); writer.WriteLine (); RenderTabs (writer); writer.WriteEndTag ("tbody"); writer.WriteEndTag ("table"); writer.WriteLine (); base.RenderChildren (writer); } public int BlankWidth { get { object o = localValues ["BlankWidth"]; if (o == null) return 15; return (int) o; } set { localValues ["BlankWidth"] = value; } } public int Width { get { object o = localValues ["Width"]; if (o == null) return 120; return (int) o; } set { localValues ["Width"] = value; } } public string Align { get { object o = localValues ["Align"]; if (o == null) return "center"; return (string) o; } set { localValues ["Align"] = value; } } public string CurrentTabName { get { object o = localValues ["CurrentTabName"]; if (o == null) return String.Empty; return (string) localValues ["CurrentTabName"]; } set { localValues ["CurrentTabName"] = value; } } public string CurrentTabColor { get { object o = localValues ["CurrentTabColor"]; if (o == null) return "#FFFFFF"; return (string) localValues ["CurrentTabColor"]; } set { localValues ["CurrentTabColor"] = value; } } public string CurrentTabBackColor { get { object o = localValues ["CurrentTabBackColor"]; if (o == null) return "#3366CC"; return (string) localValues ["CurrentTabBackColor"]; } set { localValues ["CurrentTabBackColor"] = value; } } public string TabBackColor { get { object o = localValues ["TabBackColor"]; if (o == null) return "#efefef"; return (string) localValues ["TabBackColor"]; } set { localValues ["TabBackColor"] = value; } } } }
using System; using LanguageExt; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using LanguageExt.DataTypes.Serialisation; using LanguageExt.TypeClasses; using LanguageExt.ClassInstances; using static LanguageExt.Prelude; namespace LanguageExt { public static partial class EitherAsyncT { // // Collections // public static EitherAsync<L, Arr<B>> Traverse<L, A, B>(this Arr<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Arr<B>>(Go(ma, f)); async Task<EitherData<L, Arr<B>>> Go(Arr<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L,Arr<B>>(d.Left)).Head() : EitherData.Right<L, Arr<B>>(new Arr<B>(rb.Map(d => d.Right))); } } public static EitherAsync<L, HashSet<B>> Traverse<L, A, B>(this HashSet<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, HashSet<B>>(Go(ma, f)); async Task<EitherData<L, HashSet<B>>> Go(HashSet<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L,HashSet<B>>(d.Left)).Head() : EitherData.Right<L, HashSet<B>>(new HashSet<B>(rb.Map(d => d.Right))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static EitherAsync<L, IEnumerable<B>> Traverse<L, A, B>(this IEnumerable<EitherAsync<L, A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static EitherAsync<L, IEnumerable<B>> TraverseSerial<L, A, B>(this IEnumerable<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, IEnumerable<B>>(Go(ma, f)); async Task<EitherData<L, IEnumerable<B>>> Go(IEnumerable<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { var mb = await a; if (mb.IsBottom) return default(EitherData<L, IEnumerable<B>>); if (mb.IsLeft) return EitherData.Left<L, IEnumerable<B>>(mb.LeftValue); rb.Add(f(mb.RightValue)); } return EitherData.Right<L, IEnumerable<B>>(rb); }; } public static EitherAsync<L, IEnumerable<B>> TraverseParallel<L, A, B>(this IEnumerable<EitherAsync<L, A>> ma, Func<A, B> f) => TraverseParallel(ma, Sys.DefaultAsyncSequenceConcurrency, f); public static EitherAsync<L, IEnumerable<B>> TraverseParallel<L, A, B>(this IEnumerable<EitherAsync<L, A>> ma, int windowSize, Func<A, B> f) { return new EitherAsync<L, IEnumerable<B>>(Go(ma, f)); async Task<EitherData<L, IEnumerable<B>>> Go(IEnumerable<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Data).WindowMap(windowSize, identity); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L,IEnumerable<B>>(d.Left)).Head() : EitherData.Right<L, IEnumerable<B>>(rb.Map(d => d.Right)); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static EitherAsync<L, IEnumerable<A>> Sequence<L, A>(this IEnumerable<EitherAsync<L, A>> ma) => TraverseParallel(ma, Prelude.identity); public static EitherAsync<L, IEnumerable<A>> SequenceSerial<L, A>(this IEnumerable<EitherAsync<L, A>> ma) => TraverseSerial(ma, Prelude.identity); public static EitherAsync<L, IEnumerable<A>> SequenceParallel<L, A>(this IEnumerable<EitherAsync<L, A>> ma) => TraverseParallel(ma, Prelude.identity); public static EitherAsync<L, IEnumerable<A>> SequenceParallel<L, A>(this IEnumerable<EitherAsync<L, A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static EitherAsync<L, Lst<B>> Traverse<L, A, B>(this Lst<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Lst<B>>(Go(ma, f)); async Task<EitherData<L, Lst<B>>> Go(Lst<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L,Lst<B>>(d.Left)).Head() : EitherData.Right<L, Lst<B>>(new Lst<B>(rb.Map(d => d.Right))); } } public static EitherAsync<L, Que<B>> Traverse<L, A, B>(this Que<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Que<B>>(Go(ma, f)); async Task<EitherData<L, Que<B>>> Go(Que<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L,Que<B>>(d.Left)).Head() : EitherData.Right<L, Que<B>>(new Que<B>(rb.Map(d => d.Right))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static EitherAsync<L, Seq<B>> Traverse<L, A, B>(this Seq<EitherAsync<L, A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static EitherAsync<L, Seq<B>> TraverseSerial<L, A, B>(this Seq<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Seq<B>>(Go(ma, f)); async Task<EitherData<L, Seq<B>>> Go(Seq<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = new B[ma.Count]; var ix = 0; foreach (var a in ma) { var mb = await a; if (mb.IsBottom) return default(EitherData<L, Seq<B>>); if (mb.IsLeft) return EitherData.Left<L, Seq<B>>(mb.LeftValue); rb[ix] = f(mb.RightValue); ix++; } return EitherData.Right<L, Seq<B>>(Seq.FromArray<B>(rb)); }; } public static EitherAsync<L, Seq<B>> TraverseParallel<L, A, B>(this Seq<EitherAsync<L, A>> ma, Func<A, B> f) => TraverseParallel(ma, Sys.DefaultAsyncSequenceConcurrency, f); public static EitherAsync<L, Seq<B>> TraverseParallel<L, A, B>(this Seq<EitherAsync<L, A>> ma, int windowSize, Func<A, B> f) { return new EitherAsync<L, Seq<B>>(Go(ma, f)); async Task<EitherData<L, Seq<B>>> Go(Seq<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Data).WindowMap(windowSize, identity); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L, Seq<B>>(d.Left)).Head() : EitherData.Right<L, Seq<B>>(Seq.FromArray(rb.Map(d => d.Right).ToArray())); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static EitherAsync<L, Seq<A>> Sequence<L, A>(this Seq<EitherAsync<L, A>> ma) => TraverseParallel(ma, Prelude.identity); public static EitherAsync<L, Seq<A>> SequenceSerial<L, A>(this Seq<EitherAsync<L, A>> ma) => TraverseSerial(ma, Prelude.identity); public static EitherAsync<L, Seq<A>> SequenceParallel<L, A>(this Seq<EitherAsync<L, A>> ma) => TraverseParallel(ma, Prelude.identity); public static EitherAsync<L, Seq<A>> SequenceParallel<L, A>(this Seq<EitherAsync<L, A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static EitherAsync<L, Set<B>> Traverse<L, A, B>(this Set<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Set<B>>(Go(ma, f)); async Task<EitherData<L, Set<B>>> Go(Set<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L,Set<B>>(d.Left)).Head() : EitherData.Right<L, Set<B>>(new Set<B>(rb.Map(d => d.Right))); } } public static EitherAsync<L, Stck<B>> Traverse<L, A, B>(this Stck<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Stck<B>>(Go(ma, f)); async Task<EitherData<L, Stck<B>>> Go(Stck<EitherAsync<L, A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Reverse().Map(a => a.Map(f).Data)); return rb.Exists(d => d.State == EitherStatus.IsLeft) ? rb.Filter(d => d.State == EitherStatus.IsLeft).Map(d => EitherData.Left<L,Stck<B>>(d.Left)).Head() : EitherData.Right<L, Stck<B>>(new Stck<B>(rb.Map(d => d.Right))); } } // // Async types // public static EitherAsync<L, EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, EitherAsync<L, B>>(Go(ma, f)); async Task<EitherData<L, EitherAsync<L, B>>> Go(EitherAsync<L, EitherAsync<L, A>> ma, Func<A, B> f) { var da = await ma.Data; if (da.State == EitherStatus.IsBottom) return EitherData<L, EitherAsync<L, B>>.Bottom; if (da.State == EitherStatus.IsLeft) return EitherData.Right<L, EitherAsync<L, B>>(EitherAsync<L, B>.Left(da.Left)); var db = await da.Right.Data; if (db.State == EitherStatus.IsBottom) return EitherData<L, EitherAsync<L, B>>.Bottom; if (db.State == EitherStatus.IsLeft) return EitherData.Left<L, EitherAsync<L, B>>(db.Left); return EitherData.Right<L, EitherAsync<L, B>>(EitherAsync<L, B>.Right(f(db.Right))); } } public static EitherAsync<L, OptionAsync<B>> Traverse<L, A, B>(this OptionAsync<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, OptionAsync<B>>(Go(ma, f)); async Task<EitherData<L, OptionAsync<B>>> Go(OptionAsync<EitherAsync<L, A>> ma, Func<A, B> f) { var (isSome, value) = await ma.Data; if (!isSome) return EitherData.Right<L, OptionAsync<B>>(OptionAsync<B>.None); var db = await value.Data; if (db.State == EitherStatus.IsBottom) return EitherData<L, OptionAsync<B>>.Bottom; if (db.State == EitherStatus.IsLeft) return EitherData.Left<L, OptionAsync<B>>(db.Left); return EitherData.Right<L, OptionAsync<B>>(OptionAsync<B>.Some(f(db.Right))); } } public static EitherAsync<L, TryAsync<B>> Traverse<L, A, B>(this TryAsync<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, TryAsync<B>>(Go(ma, f)); async Task<EitherData<L, TryAsync<B>>> Go(TryAsync<EitherAsync<L, A>> ma, Func<A, B> f) { var result = await ma.Try(); if (result.IsBottom) return EitherData<L, TryAsync<B>>.Bottom; if (result.IsFaulted) return EitherData.Right<L, TryAsync<B>>(TryAsyncFail<B>(result.Exception)); var db = await result.Value.Data; if (db.State == EitherStatus.IsBottom) return EitherData<L, TryAsync<B>>.Bottom; if (db.State == EitherStatus.IsLeft) return EitherData.Left<L, TryAsync<B>>(db.Left); return EitherData.Right<L, TryAsync<B>>(TryAsync<B>(f(db.Right))); } } public static EitherAsync<L, TryOptionAsync<B>> Traverse<L, A, B>(this TryOptionAsync<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, TryOptionAsync<B>>(Go(ma, f)); async Task<EitherData<L, TryOptionAsync<B>>> Go(TryOptionAsync<EitherAsync<L, A>> ma, Func<A, B> f) { var result = await ma.Try(); if (result.IsBottom) return EitherData<L, TryOptionAsync<B>>.Bottom; if (result.IsFaulted) return EitherData.Right<L, TryOptionAsync<B>>(TryOptionAsyncFail<B>(result.Exception)); if (result.IsNone) return EitherData.Right<L, TryOptionAsync<B>>(TryOptionAsync<B>(None)); var db = await result.Value.Value.Data; if (db.State == EitherStatus.IsBottom) return EitherData<L, TryOptionAsync<B>>.Bottom; if (db.State == EitherStatus.IsLeft) return EitherData.Left<L, TryOptionAsync<B>>(db.Left); return EitherData.Right<L, TryOptionAsync<B>>(TryOptionAsync<B>(f(db.Right))); } } public static EitherAsync<L, Task<B>> Traverse<L, A, B>(this Task<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Task<B>>(Go(ma, f)); async Task<EitherData<L, Task<B>>> Go(Task<EitherAsync<L, A>> ma, Func<A, B> f) { var result = await ma; var db = await result.Data; if (db.State == EitherStatus.IsBottom) return EitherData<L, Task<B>>.Bottom; if (db.State == EitherStatus.IsLeft) return EitherData.Left<L, Task<B>>(db.Left); return EitherData.Right<L, Task<B>>(f(db.Right).AsTask()); } } // // Sync types // public static EitherAsync<L, Either<L, B>> Traverse<L, A, B>(this Either<L, EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Either<L, B>>(Go(ma, f)); async Task<EitherData<L, Either<L, B>>> Go(Either<L, EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsBottom) return EitherData<L, Either<L, B>>.Bottom; if(ma.IsLeft) return EitherData.Right<L, Either<L, B>>(Left(ma.LeftValue)); var da = await ma.RightValue.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, Either<L, B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, Either<L, B>>(da.Left); return EitherData.Right<L, Either<L, B>>(f(da.Right)); } } public static EitherAsync<L, EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, EitherUnsafe<L, B>>(Go(ma, f)); async Task<EitherData<L, EitherUnsafe<L, B>>> Go(EitherUnsafe<L, EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsBottom) return EitherData<L, EitherUnsafe<L, B>>.Bottom; if(ma.IsLeft) return EitherData.Right<L, EitherUnsafe<L, B>>(Left(ma.LeftValue)); var da = await ma.RightValue.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, EitherUnsafe<L, B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, EitherUnsafe<L, B>>(da.Left); return EitherData.Right<L, EitherUnsafe<L, B>>(f(da.Right)); } } public static EitherAsync<L, Identity<B>> Traverse<L, A, B>(this Identity<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Identity<B>>(Go(ma, f)); async Task<EitherData<L, Identity<B>>> Go(Identity<EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsBottom) return EitherData<L, Identity<B>>.Bottom; var da = await ma.Value.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, Identity<B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, Identity<B>>(da.Left); return EitherData.Right<L, Identity<B>>(new Identity<B>(f(da.Right))); } } public static EitherAsync<L, Option<B>> Traverse<L, A, B>(this Option<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Option<B>>(Go(ma, f)); async Task<EitherData<L, Option<B>>> Go(Option<EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsNone) return EitherData.Right<L, Option<B>>(None); var da = await ma.Value.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, Option<B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, Option<B>>(da.Left); return EitherData.Right<L, Option<B>>(f(da.Right)); } } public static EitherAsync<L, OptionUnsafe<B>> Traverse<L, A, B>(this OptionUnsafe<EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, OptionUnsafe<B>>(Go(ma, f)); async Task<EitherData<L, OptionUnsafe<B>>> Go(OptionUnsafe<EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsNone) return EitherData.Right<L, OptionUnsafe<B>>(None); var da = await ma.Value.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, OptionUnsafe<B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, OptionUnsafe<B>>(da.Left); return EitherData.Right<L, OptionUnsafe<B>>(f(da.Right)); } } public static EitherAsync<L, Try<B>> Traverse<L, A, B>(this Try<EitherAsync<L, A>> ma, Func<A, B> f) { try { return new EitherAsync<L, Try<B>>(Go(ma, f)); async Task<EitherData<L, Try<B>>> Go(Try<EitherAsync<L, A>> ma, Func<A, B> f) { var ra = ma.Try(); if (ra.IsBottom) return EitherData<L, Try<B>>.Bottom; if (ra.IsFaulted) return EitherData.Right<L, Try<B>>(TryFail<B>(ra.Exception)); var da = await ra.Value.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, Try<B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, Try<B>>(da.Left); return EitherData.Right<L, Try<B>>(Try<B>(f(da.Right))); } } catch (Exception e) { return Try<B>(e); } } public static EitherAsync<L, TryOption<B>> Traverse<L, A, B>(this TryOption<EitherAsync<L, A>> ma, Func<A, B> f) { try { return new EitherAsync<L, TryOption<B>>(Go(ma, f)); async Task<EitherData<L, TryOption<B>>> Go(TryOption<EitherAsync<L, A>> ma, Func<A, B> f) { var ra = ma.Try(); if (ra.IsBottom) return EitherData<L, TryOption<B>>.Bottom; if (ra.IsNone) return EitherData.Right<L, TryOption<B>>(TryOptional<B>(None)); if (ra.IsFaulted) return EitherData.Right<L, TryOption<B>>(TryOptionFail<B>(ra.Exception)); var da = await ra.Value.Value.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, TryOption<B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, TryOption<B>>(da.Left); return EitherData.Right<L, TryOption<B>>(TryOption<B>(f(da.Right))); } } catch (Exception e) { return TryOption<B>(e); } } public static EitherAsync<L, Validation<L, B>> Traverse<L, A, B>(this Validation<L, EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Validation<L, B>>(Go(ma, f)); async Task<EitherData<L, Validation<L, B>>> Go(Validation<L, EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsFail) return EitherData.Right<L, Validation<L, B>>(Fail<L, B>(ma.FailValue)); var da = await ma.SuccessValue.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, Validation<L, B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, Validation<L, B>>(da.Left); return EitherData.Right<L, Validation<L, B>>(f(da.Right)); } } public static EitherAsync<L, Validation<Fail, B>> Traverse<Fail, L, A, B>(this Validation<Fail, EitherAsync<L, A>> ma, Func<A, B> f) { return new EitherAsync<L, Validation<Fail, B>>(Go(ma, f)); async Task<EitherData<L, Validation<Fail, B>>> Go(Validation<Fail, EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsFail) return EitherData.Right<L, Validation<Fail, B>>(Fail<Fail, B>(ma.FailValue)); var da = await ma.SuccessValue.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, Validation<Fail, B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, Validation<Fail, B>>(da.Left); return EitherData.Right<L, Validation<Fail, B>>(f(da.Right)); } } public static EitherAsync<Fail, Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, EitherAsync<Fail, A>> ma, Func<A, B> f) where MonoidFail : struct, Monoid<Fail>, Eq<Fail> { return new EitherAsync<Fail, Validation<MonoidFail, Fail, B>>(Go(ma, f)); async Task<EitherData<Fail, Validation<MonoidFail, Fail, B>>> Go(Validation<MonoidFail, Fail, EitherAsync<Fail, A>> ma, Func<A, B> f) { if(ma.IsFail) return EitherData.Right<Fail, Validation<MonoidFail, Fail, B>>(Fail<MonoidFail, Fail, B>(ma.FailValue)); var da = await ma.SuccessValue.Data; if(da.State == EitherStatus.IsBottom) return EitherData<Fail, Validation<MonoidFail, Fail, B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<Fail, Validation<MonoidFail, Fail, B>>(da.Left); return EitherData.Right<Fail, Validation<MonoidFail, Fail, B>>(f(da.Right)); } } public static EitherAsync<L, Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, L, A, B>(this Validation<MonoidFail, Fail, EitherAsync<L, A>> ma, Func<A, B> f) where MonoidFail : struct, Monoid<Fail>, Eq<Fail> { return new EitherAsync<L, Validation<MonoidFail, Fail, B>>(Go(ma, f)); async Task<EitherData<L, Validation<MonoidFail, Fail, B>>> Go(Validation<MonoidFail, Fail, EitherAsync<L, A>> ma, Func<A, B> f) { if(ma.IsFail) return EitherData.Right<L, Validation<MonoidFail, Fail, B>>(Fail<MonoidFail, Fail, B>(ma.FailValue)); var da = await ma.SuccessValue.Data; if(da.State == EitherStatus.IsBottom) return EitherData<L, Validation<MonoidFail, Fail, B>>.Bottom; if(da.State == EitherStatus.IsLeft) return EitherData.Left<L, Validation<MonoidFail, Fail, B>>(da.Left); return EitherData.Right<L, Validation<MonoidFail, Fail, B>>(f(da.Right)); } } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Diagnostics; namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class BufferingTargetWrapperTests : NLogTestBase { [Fact] public void BufferingTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, }; InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.Equal(10, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); Assert.Equal(10, myTarget.WriteCount); for (var i = 0; i < hitCount; ++i) { Assert.Same(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // write 9 more events - they will all be buffered and no final continuation will be reached for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } // no change Assert.Equal(10, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); Assert.Equal(10, myTarget.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); Assert.Null(flushException); // make sure remaining events were written Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); Assert.Equal(19, myTarget.WriteCount); Assert.Equal(1, myTarget.FlushCount); // flushes happen on the same thread for (var i = 10; i < hitCount; ++i) { Assert.NotNull(continuationThread[i]); Assert.Same(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // flush again - should just invoke Flush() on the wrapped target flushHit.Reset(); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); Assert.Equal(19, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); targetWrapper.Close(); myTarget.Close(); } [Fact] public void BufferingTargetWithFallbackGroupAndFirstTargetFails_Write_SecondTargetWritesEvents() { var myTarget = new MyTarget { FailCounter = 1 }; var myTarget2 = new MyTarget(); var fallbackGroup = new FallbackGroupTarget(myTarget, myTarget2); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = fallbackGroup, BufferSize = 10, }; InitializeTargets(myTarget, targetWrapper, myTarget2, fallbackGroup); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; }; // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, myTarget.WriteCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.Equal(1, myTarget.WriteCount); Assert.Equal(10, myTarget2.WriteCount); targetWrapper.Close(); myTarget.Close(); } [Fact] public void BufferingTargetWrapperSyncWithTimedFlushTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 50, }; InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); // sleep 100 ms, this will trigger the timer and flush all events Thread.Sleep(100); Assert.Equal(9, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(9, myTarget.BufferedTotalEvents); Assert.Equal(9, myTarget.WriteCount); for (var i = 0; i < hitCount; ++i) { Assert.NotSame(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // write 11 more events, 10 will be hit immediately because the buffer will fill up // 1 will be pending for (var i = 0; i < 11; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); Assert.Equal(19, myTarget.WriteCount); // sleep 100ms and the last remaining one will be flushed Thread.Sleep(100); Assert.Equal(20, hitCount); Assert.Equal(3, myTarget.BufferedWriteCount); Assert.Equal(20, myTarget.BufferedTotalEvents); Assert.Equal(20, myTarget.WriteCount); } [Fact] public void BufferingTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, }; InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, hitCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); while (hitCount < 10) { Thread.Sleep(10); } Assert.Equal(10, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); for (var i = 0; i < hitCount; ++i) { Assert.NotSame(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // write 9 more events - they will all be buffered and no final continuation will be reached for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } // no change Assert.Equal(10, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); Exception flushException = null; var flushHit = new ManualResetEvent(false); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); Assert.Null(flushException); // make sure remaining events were written Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); // flushes happen on another thread for (var i = 10; i < hitCount; ++i) { Assert.NotNull(continuationThread[i]); Assert.NotSame(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // flush again - should not do anything flushHit.Reset(); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); targetWrapper.Close(); myTarget.Close(); } [Fact] public void BufferingTargetWrapperSyncWithTimedFlushNonSlidingTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 400, SlidingTimeout = false, }; InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; var resetEvent = new ManualResetEvent(false); CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); if (eventNumber > 0) { resetEvent.Set(); } }; var eventCounter = 0; targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.True(resetEvent.WaitOne(5000)); Assert.Equal(2, hitCount); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void BufferingTargetWrapperSyncWithTimedFlushSlidingTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 400, }; InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; var eventCounter = 0; targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(100); Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(100); Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); Thread.Sleep(600); Assert.Equal(2, hitCount); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void WhenWrappedTargetThrowsExceptionThisIsHandled() { var myTarget = new MyTarget { ThrowException = true }; var bufferingTargetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, FlushTimeout = -1 }; InitializeTargets(myTarget, bufferingTargetWrapper); bufferingTargetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(_ => { })); var flushHit = new ManualResetEvent(false); bufferingTargetWrapper.Flush(ex => flushHit.Set()); flushHit.WaitOne(); Assert.Equal(1, myTarget.FlushCount); } [Fact] public void BufferingTargetWrapperSyncWithOverflowDiscardTest() { const int totalEvents = 15; const int bufferSize = 10; var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = bufferSize, OverflowAction = BufferingTargetWrapperOverflowAction.Discard }; InitializeTargets(myTarget, targetWrapper); var continuationHit = new bool[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; Assert.Equal(0, myTarget.WriteCount); for (int i = 0; i < totalEvents; i++) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(i))); } // No events should be written to the wrapped target unless flushing manually. Assert.Equal(0, myTarget.WriteCount); Assert.Equal(0, myTarget.BufferedWriteCount); Assert.Equal(0, myTarget.BufferedTotalEvents); targetWrapper.Flush(e => { }); Assert.Equal(bufferSize, hitCount); Assert.Equal(bufferSize, myTarget.WriteCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(bufferSize, myTarget.BufferedTotalEvents); // Validate that we dropped the oldest events. Assert.False(continuationHit[totalEvents-bufferSize-1]); Assert.True(continuationHit[totalEvents - bufferSize]); // Make sure the events do not stay in the buffer. targetWrapper.Flush(e => { }); Assert.Equal(bufferSize, hitCount); Assert.Equal(bufferSize, myTarget.WriteCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(bufferSize, myTarget.BufferedTotalEvents); } private static void InitializeTargets(params Target[] targets) { foreach (var target in targets) { target.Initialize(null); } } private class MyAsyncTarget : Target { private readonly NLog.Internal.AsyncOperationCounter _pendingWriteCounter = new NLog.Internal.AsyncOperationCounter(); public int BufferedWriteCount { get; private set; } public int BufferedTotalEvents { get; private set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(IList<AsyncLogEventInfo> logEvents) { _pendingWriteCounter.BeginOperation(); BufferedWriteCount++; BufferedTotalEvents += logEvents.Count; for (int i = 0; i < logEvents.Count; ++i) { var @event = logEvents[i]; ThreadPool.QueueUserWorkItem( s => { try { if (ThrowExceptions) { @event.Continuation(new InvalidOperationException("Some problem!")); } else { @event.Continuation(null); } } finally { _pendingWriteCounter.CompleteOperation(null); } }); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { var wrappedContinuation = _pendingWriteCounter.RegisterCompletionNotification(asyncContinuation); ThreadPool.QueueUserWorkItem( s => { wrappedContinuation(null); }); } public bool ThrowExceptions { get; set; } } private class MyTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } public int BufferedWriteCount { get; private set; } public int BufferedTotalEvents { get; private set; } public bool ThrowException { get; set; } public int FailCounter { get; set; } protected override void Write(IList<AsyncLogEventInfo> logEvents) { BufferedWriteCount++; BufferedTotalEvents += logEvents.Count; base.Write(logEvents); } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; if (ThrowException) { throw new Exception("Target exception"); } if (FailCounter > 0) { FailCounter--; throw new InvalidOperationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } private delegate AsyncContinuation CreateContinuationFunc(int eventNumber); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Input; using FluentValidation; using Maple.Core; using Maple.Domain; using Maple.Localization.Properties; namespace Maple { [DebuggerDisplay("{Name}, {Sequence}")] public class MediaPlayer : ValidableBaseDataViewModel<MediaPlayer, MediaPlayerModel>, IDisposable, IChangeState, ISequence { protected readonly ILocalizationService _manager; public bool IsPlaying { get { return Player.IsPlaying; } } public bool IsNew => Model.IsNew; public bool IsDeleted => Model.IsDeleted; private IMediaPlayer _player; public IMediaPlayer Player { get { return _player; } private set { SetValue(ref _player, value); } } public ICommand PlayCommand { get; private set; } public ICommand PauseCommand { get; private set; } public ICommand NextCommand { get; private set; } public ICommand PreviousCommand { get; private set; } public ICommand StopCommand { get; private set; } public ICommand RemoveRangeCommand { get; protected set; } public ICommand RemoveCommand { get; protected set; } public ICommand ClearCommand { get; protected set; } private ICommand _loadFromFileCommand; public ICommand LoadFromFileCommand { get { return _loadFromFileCommand; } private set { SetValue(ref _loadFromFileCommand, value); } } private ICommand _loadFromFolderCommand; public ICommand LoadFromFolderCommand { get { return _loadFromFolderCommand; } private set { SetValue(ref _loadFromFolderCommand, value); } } private ICommand _loadFromUrlCommand; public ICommand LoadFromUrlCommand { get { return _loadFromUrlCommand; } private set { SetValue(ref _loadFromUrlCommand, value); } } private AudioDevices _audioDevices; public AudioDevices AudioDevices { get { return _audioDevices; } private set { SetValue(ref _audioDevices, value); } } private Playlist _playlist; public Playlist Playlist { get { return _playlist; } set { SetValue(ref _playlist, value, OnChanging: OnPlaylistChanging, OnChanged: OnPlaylistChanged); } } private int _sequence; public int Sequence { get { return _sequence; } set { SetValue(ref _sequence, value, OnChanged: () => Model.Sequence = value); } } private string _name; public string Name { get { return _name; } set { SetValue(ref _name, value, OnChanged: () => Model.Name = value); } } private bool _isPrimary; public bool IsPrimary { get { return _isPrimary; } protected set { SetValue(ref _isPrimary, value, OnChanged: () => Model.IsPrimary = value); } } private string _createdBy; public string CreatedBy { get { return _createdBy; } set { SetValue(ref _createdBy, value, OnChanged: () => Model.CreatedBy = value); } } private string _updatedBy; public string UpdatedBy { get { return _updatedBy; } set { SetValue(ref _updatedBy, value, OnChanged: () => Model.UpdatedBy = value); } } private DateTime _updatedOn; public DateTime UpdatedOn { get { return _updatedOn; } set { SetValue(ref _updatedOn, value, OnChanged: () => Model.UpdatedOn = value); } } private DateTime _createdOn; public DateTime CreatedOn { get { return _updatedOn; } set { SetValue(ref _updatedOn, value, OnChanged: () => Model.CreatedOn = value); } } public MediaPlayer(ViewModelServiceContainer container, IMediaPlayer player, IValidator<MediaPlayer> validator, AudioDevices devices, Playlist playlist, MediaPlayerModel model) : base(model, validator, container.Messenger) { _manager = container.LocalizationService; Player = player ?? throw new ArgumentNullException(nameof(player), $"{nameof(player)} {Resources.IsRequired}"); _name = model.Name; _audioDevices = devices; _sequence = model.Sequence; _createdBy = model.CreatedBy; _createdOn = model.CreatedOn; _updatedBy = model.UpdatedBy; _updatedOn = model.UpdatedOn; if (AudioDevices.Items.Count > 0) Player.AudioDevice = AudioDevices.Items.FirstOrDefault(p => p.Name == Model.DeviceName) ?? AudioDevices[0]; Playlist = playlist; InitializeSubscriptions(); InitiliazeCommands(); Validate(); } private void InitializeSubscriptions() { MessageTokens.Add(Messenger.Subscribe<PlayingMediaItemMessage>(Player_PlayingMediaItem, IsSenderEqualsPlayer)); MessageTokens.Add(Messenger.Subscribe<CompletedMediaItemMessage>(MediaPlayer_CompletedMediaItem, IsSenderEqualsPlayer)); MessageTokens.Add(Messenger.Subscribe<ViewModelSelectionChangingMessage<AudioDevice>>(Player_AudioDeviceChanging, IsSenderEqualsPlayer)); MessageTokens.Add(Messenger.Subscribe<ViewModelSelectionChangingMessage<AudioDevice>>(Player_AudioDeviceChanged, IsSenderEqualsPlayer)); } private void InitiliazeCommands() { PlayCommand = new RelayCommand<MediaItem>(Play, CanPlay); PreviousCommand = new RelayCommand(Previous, () => Playlist?.CanPrevious() == true && CanPrevious()); NextCommand = new RelayCommand(Next, () => Playlist?.CanNext() == true && CanNext()); PauseCommand = new RelayCommand(Pause, () => CanPause()); StopCommand = new RelayCommand(Stop, () => CanStop()); RemoveCommand = new RelayCommand<MediaItem>(Remove, CanRemove); ClearCommand = new RelayCommand(Clear, CanClear); UpdatePlaylistCommands(); } public void Play(MediaItem mediaItem) { if (mediaItem == null) throw new ArgumentNullException(nameof(mediaItem), $"{nameof(mediaItem)} {Resources.IsRequired}"); if (!Playlist.Items.Contains(mediaItem)) throw new ArgumentException("Cant play an item thats not part of the playlist"); // TODO localize if (Player.Play(mediaItem)) Messenger.Publish(new PlayingMediaItemMessage(this, mediaItem, Playlist.Id)); } private bool IsSenderEqualsPlayer(object sender) { return ReferenceEquals(sender, Player); } private void Player_AudioDeviceChanging(ViewModelSelectionChangingMessage<AudioDevice> e) { // TODO handle Player_AudioDeviceChanging } private void Player_AudioDeviceChanged(ViewModelSelectionChangingMessage<AudioDevice> e) { if (!string.IsNullOrEmpty(e?.Content?.Name)) Model.DeviceName = e.Content.Name; } private void OnPlaylistChanging() { Stop(); } private void OnPlaylistChanged() { Model.Playlist = Playlist.Model; // TODO: maybe add optional endless playback OnPropertyChanged(nameof(Playlist.View)); UpdatePlaylistCommands(); } private void UpdatePlaylistCommands() { if (Playlist != null) { LoadFromFileCommand = Playlist.LoadFromFileCommand; LoadFromFolderCommand = Playlist.LoadFromFolderCommand; LoadFromUrlCommand = Playlist.LoadFromUrlCommand; } } private void Player_PlayingMediaItem(PlayingMediaItemMessage e) { // TODO: sync state to other viewmodels OnPropertyChanged(nameof(IsPlaying)); } private void MediaPlayer_CompletedMediaItem(CompletedMediaItemMessage e) { OnPropertyChanged(nameof(IsPlaying)); Next(); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { using (BusyStack.GetToken()) Playlist.Clear(); } /// <summary> /// Determines whether this instance can clear. /// </summary> /// <returns> /// <c>true</c> if this instance can clear; otherwise, <c>false</c>. /// </returns> public bool CanClear() { return !IsBusy && Playlist.Count > 0; } /// <summary> /// Adds the range. /// </summary> /// <param name="mediaItems">The media items.</param> public void AddRange(IEnumerable<MediaItem> mediaItems) { using (BusyStack.GetToken()) { foreach (var item in mediaItems) Playlist.Add(item); } } /// <summary> /// Adds the specified media item. /// </summary> /// <param name="mediaItem">The media item.</param> public void Add(MediaItem mediaItem) { using (BusyStack.GetToken()) { if (Playlist.Items.Any()) { var maxIndex = Playlist.Items.Max(p => p.Sequence) + 1; if (maxIndex < 0) maxIndex = 0; mediaItem.Sequence = maxIndex; } else mediaItem.Sequence = 0; Playlist.Add(mediaItem); } } /// <summary> /// Removes the specified item. /// </summary> /// <param name="item">The item.</param> public void Remove(MediaItem item) { using (BusyStack.GetToken()) Playlist.Remove(item); } private bool CanRemove(MediaItem item) { using (BusyStack.GetToken()) return Playlist.CanRemove(item); } /// <summary> /// Pauses this instance. /// </summary> public void Pause() { using (BusyStack.GetToken()) Player.Pause(); } /// <summary> /// Stops this instance. /// </summary> public void Stop() { using (BusyStack.GetToken()) Player.Stop(); } /// <summary> /// Previouses this instance. /// </summary> public void Previous() { using (BusyStack.GetToken()) { var item = Playlist.Previous(); Play(item); } } /// <summary> /// Nexts this instance. /// </summary> public void Next() { using (BusyStack.GetToken()) { var item = Playlist.Next(); Play(item); } } /// <summary> /// Determines whether this instance can next. /// </summary> /// <returns> /// <c>true</c> if this instance can next; otherwise, <c>false</c>. /// </returns> public bool CanNext() { var item = Playlist.Next(); return CanPlay(item); } /// <summary> /// Determines whether this instance can previous. /// </summary> /// <returns> /// <c>true</c> if this instance can previous; otherwise, <c>false</c>. /// </returns> public bool CanPrevious() { var item = Playlist.Previous(); return CanPlay(item); } /// <summary> /// Determines whether this instance can pause. /// </summary> /// <returns> /// <c>true</c> if this instance can pause; otherwise, <c>false</c>. /// </returns> public bool CanPause() { return Player.CanPause(); } /// <summary> /// Determines whether this instance can stop. /// </summary> /// <returns> /// <c>true</c> if this instance can stop; otherwise, <c>false</c>. /// </returns> public bool CanStop() { return Player.CanStop(); } /// <summary> /// Determines whether this instance can play the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns> /// <c>true</c> if this instance can play the specified item; otherwise, <c>false</c>. /// </returns> private bool CanPlay(MediaItem item) { return Player.CanPlay(item); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (Disposed) return; if (IsPlaying) Stop(); if (disposing) { if (Player != null) { Player?.Dispose(); Player = null; } base.Dispose(disposing); // Free any other managed objects here. } // Free any unmanaged objects here. Disposed = true; } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] Value of GL_IMAGE_SCALE_X_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_SCALE_X_HP = 0x8155; /// <summary> /// [GL] Value of GL_IMAGE_SCALE_Y_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_SCALE_Y_HP = 0x8156; /// <summary> /// [GL] Value of GL_IMAGE_TRANSLATE_X_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_TRANSLATE_X_HP = 0x8157; /// <summary> /// [GL] Value of GL_IMAGE_TRANSLATE_Y_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_TRANSLATE_Y_HP = 0x8158; /// <summary> /// [GL] Value of GL_IMAGE_ROTATE_ANGLE_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_ROTATE_ANGLE_HP = 0x8159; /// <summary> /// [GL] Value of GL_IMAGE_ROTATE_ORIGIN_X_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_ROTATE_ORIGIN_X_HP = 0x815A; /// <summary> /// [GL] Value of GL_IMAGE_ROTATE_ORIGIN_Y_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_ROTATE_ORIGIN_Y_HP = 0x815B; /// <summary> /// [GL] Value of GL_IMAGE_MAG_FILTER_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_MAG_FILTER_HP = 0x815C; /// <summary> /// [GL] Value of GL_IMAGE_MIN_FILTER_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_MIN_FILTER_HP = 0x815D; /// <summary> /// [GL] Value of GL_IMAGE_CUBIC_WEIGHT_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_CUBIC_WEIGHT_HP = 0x815E; /// <summary> /// [GL] Value of GL_CUBIC_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int CUBIC_HP = 0x815F; /// <summary> /// [GL] Value of GL_AVERAGE_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int AVERAGE_HP = 0x8160; /// <summary> /// [GL] Value of GL_IMAGE_TRANSFORM_2D_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int IMAGE_TRANSFORM_2D_HP = 0x8161; /// <summary> /// [GL] Value of GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int POST_IMAGE_TRANSFORM_COLOR_TABLE_HP = 0x8162; /// <summary> /// [GL] Value of GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP symbol. /// </summary> [RequiredByFeature("GL_HP_image_transform")] public const int PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP = 0x8163; /// <summary> /// [GL] glImageTransformParameteriHP: Binding for glImageTransformParameteriHP. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="pname"> /// A <see cref="T:int"/>. /// </param> /// <param name="param"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_HP_image_transform")] public static void ImageTransformParameterHP(int target, int pname, int param) { Debug.Assert(Delegates.pglImageTransformParameteriHP != null, "pglImageTransformParameteriHP not implemented"); Delegates.pglImageTransformParameteriHP(target, pname, param); LogCommand("glImageTransformParameteriHP", null, target, pname, param ); DebugCheckErrors(null); } /// <summary> /// [GL] glImageTransformParameterfHP: Binding for glImageTransformParameterfHP. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="pname"> /// A <see cref="T:int"/>. /// </param> /// <param name="param"> /// A <see cref="T:float"/>. /// </param> [RequiredByFeature("GL_HP_image_transform")] public static void ImageTransformParameterHP(int target, int pname, float param) { Debug.Assert(Delegates.pglImageTransformParameterfHP != null, "pglImageTransformParameterfHP not implemented"); Delegates.pglImageTransformParameterfHP(target, pname, param); LogCommand("glImageTransformParameterfHP", null, target, pname, param ); DebugCheckErrors(null); } /// <summary> /// [GL] glImageTransformParameterivHP: Binding for glImageTransformParameterivHP. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="pname"> /// A <see cref="T:int"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_HP_image_transform")] public static void ImageTransformParameterHP(int target, int pname, int[] @params) { unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglImageTransformParameterivHP != null, "pglImageTransformParameterivHP not implemented"); Delegates.pglImageTransformParameterivHP(target, pname, p_params); LogCommand("glImageTransformParameterivHP", null, target, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glImageTransformParameterfvHP: Binding for glImageTransformParameterfvHP. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="pname"> /// A <see cref="T:int"/>. /// </param> /// <param name="params"> /// A <see cref="T:float[]"/>. /// </param> [RequiredByFeature("GL_HP_image_transform")] public static void ImageTransformParameterHP(int target, int pname, float[] @params) { unsafe { fixed (float* p_params = @params) { Debug.Assert(Delegates.pglImageTransformParameterfvHP != null, "pglImageTransformParameterfvHP not implemented"); Delegates.pglImageTransformParameterfvHP(target, pname, p_params); LogCommand("glImageTransformParameterfvHP", null, target, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetImageTransformParameterivHP: Binding for glGetImageTransformParameterivHP. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="pname"> /// A <see cref="T:int"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_HP_image_transform")] public static void GetImageTransformParameterHP(int target, int pname, [Out] int[] @params) { unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglGetImageTransformParameterivHP != null, "pglGetImageTransformParameterivHP not implemented"); Delegates.pglGetImageTransformParameterivHP(target, pname, p_params); LogCommand("glGetImageTransformParameterivHP", null, target, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetImageTransformParameterfvHP: Binding for glGetImageTransformParameterfvHP. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="pname"> /// A <see cref="T:int"/>. /// </param> /// <param name="params"> /// A <see cref="T:float[]"/>. /// </param> [RequiredByFeature("GL_HP_image_transform")] public static void GetImageTransformParameterHP(int target, int pname, [Out] float[] @params) { unsafe { fixed (float* p_params = @params) { Debug.Assert(Delegates.pglGetImageTransformParameterfvHP != null, "pglGetImageTransformParameterfvHP not implemented"); Delegates.pglGetImageTransformParameterfvHP(target, pname, p_params); LogCommand("glGetImageTransformParameterfvHP", null, target, pname, @params ); } } DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_HP_image_transform")] [SuppressUnmanagedCodeSecurity] internal delegate void glImageTransformParameteriHP(int target, int pname, int param); [RequiredByFeature("GL_HP_image_transform")] [ThreadStatic] internal static glImageTransformParameteriHP pglImageTransformParameteriHP; [RequiredByFeature("GL_HP_image_transform")] [SuppressUnmanagedCodeSecurity] internal delegate void glImageTransformParameterfHP(int target, int pname, float param); [RequiredByFeature("GL_HP_image_transform")] [ThreadStatic] internal static glImageTransformParameterfHP pglImageTransformParameterfHP; [RequiredByFeature("GL_HP_image_transform")] [SuppressUnmanagedCodeSecurity] internal delegate void glImageTransformParameterivHP(int target, int pname, int* @params); [RequiredByFeature("GL_HP_image_transform")] [ThreadStatic] internal static glImageTransformParameterivHP pglImageTransformParameterivHP; [RequiredByFeature("GL_HP_image_transform")] [SuppressUnmanagedCodeSecurity] internal delegate void glImageTransformParameterfvHP(int target, int pname, float* @params); [RequiredByFeature("GL_HP_image_transform")] [ThreadStatic] internal static glImageTransformParameterfvHP pglImageTransformParameterfvHP; [RequiredByFeature("GL_HP_image_transform")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetImageTransformParameterivHP(int target, int pname, int* @params); [RequiredByFeature("GL_HP_image_transform")] [ThreadStatic] internal static glGetImageTransformParameterivHP pglGetImageTransformParameterivHP; [RequiredByFeature("GL_HP_image_transform")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetImageTransformParameterfvHP(int target, int pname, float* @params); [RequiredByFeature("GL_HP_image_transform")] [ThreadStatic] internal static glGetImageTransformParameterfvHP pglGetImageTransformParameterfvHP; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using System.Xml; using Core.Utils; namespace Core.Geometry { public interface IPoint { double X { get; set; } double Y { get; set; } bool Equals(IPoint test, double tolerance); string Serialize(); void Deserialize(string str); } public class PointE : AShapeE, IXmlSerializable, IPoint {//Point2D #region Private Fields private double m_X; private double m_Y; #endregion #region Constructors public PointE() { } public PointE(double x, double y) { m_X = x; m_Y = y; } public PointE(PointE pt) : this(pt.X, pt.Y) { } #endregion #region GetSet public double X { get { return m_X; } set { m_X = value; CallGeometryChanged(); } } public double Y { get { return m_Y; } set { m_Y = value; CallGeometryChanged(); } } public double Abs { get { return Math.Sqrt(X * X + Y * Y); } } public double Magnitude { get { return (double)Math.Sqrt(X * X + Y * Y); } } public PointE GetNormalized() { double magnitude = Magnitude; return new PointE(X / magnitude, Y / magnitude); } #endregion public PointE AbsDifference(PointE point) { return new PointE(Math.Abs(X - point.X), Math.Abs(Y - point.Y)); } public double Dist(PointE point) { double x = X - point.X; double y = Y - point.Y; return Math.Sqrt(x * x + y * y); } public void Normalize() { double magnitude = Magnitude; X = X / magnitude; Y = Y / magnitude; } public double DotProduct(PointE vector) { return this.X * vector.X + this.Y * vector.Y; } #region Conversions static public implicit operator PointE(System.Drawing.PointF floatPt) { return new PointE((double)floatPt.X, (double)floatPt.Y); } static public explicit operator System.Drawing.PointF(PointE doublePt) { return new System.Drawing.PointF((float)doublePt.X, (float)doublePt.Y); } static public implicit operator PointE(System.Drawing.Point intPt) { return new PointE((double)intPt.X, (double)intPt.Y); } static public explicit operator System.Drawing.Point(PointE doublePt) { return new System.Drawing.Point((int)doublePt.X, (int)doublePt.Y); } static public implicit operator PointE(SizeE size) { return new PointE((double)size.Width, (double)size.Height); } static public explicit operator SizeE(PointE doublePt) { return new SizeE((float)doublePt.X, (float)doublePt.Y); } #endregion #region Operator Overloads public static PointE operator +(PointE c) { PointE ans = new PointE(); ans.X = +c.X; ans.Y = +c.Y; return ans; } public static PointE operator -(PointE c) { PointE ans = new PointE(); ans.X = -c.X; ans.Y = -c.Y; return ans; } public static PointE operator +(PointE a, PointE b) { return new PointE(a.X + b.X, a.Y + b.Y); } public static PointE operator -(PointE a, PointE b) { return new PointE(a.X - b.X, a.Y - b.Y); } public static PointE operator *(PointE a, PointE b) { return new PointE(a.X * b.X, a.Y * b.Y); } public static PointE operator *(PointE a, double muliplier) { return new PointE(a.X * muliplier, a.Y * muliplier); } public static PointE operator /(PointE a, PointE b) { return new PointE(a.X / b.X, a.Y / b.Y); } public static PointE operator /(PointE a, double divisor) { return new PointE(a.X / divisor, a.Y / divisor); } #endregion public override bool Equals(object obj) { if (obj.GetType() != this.GetType()) { return false; } PointE test = obj as PointE; return (test.X == X && test.Y == Y); } public virtual bool Equals(IPoint test, double tolerance) { return (Math.Abs(test.X - X) < tolerance && Math.Abs(test.Y - Y) < tolerance); } public override int GetHashCode() { return (int)X ^ (int)Y; } public override string ToString() { return "PointE: (" + X + ", " + Y + ")"; } #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public virtual void ReadXml(XmlReader r) { string str = r.ReadElementContentAsString(); Deserialize(str); } public virtual void WriteXml(XmlWriter w) { w.WriteString(Serialize()); } #endregion #region IPoint Members #region (De)Serialize public virtual string Serialize() { return m_X + "," + m_Y; } public virtual void Deserialize(string str) { List<string> bits = StringUtils.SplitToList(str, ","); m_X = Convert.ToDouble(bits[0]); m_Y = Convert.ToDouble(bits[1]); } #endregion #endregion public override RectangleE BoundingBox { get { return null; } } public PointE ShiftPt(PointE offset) { return new PointE(X + offset.X, Y + offset.Y); } public override IShapeE Shift(PointE offset) { return ShiftPt(offset); } public bool HasSamePoints(PointE nxtPt) { return nxtPt.X == X && nxtPt.Y == Y; } public bool HasSamePoints(PointE nxtPt, double tol) { if (HasSamePoints(nxtPt)) { return true; } if (Math.Abs(nxtPt.X - X) > tol) { return false; } if (Math.Abs(nxtPt.Y - Y) > tol) { return false; } return true; //return Calc.GetDist(this, nxtPt) < tol; } public PointE TransformByRotationAbout(double rotation, PointE center) { PointE t = this - center; // translate to origin // apply rotation matrix cos x -sin x // sin x cos x which rotates about origin double cos = Math.Cos(rotation); double sin = Math.Sin(rotation); t = new PointE(cos * t.X - sin * t.Y, sin * t.X + cos * t.Y); return t + center; // translate back } public void UpdatePoint(PointE pointE) { if (pointE == null) return; m_X = pointE.m_X; m_Y = pointE.m_Y; } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.ComponentModel; using System.Globalization; using JetBrains.Annotations; using NLog.Internal; namespace NLog.Targets { /// <summary> /// Line ending mode. /// </summary> #if !NETSTANDARD1_3 [TypeConverter(typeof(LineEndingModeConverter))] #endif public sealed class LineEndingMode : IEquatable<LineEndingMode> { /// <summary> /// Insert platform-dependent end-of-line sequence after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode Default = new LineEndingMode("Default", EnvironmentHelper.NewLine); /// <summary> /// Insert CR LF sequence (ASCII 13, ASCII 10) after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode CRLF = new LineEndingMode("CRLF", "\r\n"); /// <summary> /// Insert CR character (ASCII 13) after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode CR = new LineEndingMode("CR", "\r"); /// <summary> /// Insert LF character (ASCII 10) after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode LF = new LineEndingMode("LF", "\n"); /// <summary> /// Insert null terminator (ASCII 0) after each line. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode Null = new LineEndingMode("Null", "\0"); /// <summary> /// Do not insert any line ending. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LineEndingMode None = new LineEndingMode("None", string.Empty); private readonly string _name; private readonly string _newLineCharacters; /// <summary> /// Gets the name of the LineEndingMode instance. /// </summary> public string Name => _name; /// <summary> /// Gets the new line characters (value) of the LineEndingMode instance. /// </summary> public string NewLineCharacters => _newLineCharacters; private LineEndingMode() { } /// <summary> /// Initializes a new instance of <see cref="LogLevel"/>. /// </summary> /// <param name="name">The mode name.</param> /// <param name="newLineCharacters">The new line characters to be used.</param> private LineEndingMode(string name, string newLineCharacters) { _name = name; _newLineCharacters = newLineCharacters; } /// <summary> /// Returns the <see cref="LineEndingMode"/> that corresponds to the supplied <paramref name="name"/>. /// </summary> /// <param name="name"> /// The textual representation of the line ending mode, such as CRLF, LF, Default etc. /// Name is not case sensitive. /// </param> /// <returns>The <see cref="LineEndingMode"/> value, that corresponds to the <paramref name="name"/>.</returns> /// <exception cref="ArgumentOutOfRangeException">There is no line ending mode with the specified name.</exception> public static LineEndingMode FromString([NotNull] string name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Equals(CRLF.Name, StringComparison.OrdinalIgnoreCase)) return CRLF; if (name.Equals(LF.Name, StringComparison.OrdinalIgnoreCase)) return LF; if (name.Equals(CR.Name, StringComparison.OrdinalIgnoreCase)) return CR; if (name.Equals(Default.Name, StringComparison.OrdinalIgnoreCase)) return Default; if (name.Equals(Null.Name, StringComparison.OrdinalIgnoreCase)) return Null; if (name.Equals(None.Name, StringComparison.OrdinalIgnoreCase)) return None; #if !SILVERLIGHT throw new ArgumentOutOfRangeException(nameof(name), name, "LineEndingMode is out of range"); #else throw new ArgumentOutOfRangeException("name", "LineEndingMode is out of range"); #endif } /// <summary> /// Compares two <see cref="LineEndingMode"/> objects and returns a /// value indicating whether the first one is equal to the second one. /// </summary> /// <param name="mode1">The first level.</param> /// <param name="mode2">The second level.</param> /// <returns>The value of <c>mode1.NewLineCharacters == mode2.NewLineCharacters</c>.</returns> public static bool operator ==(LineEndingMode mode1, LineEndingMode mode2) { if (ReferenceEquals(mode1, null)) { return ReferenceEquals(mode2, null); } if (ReferenceEquals(mode2, null)) { return false; } return mode1.NewLineCharacters == mode2.NewLineCharacters; } /// <summary> /// Compares two <see cref="LineEndingMode"/> objects and returns a /// value indicating whether the first one is not equal to the second one. /// </summary> /// <param name="mode1">The first mode</param> /// <param name="mode2">The second mode</param> /// <returns>The value of <c>mode1.NewLineCharacters != mode2.NewLineCharacters</c>.</returns> public static bool operator !=(LineEndingMode mode1, LineEndingMode mode2) { if (ReferenceEquals(mode1, null)) { return !ReferenceEquals(mode2, null); } if (ReferenceEquals(mode2, null)) { return true; } return mode1.NewLineCharacters != mode2.NewLineCharacters; } /// <summary> /// Returns a string representation of the log level. /// </summary> /// <returns>Log level name.</returns> public override string ToString() { return Name; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms /// and data structures like a hash table. /// </returns> public override int GetHashCode() { return (_newLineCharacters != null ? _newLineCharacters.GetHashCode() : 0); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is /// equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with /// this instance.</param> /// <returns> /// Value of <c>true</c> if the specified <see cref="System.Object"/> /// is equal to this instance; otherwise, <c>false</c>. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is LineEndingMode mode && Equals(mode); } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(LineEndingMode other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(_newLineCharacters, other._newLineCharacters); } #if !NETSTANDARD1_3 /// <summary> /// Provides a type converter to convert <see cref="LineEndingMode"/> objects to and from other representations. /// </summary> public class LineEndingModeConverter : TypeConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <returns> /// true if this converter can perform the conversion; otherwise, false. /// </returns> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param><param name="sourceType">A <see cref="T:System.Type"/> that represents the type you want to convert from. </param> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <returns> /// An <see cref="T:System.Object"/> that represents the converted value. /// </returns> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param><param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param><param name="value">The <see cref="T:System.Object"/> to convert. </param><exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var name = value as string; return name != null ? FromString(name) : base.ConvertFrom(context, culture, value); } } #endif } }
#if CEFGLUE using Eto; using Eto.Drawing; using Eto.Forms; using Eto.Platform.CustomControls; using Eto.Platform.Wpf.Forms; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using xc = Xilium.CefGlue; using swm = System.Windows.Media; using xcw = Xilium.CefGlue.WPF; using sw = System.Windows; namespace JabbR.Windows.Controls { public class CefGlueWebViewHandler : WpfFrameworkElement<xcw.WpfCefBrowser, WebView>, IWebView { double zoomLevel = 0.0; public override bool UseMousePreview { get { return true; } } class MyCefApp : xcw.WpfCefApp { } static CefGlueWebViewHandler () { xc.CefRuntime.Load(); var mainArgs = new xc.CefMainArgs(null); var cefApp = new MyCefApp(); //var exitCode = xc.CefRuntime.ExecuteProcess(mainArgs, cefApp); //if (exitCode != -1) { return exitCode; } var cefSettings = new xc.CefSettings { SingleProcess = true, MultiThreadedMessageLoop = true, LogSeverity = xc.CefLogSeverity.Disable, }; xc.CefRuntime.Initialize(mainArgs, cefSettings, cefApp); } public CefGlueWebViewHandler() { Control = new xcw.WpfCefBrowser (); Control.Loaded += (s, e) => { // make the dpi match the screen var visual = sw.PresentationSource.FromVisual(Control); if (visual != null) { var m = visual.CompositionTarget.TransformToDevice; var dpiTransform = new swm.ScaleTransform(1 / m.M11, 1 / m.M22); if (dpiTransform.CanFreeze) dpiTransform.Freeze(); Control.LayoutTransform = dpiTransform; zoomLevel = Math.Log(m.M11) / Math.Log(1.2); } }; Control.LoadingStateChanged += (sender, e) => { Control.Browser.GetHost().SetZoomLevel(zoomLevel); }; } public override void AttachEvent (string handler) { switch (handler) { case WebView.DocumentLoadedEvent: Control.LoadingStateChanged += (sender, e) => { if (!Control.Browser.IsLoading) { Control.Dispatcher.BeginInvoke(new Action(() => { Widget.OnDocumentLoaded(new WebViewLoadedEventArgs(this.Url)); })); } }; break; case WebView.DocumentLoadingEvent: Control.BeforeNavigation += (sender, e) => { var args = new WebViewLoadingEventArgs(new Uri(e.Request.Url), e.Frame.IsMain); Widget.OnDocumentLoading(args); e.Cancel = args.Cancel; }; break; case WebView.OpenNewWindowEvent: Control.BeforePopup += (sender, e) => { var uri = new Uri(e.TargetUrl); if (uri.Scheme != "chrome-devtools") { var args = new WebViewNewWindowEventArgs(uri, null); Widget.OnOpenNewWindow(args); e.Cancel = args.Cancel; } }; break; case WebView.DocumentTitleChangedEvent: Control.TitleChanged += (sender, e) => { Control.Dispatcher.BeginInvoke (new Action (() => { Widget.OnDocumentTitleChanged (new WebViewTitleEventArgs (Control.Title)); })); }; break; default: base.AttachEvent (handler); break; } } public Uri Url { get { return string.IsNullOrEmpty(Control.Address) ? null : new Uri(Control.Address); } set { Control.StartUrl = value.AbsoluteUri; } } public void LoadHtml (string html, Uri baseUri) { Control.LoadString(html, baseUri != null ? baseUri.LocalPath : null); } public void GoBack () { Control.GoBack (); } public bool CanGoBack { get { return Control.CanGoBack(); } } public void GoForward () { Control.GoForward (); } public bool CanGoForward { get { return Control.CanGoForward(); } } public void Stop () { if (Control.Browser != null) Control.Browser.StopLoad(); } public void Reload () { if (Control.Browser != null) Control.Browser.Reload(); } public string DocumentTitle { get { return Control.Title; } } public string ExecuteScript (string script) { /**/ Control.ExecuteJavaScript(script); return null; /** return Convert.ToString (Control.EvaluateScript (script)); /**/ } public void ShowPrintDialog () { } public override Color BackgroundColor { get { return Colors.Transparent; } set { } } public bool BrowserContextMenuEnabled { get; set; } } } #endif
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using MBProgressHUD; using MonoTouch.Dialog; namespace MBProgressHUDDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; UINavigationController navController; DialogViewController dvcDialog; MTMBProgressHUD hud; // vars for managing NSUrlConnection Demo public long expectedLength; public long currentLength; // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); var root = new RootElement("MBProgressHUD") { new Section ("Samples") { new StringElement ("Simple indeterminate progress", ShowSimple), new StringElement ("With label", ShowWithLabel), new StringElement ("With details label", ShowWithDetailsLabel), new StringElement ("Determinate mode", ShowWithLabelDeterminate), new StringElement ("Annular determinate mode", ShowWIthLabelAnnularDeterminate), new StringElement ("Custom view", ShowWithCustomView), new StringElement ("Mode switching", ShowWithLabelMixed), new StringElement ("Using handlers", ShowUsingHandlers), new StringElement ("On Window", ShowOnWindow), new StringElement ("NSURLConnection", ShowUrl), new StringElement ("Dim background", ShowWithGradient), new StringElement ("Text only", ShowTextOnly), new StringElement ("Colored", ShowWithColor), } }; dvcDialog = new DialogViewController(UITableViewStyle.Grouped, root, false); navController = new UINavigationController(dvcDialog); window.RootViewController = navController; window.MakeKeyAndVisible (); return true; } #region Button Actions void ShowSimple () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD(this.navController.View); navController.View.AddSubview(hud); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Show the HUD while the provided method executes in a new thread hud.Show(new MonoTouch.ObjCRuntime.Selector("MyTask"), this, null, true); } void ShowWithLabel () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD(this.navController.View); navController.View.AddSubview(hud); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Add information to your HUD hud.LabelText = "Loading"; // Show the HUD while the provided method executes in a new thread hud.Show(new MonoTouch.ObjCRuntime.Selector("MyTask"), this, null, true); } void ShowWithDetailsLabel () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD(this.navController.View); navController.View.AddSubview(hud); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Add information to your HUD hud.LabelText = "Loading"; hud.DetailsLabelText = "updating data"; hud.Square = true; // Show the HUD while the provided method executes in a new thread hud.Show(new MonoTouch.ObjCRuntime.Selector("MyTask"), this, null, true); } void ShowWithLabelDeterminate () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD(this.navController.View); navController.View.AddSubview(hud); // Set determinate mode hud.Mode = MBProgressHUDMode.Determinate; // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Add information to your HUD hud.LabelText = "Loading"; // Show the HUD while the provided method executes in a new thread hud.Show(new MonoTouch.ObjCRuntime.Selector("MyProgressTask"), this, null, true); } void ShowWIthLabelAnnularDeterminate () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD(this.navController.View); navController.View.AddSubview(hud); // Set determinate mode hud.Mode = MBProgressHUDMode.AnnularDeterminate; // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Add information to your HUD hud.LabelText = "Loading"; // Show the HUD while the provided method executes in a new thread hud.Show(new MonoTouch.ObjCRuntime.Selector("MyProgressTask"), this, null, true); } void ShowWithCustomView () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD (this.navController.View); navController.View.AddSubview (hud); // Set custom view mode hud.Mode = MBProgressHUDMode.CustomView; // The sample image is based on the work by http://www.pixelpressicons.com, http://creativecommons.org/licenses/by/2.5/ca/ // Make the customViews 37 by 37 pixels for best results (those are the bounds of the build-in progress indicators) hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png")); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Add information to your HUD hud.LabelText = "Completed"; // Show the HUD hud.Show(true); // Hide the HUD after 3 seconds hud.Hide (true, 3); } void ShowWithLabelMixed () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD (this.navController.View); navController.View.AddSubview (hud); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Add information to your HUD hud.LabelText = "Connecting"; hud.MinSize = new System.Drawing.SizeF(135f, 135f); // Show the HUD while the provided method executes in a new thread hud.Show (new MonoTouch.ObjCRuntime.Selector("MyMixedTask"), this, null, true); } void ShowUsingHandlers () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD (this.navController.View); navController.View.AddSubview (hud); // Add information to your HUD hud.LabelText = "With a handler"; // We show the hud while executing MyTask, and then we clean up hud.Show (true, () => { MyTask(); }, () => { hud.RemoveFromSuperview(); hud = null; }); } void ShowOnWindow () { // The hud will dispable all input on the window hud = new MTMBProgressHUD (this.window); this.window.AddSubview(hud); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Add information to your HUD hud.LabelText = "Loading"; // Show the HUD while the provided method executes in a new thread hud.Show (new MonoTouch.ObjCRuntime.Selector("MyTask"), this, null, true); } void ShowUrl () { // Show the hud on top most view hud = MTMBProgressHUD.ShowHUD(this.navController.View, true); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; NSUrl url = new NSUrl("https://github.com/matej/MBProgressHUD/zipball/master"); NSUrlRequest request = new NSUrlRequest(url); NSUrlConnection connection = new NSUrlConnection(request, new MyNSUrlConnectionDelegete(this, hud)); connection.Start(); } void ShowWithGradient () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD (this.navController.View); navController.View.AddSubview (hud); // Set HUD to dim Background hud.DimBackground = true; // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Show the HUD while the provided method executes in a new thread hud.Show(new MonoTouch.ObjCRuntime.Selector("MyTask"), this, null, true); } void ShowTextOnly () { // Show the hud on top most view hud = MTMBProgressHUD.ShowHUD(this.navController.View, true); // Configure for text only and offset down hud.Mode = MBProgressHUDMode.Text; hud.LabelText = "Some message..."; hud.Margin = 10f; hud.YOffset = 150f; hud.RemoveFromSuperViewOnHide = true; hud.Hide(true, 3); } void ShowWithColor () { // The hud will dispable all input on the view (use the higest view possible in the view hierarchy) hud = new MTMBProgressHUD (this.navController.View); navController.View.AddSubview (hud); // Set the hud to display with a color hud.Color = new UIColor(0.23f, 0.5f, 0.82f, 0.90f); // Regiser for DidHide Event so we can remove it from the window at the right time hud.DidHide += HandleDidHide; // Show the HUD while the provided method executes in a new thread hud.Show(new MonoTouch.ObjCRuntime.Selector("MyTask"), this, null, true); } #endregion #region fake tasks and Hide Handler [Export ("MyTask")] void MyTask () { System.Threading.Thread.Sleep(3000); } [Export ("MyProgressTask")] void MyProgressTask () { float progress = 0.0f; while (progress < 1.0f) { progress += 0.01f; hud.Progress = progress; System.Threading.Thread.Sleep(50); } } [Export ("MyMixedTask")] void MyMixedTask () { // Indeterminate mode System.Threading.Thread.Sleep(2000); // Switch to determinate mode hud.Mode = MBProgressHUDMode.Determinate; hud.LabelText = "Progress"; float progress = 0.0f; while (progress < 1.0f) { progress += 0.01f; hud.Progress = progress; System.Threading.Thread.Sleep(50); } // Back to indeterminate mode hud.Mode = MBProgressHUDMode.Indeterminate; hud.LabelText = "Cleaning up"; System.Threading.Thread.Sleep(2000); // The sample image is based on the work by www.pixelpressicons.com, http://creativecommons.org/licenses/by/2.5/ca/ // Make the customViews 37 by 37 pixels for best results (those are the bounds of the build-in progress indicators) // Since HUD is already on screen, we must set It's custom vien on Main Thread BeginInvokeOnMainThread ( ()=> { hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png")); }); hud.Mode = MBProgressHUDMode.CustomView; hud.LabelText = "Completed"; System.Threading.Thread.Sleep(2000); } void HandleDidHide (object sender, EventArgs e) { hud.RemoveFromSuperview(); hud = null; } #endregion } // Custom NSUrlConnectionDelegate that handles NSUrlConnection Events public class MyNSUrlConnectionDelegete : MonoTouch.Foundation.NSUrlConnectionDelegate { AppDelegate del; MTMBProgressHUD hud; public MyNSUrlConnectionDelegete (AppDelegate del, MTMBProgressHUD hud) { this.del = del; this.hud = hud; } public override void ReceivedResponse (NSUrlConnection connection, NSUrlResponse response) { del.expectedLength = response.ExpectedContentLength; del.currentLength = 0; hud.Mode = MBProgressHUDMode.Determinate; } public override void ReceivedData (NSUrlConnection connection, NSData data) { del.currentLength += data.Length; hud.Progress = (del.currentLength / (float) del.expectedLength); } public override void FinishedLoading (NSUrlConnection connection) { BeginInvokeOnMainThread ( ()=> { hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png")); }); hud.Mode = MBProgressHUDMode.CustomView; hud.Hide(true, 2); } public override void FailedWithError (NSUrlConnection connection, NSError error) { hud.Hide(true); } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Crypto.Interfaces.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Javax.Crypto.Interfaces { /// <summary> /// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPrivateKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDHPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serialization version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 2211791113380396553; } /// <summary> /// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPrivateKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537)] public partial interface IDHPrivateKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns this key's private value x. </para> /// </summary> /// <returns> /// <para>this key's private value x. </para> /// </returns> /// <java-name> /// getX /// </java-name> [Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Diffie-Hellman key. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHKey", AccessFlags = 1537)] public partial interface IDHKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the parameters for this key.</para><para></para> /// </summary> /// <returns> /// <para>the parameters for this key. </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Ljavax/crypto/spec/DHParameterSpec;", AccessFlags = 1025)] global::Javax.Crypto.Spec.DHParameterSpec GetParams() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPublicKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDHPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -6628103563352519193; } /// <summary> /// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPublicKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537)] public partial interface IDHPublicKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPublicKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns this key's public value Y. </para> /// </summary> /// <returns> /// <para>this key's public value Y. </para> /// </returns> /// <java-name> /// getY /// </java-name> [Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface to a <b>password-based-encryption</b> key. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/PBEKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IPBEKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -1430015993304333921; } /// <summary> /// <para>The interface to a <b>password-based-encryption</b> key. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/PBEKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537)] public partial interface IPBEKey : global::Javax.Crypto.ISecretKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the iteration count, 0 if not specified.</para><para></para> /// </summary> /// <returns> /// <para>the iteration count, 0 if not specified. </para> /// </returns> /// <java-name> /// getIterationCount /// </java-name> [Dot42.DexImport("getIterationCount", "()I", AccessFlags = 1025)] int GetIterationCount() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a copy of the salt data or null if not specified.</para><para></para> /// </summary> /// <returns> /// <para>a copy of the salt data or null if not specified. </para> /// </returns> /// <java-name> /// getSalt /// </java-name> [Dot42.DexImport("getSalt", "()[B", AccessFlags = 1025, IgnoreFromJava = true)] byte[] GetSalt() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a copy to the password.</para><para></para> /// </summary> /// <returns> /// <para>a copy to the password. </para> /// </returns> /// <java-name> /// getPassword /// </java-name> [Dot42.DexImport("getPassword", "()[C", AccessFlags = 1025)] char[] GetPassword() /* MethodBuilder.Create */ ; } }
using System; using System.Collections; using System.Text.RegularExpressions; using System.Xml; using SharpVectors.Dom.Stylesheets; namespace SharpVectors.Dom.Css { /// <summary> /// The CSSRuleList interface provides the abstraction of an ordered collection of CSS rules. /// The items in the CSSRuleList are accessible via an integral index, starting from 0. /// </summary> /// <developer>niklas@protocol7.com</developer> /// <completed>80</completed> public class CssRuleList : ICssRuleList { #region Static members /* can take two kind of structures: * rule{} * rule{} * or: * { * rule{} * rule{} * } * */ private void Parse(ref string css, object parent, bool readOnly, string[] replacedStrings, CssStyleSheetType origin) { bool withBrackets = false; css = css.Trim(); if(css.StartsWith("{")) { withBrackets = true; css = css.Substring(1); } while(true) { css = css.Trim(); if(css.Length == 0) { if(withBrackets) { throw new DomException(DomExceptionType.SyntaxErr, "Style block missing ending bracket"); } break; } else if(css.StartsWith("}")) { // end of block; css = css.Substring(1); break; } else if(css.StartsWith("@")) { #region Parse at-rules // @-rule CssRule rule; // creates and parses a CssMediaRule or return null rule = CssMediaRule.Parse(ref css, parent, readOnly, replacedStrings, origin); if(rule == null) { // create ImportRule rule = CssImportRule.Parse(ref css, parent, readOnly, replacedStrings, origin); if(rule == null) { // create CharSetRule rule = CssCharsetRule.Parse(ref css, parent, readOnly, replacedStrings, origin); if(rule == null) { rule = CssFontFaceRule.Parse(ref css, parent, readOnly, replacedStrings, origin); if(rule == null) { rule = CssPageRule.Parse(ref css, parent, readOnly, replacedStrings, origin); if(rule == null) { rule = CssUnknownRule.Parse(ref css, parent, readOnly, replacedStrings, origin); } } } } } InsertRule(rule); #endregion } else { // must be a selector or error CssRule rule = CssStyleRule.Parse(ref css, parent, readOnly, replacedStrings, origin); if(rule != null) { InsertRule(rule); } else { // this is an unknown rule format, possibly a new kind of selector. Try to find the end of it to skip it int startBracket = css.IndexOf("{"); int endBracket = css.IndexOf("}"); int endSemiColon = css.IndexOf(";"); int endRule; if(endSemiColon > 0 && endSemiColon < startBracket) { endRule = endSemiColon; } else { endRule = endBracket; } if(endRule > -1) { css = css.Substring(endRule+1); } else { throw new DomException(DomExceptionType.SyntaxErr, "Can not parse the CSS file"); } } //} } } } #endregion #region Constructor /// <summary> /// Constructor for CssRuleList /// </summary> /// <param name="parent">The parent rule or parent stylesheet</param> /// <param name="cssText">The CSS text containing the rules that will be in this list</param> /// <param name="replacedStrings">An array of strings that have been replaced in the string used for matching. These needs to be put back use the DereplaceStrings method</param> /// <param name="origin">The type of CssStyleSheet</param> internal CssRuleList(ref string cssText, object parent, string[] replacedStrings, CssStyleSheetType origin) : this(ref cssText, parent, replacedStrings, false, origin) { } /// <summary> /// Constructor for CssRuleList /// </summary> /// <param name="parent">The parent rule or parent stylesheet</param> /// <param name="cssText">The CSS text containing the rules that will be in this list</param> /// <param name="readOnly">True if this instance is readonly</param> /// <param name="replacedStrings">An array of strings that have been replaced in the string used for matching. These needs to be put back use the DereplaceStrings method</param> /// <param name="origin">The type of CssStyleSheet</param> public CssRuleList(ref string cssText, object parent, string[] replacedStrings, bool readOnly, CssStyleSheetType origin) { Origin = origin; ReadOnly = readOnly; if(parent is CssRule || parent is CssStyleSheet) { Parent = parent; } else { throw new Exception("The CssRuleList constructor can only take a CssRule or CssStyleSheet as it's first argument " + parent.GetType()); } Parse(ref cssText, parent, readOnly, replacedStrings, origin); //AppendRules(cssText, replacedStrings); } #endregion #region Private fields private CssStyleSheetType Origin; private object Parent; private ArrayList cssRules = new ArrayList(); private bool ReadOnly = false; #endregion #region Public methods /// <summary> /// Used to find matching style rules in the cascading order /// </summary> /// <param name="elt">The element to find styles for</param> /// <param name="pseudoElt">The pseudo-element to find styles for</param> /// <param name="ml">The medialist that the document is using</param> /// <param name="csd">A CssStyleDeclaration that holds the collected styles</param> internal void GetStylesForElement(XmlElement elt, string pseudoElt, MediaList ml, CssCollectedStyleDeclaration csd) { ulong len = Length; for(ulong i = 0; i<len; i++) { CssRule csr = (CssRule)this[i]; csr.GetStylesForElement(elt, pseudoElt, ml, csd); } } internal ulong InsertRule(CssRule rule, ulong index) { /* TODO: * HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at the specified index e.g. if an @import rule is inserted after a standard rule set or other at-rule. * SYNTAX_ERR: Raised if the specified rule has a syntax error and is unparsable */ if(ReadOnly) throw new DomException(DomExceptionType.NoModificationAllowedErr); if(index > Length || index<0) throw new DomException(DomExceptionType.IndexSizeErr); if(index == Length) { cssRules.Add(rule); } else { cssRules.Insert((int) index, rule); } return index; } internal ulong InsertRule(CssRule rule) { return InsertRule(rule, Length); } /// <summary> /// Deletes a rule from the list /// </summary> /// <param name="index">The index of the rule to delete</param> /// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR</exception> /// <exception cref="DomException">INDEX_SIZE_ERR</exception> internal void DeleteRule(ulong index) { if(ReadOnly) throw new DomException(DomExceptionType.InvalidModificationErr); if(index >= Length || index<0) throw new DomException(DomExceptionType.IndexSizeErr); cssRules.RemoveAt((int)index); } #endregion #region Implementation of ICssRuleList /// <summary> /// The number of CSSRules in the list. The range of valid child rule indices is 0 to length-1 inclusive /// </summary> public ulong Length { get { return (ulong)cssRules.Count; } } /// <summary> /// Used to retrieve a CSS rule by ordinal index. The order in this collection represents the order of the rules in the CSS style sheet. If index is greater than or equal to the number of rules in the list, this returns null /// </summary> public SharpVectors.Dom.Css.ICssRule this[ulong index] { get { return (index<Length) ? (CssRule)cssRules[(int)index] : null; } set { } } #endregion } }
// Copyright (c) 2012, Event Store LLP // 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 the Event Store LLP 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 // 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.Concurrent; using System.Net; using System.Net.Sockets; using System.Threading; using EventStore.Common.Utils; namespace EventStore.Transport.Tcp { public class TcpClientConnector { private const int CheckPeriodMs = 200; private readonly SocketArgsPool _connectSocketArgsPool; private readonly ConcurrentDictionary<Guid, PendingConnection> _pendingConections; private readonly Timer _timer; public TcpClientConnector() { _connectSocketArgsPool = new SocketArgsPool("TcpClientConnector._connectSocketArgsPool", TcpConfiguration.ConnectPoolSize, CreateConnectSocketArgs); _pendingConections = new ConcurrentDictionary<Guid, PendingConnection>(); _timer = new Timer(TimerCallback, null, CheckPeriodMs, Timeout.Infinite); } private SocketAsyncEventArgs CreateConnectSocketArgs() { var socketArgs = new SocketAsyncEventArgs(); socketArgs.Completed += ConnectCompleted; socketArgs.UserToken = new CallbacksStateToken(); return socketArgs; } public ITcpConnection ConnectTo(Guid connectionId, IPEndPoint remoteEndPoint, TimeSpan connectionTimeout, Action<ITcpConnection> onConnectionEstablished = null, Action<ITcpConnection, SocketError> onConnectionFailed = null, bool verbose = true) { Ensure.NotNull(remoteEndPoint, "remoteEndPoint"); return TcpConnection.CreateConnectingTcpConnection(connectionId, remoteEndPoint, this, connectionTimeout, onConnectionEstablished, onConnectionFailed, verbose); } public ITcpConnection ConnectSslTo(Guid connectionId, IPEndPoint remoteEndPoint, TimeSpan connectionTimeout, string targetHost, bool validateServer, Action<ITcpConnection> onConnectionEstablished = null, Action<ITcpConnection, SocketError> onConnectionFailed = null, bool verbose = true) { Ensure.NotNull(remoteEndPoint, "remoteEndPoint"); Ensure.NotNullOrEmpty(targetHost, "targetHost"); return TcpConnectionSsl.CreateConnectingConnection(connectionId, remoteEndPoint, targetHost, validateServer, this, connectionTimeout, onConnectionEstablished, onConnectionFailed, verbose); } internal void InitConnect(IPEndPoint serverEndPoint, Action<IPEndPoint, Socket> onConnectionEstablished, Action<IPEndPoint, SocketError> onConnectionFailed, ITcpConnection connection, TimeSpan connectionTimeout) { if (serverEndPoint == null) throw new ArgumentNullException("serverEndPoint"); if (onConnectionEstablished == null) throw new ArgumentNullException("onConnectionEstablished"); if (onConnectionFailed == null) throw new ArgumentNullException("onConnectionFailed"); var socketArgs = _connectSocketArgsPool.Get(); var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socketArgs.RemoteEndPoint = serverEndPoint; socketArgs.AcceptSocket = connectingSocket; var callbacks = (CallbacksStateToken)socketArgs.UserToken; callbacks.OnConnectionEstablished = onConnectionEstablished; callbacks.OnConnectionFailed = onConnectionFailed; callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout)); AddToConnecting(callbacks.PendingConnection); try { var firedAsync = connectingSocket.ConnectAsync(socketArgs); if (!firedAsync) ProcessConnect(socketArgs); } catch (ObjectDisposedException) { HandleBadConnect(socketArgs); } } private void ConnectCompleted(object sender, SocketAsyncEventArgs e) { ProcessConnect(e); } private void ProcessConnect(SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) HandleBadConnect(e); else OnSocketConnected(e); } private void HandleBadConnect(SocketAsyncEventArgs socketArgs) { var serverEndPoint = socketArgs.RemoteEndPoint; var socketError = socketArgs.SocketError; var callbacks = (CallbacksStateToken)socketArgs.UserToken; var onConnectionFailed = callbacks.OnConnectionFailed; var pendingConnection = callbacks.PendingConnection; Helper.EatException(() => socketArgs.AcceptSocket.Close(TcpConfiguration.SocketCloseTimeoutMs)); socketArgs.AcceptSocket = null; callbacks.Reset(); _connectSocketArgsPool.Return(socketArgs); if (RemoveFromConnecting(pendingConnection)) onConnectionFailed((IPEndPoint)serverEndPoint, socketError); } private void OnSocketConnected(SocketAsyncEventArgs socketArgs) { var remoteEndPoint = (IPEndPoint)socketArgs.RemoteEndPoint; var socket = socketArgs.AcceptSocket; var callbacks = (CallbacksStateToken)socketArgs.UserToken; var onConnectionEstablished = callbacks.OnConnectionEstablished; var pendingConnection = callbacks.PendingConnection; socketArgs.AcceptSocket = null; callbacks.Reset(); _connectSocketArgsPool.Return(socketArgs); if (RemoveFromConnecting(pendingConnection)) onConnectionEstablished(remoteEndPoint, socket); } private void TimerCallback(object state) { foreach (var pendingConnection in _pendingConections.Values) { if (DateTime.UtcNow >= pendingConnection.WhenToKill && RemoveFromConnecting(pendingConnection)) Helper.EatException(() => pendingConnection.Connection.Close("Connection establishment timeout.")); } _timer.Change(CheckPeriodMs, Timeout.Infinite); } private void AddToConnecting(PendingConnection pendingConnection) { _pendingConections.TryAdd(pendingConnection.Connection.ConnectionId, pendingConnection); } private bool RemoveFromConnecting(PendingConnection pendingConnection) { PendingConnection conn; return _pendingConections.TryRemove(pendingConnection.Connection.ConnectionId, out conn) && Interlocked.CompareExchange(ref conn.Done, 1, 0) == 0; } private class CallbacksStateToken { public Action<IPEndPoint, Socket> OnConnectionEstablished; public Action<IPEndPoint, SocketError> OnConnectionFailed; public PendingConnection PendingConnection; public void Reset() { OnConnectionEstablished = null; OnConnectionFailed = null; PendingConnection = null; } } private class PendingConnection { public readonly ITcpConnection Connection; public readonly DateTime WhenToKill; public int Done; public PendingConnection(ITcpConnection connection, DateTime whenToKill) { Connection = connection; WhenToKill = whenToKill; } } } }
using System.Collections.Generic; using System.Runtime.CompilerServices; using QUnit; using System; namespace CoreLib.TestScript.Reflection { [TestFixture] public class TypeSystemTests { public class ClassWithExpandParamsCtor { public object[] CtorArgs; [ExpandParams] public ClassWithExpandParamsCtor(params object[] args) { this.CtorArgs = args; } } public interface I1 {} public interface I2 : I1 {} public interface I3 {} public interface I4 : I3 {} public class B : I2 {} public class C : B, I4 {} [IncludeGenericArguments] public interface IG<T> {} [IncludeGenericArguments] public class BX<T> {} [IncludeGenericArguments] public class G<T1, T2> : BX<G<T1,C>>, IG<G<T2,string>> { public static string field; static G() { field = typeof(T1).FullName + " " + typeof(T2).FullName; } } public enum E1 {} [Flags] public enum E2 {} [Imported] public interface IImported {} [Serializable] public class BS { public int X; public BS(int x) { X = x; } } public class DS : BS { public int GetX() { return X; } public DS(int x) : base(x) { } } public class CS2 : Record { public int X; } [Serializable(TypeCheckCode = "{$System.Script}.isValue({this}.y)")] public class DS2 : BS { public DS2() : base(0) {} } [Test] public void FullNamePropertyReturnsTheNameWithTheNamespace() { Assert.AreEqual(typeof(TypeSystemTests).FullName, "CoreLib.TestScript.Reflection.TypeSystemTests"); } [Test] public void InstantiatingClassWithConstructorThatNeedsToBeAppliedWorks() { var args = new List<object> { 42, "x", 18 }; var obj = new ClassWithExpandParamsCtor(args.ToArray()); Assert.AreEqual(obj.CtorArgs, args); Assert.AreEqual(obj.GetType(), typeof(ClassWithExpandParamsCtor)); } [Test] public void NamePropertyRemovesTheNamespace() { Assert.AreEqual(typeof(TypeSystemTests).Name, "TypeSystemTests", "non-generic"); Assert.AreEqual(typeof(G<int, string>).Name, "TypeSystemTests$G$2[ss.Int32,String]", "generic"); Assert.AreEqual(typeof(G<BX<double>, string>).Name, "TypeSystemTests$G$2[CoreLib.TestScript.Reflection.TypeSystemTests$BX$1[Number],String]", "nested generic"); } [Test] public void GettingBaseTypeWorks() { Assert.AreStrictEqual(typeof(B).BaseType, typeof(object)); Assert.AreStrictEqual(typeof(C).BaseType, typeof(B)); Assert.AreStrictEqual(typeof(object).BaseType, null); } [Test] public void GettingImplementedInterfacesWorks() { var ifs = typeof(C).GetInterfaces(); Assert.AreEqual(ifs.Length, 4); Assert.IsTrue(ifs.Contains(typeof(I1))); Assert.IsTrue(ifs.Contains(typeof(I2))); Assert.IsTrue(ifs.Contains(typeof(I3))); Assert.IsTrue(ifs.Contains(typeof(I4))); } [Test] public void TypeOfAnOpenGenericClassWorks() { Assert.AreEqual(typeof(G<,>).FullName, "CoreLib.TestScript.Reflection.TypeSystemTests$G$2"); } [Test] public void TypeOfAnOpenGenericInterfaceWorks() { Assert.AreEqual(typeof(IG<>).FullName, "CoreLib.TestScript.Reflection.TypeSystemTests$IG$1"); } [Test] public void TypeOfInstantiatedGenericClassWorks() { Assert.AreEqual(typeof(G<int,C>).FullName, "CoreLib.TestScript.Reflection.TypeSystemTests$G$2[ss.Int32,CoreLib.TestScript.Reflection.TypeSystemTests$C]"); } [Test] public void TypeOfInstantiatedGenericInterfaceWorks() { Assert.AreEqual(typeof(IG<int>).FullName, "CoreLib.TestScript.Reflection.TypeSystemTests$IG$1[ss.Int32]"); } [Test] public void ConstructingAGenericTypeTwiceWithTheSameArgumentsReturnsTheSameInstance() { var t1 = typeof(G<int,C>); var t2 = typeof(G<C,int>); var t3 = typeof(G<int,C>); Assert.IsFalse(t1 == t2); Assert.IsTrue (t1 == t3); } [Test] public void AccessingAStaticMemberInAGenericClassWorks() { Assert.AreEqual(G<int,C>.field, "ss.Int32 CoreLib.TestScript.Reflection.TypeSystemTests$C"); Assert.AreEqual(G<C,int>.field, "CoreLib.TestScript.Reflection.TypeSystemTests$C ss.Int32"); Assert.AreEqual(G<G<C,int>,G<string,C>>.field, "CoreLib.TestScript.Reflection.TypeSystemTests$G$2[CoreLib.TestScript.Reflection.TypeSystemTests$C,ss.Int32] CoreLib.TestScript.Reflection.TypeSystemTests$G$2[String,CoreLib.TestScript.Reflection.TypeSystemTests$C]"); } [Test] public void TypeOfNestedGenericClassWorks() { Assert.AreEqual(typeof(G<int,G<C,IG<string>>>).FullName, "CoreLib.TestScript.Reflection.TypeSystemTests$G$2[ss.Int32,CoreLib.TestScript.Reflection.TypeSystemTests$G$2[CoreLib.TestScript.Reflection.TypeSystemTests$C,CoreLib.TestScript.Reflection.TypeSystemTests$IG$1[String]]]"); } [Test] public void BaseTypeAndImplementedInterfacesForGenericTypeWorks() { Assert.AreEqual(typeof(G<int,G<C,IG<string>>>).BaseType.FullName, "CoreLib.TestScript.Reflection.TypeSystemTests$BX$1[CoreLib.TestScript.Reflection.TypeSystemTests$G$2[ss.Int32,CoreLib.TestScript.Reflection.TypeSystemTests$C]]"); Assert.AreEqual(typeof(G<int,G<C,IG<string>>>).GetInterfaces()[0].FullName, "CoreLib.TestScript.Reflection.TypeSystemTests$IG$1[CoreLib.TestScript.Reflection.TypeSystemTests$G$2[CoreLib.TestScript.Reflection.TypeSystemTests$G$2[CoreLib.TestScript.Reflection.TypeSystemTests$C,CoreLib.TestScript.Reflection.TypeSystemTests$IG$1[String]],String]]"); } [Test] public void IsGenericTypeDefinitionWorksAsExpected() { Assert.IsTrue (typeof(G<,>).IsGenericTypeDefinition); Assert.IsFalse(typeof(G<int,string>).IsGenericTypeDefinition); Assert.IsFalse(typeof(C).IsGenericTypeDefinition); Assert.IsTrue (typeof(IG<>).IsGenericTypeDefinition); Assert.IsFalse(typeof(IG<int>).IsGenericTypeDefinition); Assert.IsFalse(typeof(I2).IsGenericTypeDefinition); Assert.IsFalse(typeof(E1).IsGenericTypeDefinition); } [Test] public void GenericParameterCountReturnsZeroForConstructedTypesAndNonZeroForOpenOnes() { Assert.AreEqual(typeof(G<,>).GenericParameterCount, 2); Assert.AreEqual(typeof(G<int,string>).GenericParameterCount, 0); Assert.AreEqual(typeof(C).GenericParameterCount, 0); Assert.AreEqual(typeof(IG<>).GenericParameterCount, 1); Assert.AreEqual(typeof(IG<int>).GenericParameterCount, 0); Assert.AreEqual(typeof(I2).GenericParameterCount, 0); Assert.AreEqual(typeof(E1).GenericParameterCount, 0); } [Test] public void GetGenericArgumentsReturnsTheCorrectTypesForConstructedTypesOtherwiseNull() { Assert.AreEqual(typeof(G<,>).GetGenericArguments(), null); Assert.AreEqual(typeof(G<int, string>).GetGenericArguments(), new[] { typeof(int), typeof(string) }); Assert.AreEqual(typeof(C).GetGenericArguments(), null); Assert.AreEqual(typeof(IG<>).GetGenericArguments(), null); Assert.AreEqual(typeof(IG<string>).GetGenericArguments(), new[] { typeof(string) }); Assert.AreEqual(typeof(I2).GetGenericArguments(), null); Assert.AreEqual(typeof(E1).GetGenericArguments(), null); } [Test] public void GetGenericTypeDefinitionReturnsTheGenericTypeDefinitionForConstructedTypeOtherwiseNull() { Assert.AreEqual(typeof(G<,>).GetGenericTypeDefinition(), null); Assert.AreEqual(typeof(G<int,string>).GetGenericTypeDefinition(), typeof(G<,>)); Assert.AreEqual(typeof(C).GetGenericTypeDefinition(), null); Assert.AreEqual(typeof(IG<>).GetGenericTypeDefinition(), null); Assert.AreEqual(typeof(IG<string>).GetGenericTypeDefinition(), typeof(IG<>)); Assert.AreEqual(typeof(I2).GetGenericTypeDefinition(), null); Assert.AreEqual(typeof(E1).GetGenericTypeDefinition(), null); } class IsAssignableFromTypes { public class C1 {} [IncludeGenericArguments] public class C2<T> {} public interface I1 {} [IncludeGenericArguments] public interface I2<T1> {} public interface I3 : I1 {} public interface I4 {} [IncludeGenericArguments] public interface I5<T1> : I2<T1> {} public class D1 : C1, I1 {} [IncludeGenericArguments] public class D2<T> : C2<T>, I2<T>, I1 { } public class D3 : C2<int>, I2<string> { } public class D4 : I3, I4 { } public class X1 : I1 { } public class X2 : X1 { } } [Test] public void IsAssignableFromWorks() { Assert.IsTrue (typeof(IsAssignableFromTypes.C1).IsAssignableFrom(typeof(IsAssignableFromTypes.C1))); Assert.IsFalse(typeof(IsAssignableFromTypes.C1).IsAssignableFrom(typeof(object))); Assert.IsTrue (typeof(object).IsAssignableFrom(typeof(IsAssignableFromTypes.C1))); Assert.IsFalse(typeof(IsAssignableFromTypes.I1).IsAssignableFrom(typeof(object))); Assert.IsTrue (typeof(object).IsAssignableFrom(typeof(IsAssignableFromTypes.I1))); Assert.IsFalse(typeof(IsAssignableFromTypes.I3).IsAssignableFrom(typeof(IsAssignableFromTypes.I1))); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsAssignableFrom(typeof(IsAssignableFromTypes.I3))); Assert.IsFalse(typeof(IsAssignableFromTypes.D1).IsAssignableFrom(typeof(IsAssignableFromTypes.C1))); Assert.IsTrue (typeof(IsAssignableFromTypes.C1).IsAssignableFrom(typeof(IsAssignableFromTypes.D1))); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsAssignableFrom(typeof(IsAssignableFromTypes.D1))); Assert.IsTrue (typeof(IsAssignableFromTypes.C2<int>).IsAssignableFrom(typeof(IsAssignableFromTypes.D2<int>))); Assert.IsFalse(typeof(IsAssignableFromTypes.C2<string>).IsAssignableFrom(typeof(IsAssignableFromTypes.D2<int>))); Assert.IsTrue (typeof(IsAssignableFromTypes.I2<int>).IsAssignableFrom(typeof(IsAssignableFromTypes.D2<int>))); Assert.IsFalse(typeof(IsAssignableFromTypes.I2<string>).IsAssignableFrom(typeof(IsAssignableFromTypes.D2<int>))); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsAssignableFrom(typeof(IsAssignableFromTypes.D2<int>))); Assert.IsFalse(typeof(IsAssignableFromTypes.C2<string>).IsAssignableFrom(typeof(IsAssignableFromTypes.D3))); Assert.IsTrue (typeof(IsAssignableFromTypes.C2<int>).IsAssignableFrom(typeof(IsAssignableFromTypes.D3))); Assert.IsFalse(typeof(IsAssignableFromTypes.I2<int>).IsAssignableFrom(typeof(IsAssignableFromTypes.D3))); Assert.IsTrue (typeof(IsAssignableFromTypes.I2<string>).IsAssignableFrom(typeof(IsAssignableFromTypes.D3))); Assert.IsFalse(typeof(IsAssignableFromTypes.I2<int>).IsAssignableFrom(typeof(IsAssignableFromTypes.I5<string>))); Assert.IsTrue (typeof(IsAssignableFromTypes.I2<int>).IsAssignableFrom(typeof(IsAssignableFromTypes.I5<int>))); Assert.IsFalse(typeof(IsAssignableFromTypes.I5<int>).IsAssignableFrom(typeof(IsAssignableFromTypes.I2<int>))); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsAssignableFrom(typeof(IsAssignableFromTypes.D4))); Assert.IsTrue (typeof(IsAssignableFromTypes.I3).IsAssignableFrom(typeof(IsAssignableFromTypes.D4))); Assert.IsTrue (typeof(IsAssignableFromTypes.I4).IsAssignableFrom(typeof(IsAssignableFromTypes.D4))); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsAssignableFrom(typeof(IsAssignableFromTypes.X2))); Assert.IsFalse(typeof(IsAssignableFromTypes.I2<>).IsAssignableFrom(typeof(IsAssignableFromTypes.I5<>))); Assert.IsFalse(typeof(IsAssignableFromTypes.C2<>).IsAssignableFrom(typeof(IsAssignableFromTypes.D2<>))); Assert.IsFalse(typeof(IsAssignableFromTypes.C2<>).IsAssignableFrom(typeof(IsAssignableFromTypes.D3))); Assert.IsFalse(typeof(E1).IsAssignableFrom(typeof(E2))); Assert.IsFalse(typeof(int).IsAssignableFrom(typeof(E1))); Assert.IsTrue (typeof(object).IsAssignableFrom(typeof(E1))); } class IsSubclassOfTypes { public class C1 {} [IncludeGenericArguments] public class C2<T> {} public class D1 : C1 {} [IncludeGenericArguments] public class D2<T> : C2<T> {} public class D3 : C2<int> {} } [Test] public void IsSubclassOfWorks() { Assert.IsFalse(typeof(IsSubclassOfTypes.C1).IsSubclassOf(typeof(IsSubclassOfTypes.C1))); Assert.IsTrue (typeof(IsSubclassOfTypes.C1).IsSubclassOf(typeof(object))); Assert.IsFalse(typeof(object).IsSubclassOf(typeof(IsSubclassOfTypes.C1))); Assert.IsTrue (typeof(IsSubclassOfTypes.D1).IsSubclassOf(typeof(IsSubclassOfTypes.C1))); Assert.IsFalse(typeof(IsSubclassOfTypes.C1).IsSubclassOf(typeof(IsSubclassOfTypes.D1))); Assert.IsTrue (typeof(IsSubclassOfTypes.D1).IsSubclassOf(typeof(object))); Assert.IsTrue (typeof(IsSubclassOfTypes.D2<int>).IsSubclassOf(typeof(IsSubclassOfTypes.C2<int>))); Assert.IsFalse(typeof(IsSubclassOfTypes.D2<string>).IsSubclassOf(typeof(IsSubclassOfTypes.C2<int>))); Assert.IsFalse(typeof(IsSubclassOfTypes.D3).IsSubclassOf(typeof(IsSubclassOfTypes.C2<string>))); Assert.IsTrue (typeof(IsSubclassOfTypes.D3).IsSubclassOf(typeof(IsSubclassOfTypes.C2<int>))); Assert.IsFalse(typeof(IsSubclassOfTypes.D2<>).IsSubclassOf(typeof(IsSubclassOfTypes.C2<>))); Assert.IsFalse(typeof(IsSubclassOfTypes.D3).IsSubclassOf(typeof(IsSubclassOfTypes.C2<>))); } [Test] public void IsClassWorks() { Assert.IsFalse(typeof(E1).IsClass); Assert.IsFalse(typeof(E2).IsClass); Assert.IsTrue (typeof(C).IsClass); Assert.IsTrue (typeof(G<,>).IsClass); Assert.IsTrue (typeof(G<int,string>).IsClass); Assert.IsFalse(typeof(I1).IsClass); Assert.IsFalse(typeof(IG<>).IsClass); Assert.IsFalse(typeof(IG<int>).IsClass); } [Test] public void IsEnumWorks() { Assert.IsTrue (typeof(E1).IsEnum); Assert.IsTrue (typeof(E2).IsEnum); Assert.IsFalse(typeof(C).IsEnum); Assert.IsFalse(typeof(G<,>).IsEnum); Assert.IsFalse(typeof(G<int,string>).IsEnum); Assert.IsFalse(typeof(I1).IsEnum); Assert.IsFalse(typeof(IG<>).IsEnum); Assert.IsFalse(typeof(IG<int>).IsEnum); } [Test] public void IsFlagsWorks() { Assert.IsFalse(typeof(E1).IsFlags); Assert.IsTrue (typeof(E2).IsFlags); Assert.IsFalse(typeof(C).IsFlags); Assert.IsFalse(typeof(G<,>).IsFlags); Assert.IsFalse(typeof(G<int,string>).IsFlags); Assert.IsFalse(typeof(I1).IsFlags); Assert.IsFalse(typeof(IG<>).IsFlags); Assert.IsFalse(typeof(IG<int>).IsFlags); } [Test] public void IsInterfaceWorks() { Assert.IsFalse(typeof(E1).IsInterface); Assert.IsFalse(typeof(E2).IsInterface); Assert.IsFalse(typeof(C).IsInterface); Assert.IsFalse(typeof(G<,>).IsInterface); Assert.IsFalse(typeof(G<int,string>).IsInterface); Assert.IsTrue (typeof(I1).IsInterface); Assert.IsTrue (typeof(IG<>).IsInterface); Assert.IsTrue (typeof(IG<int>).IsInterface); } [Test] public void IsInstanceOfTypeWorksForReferenceTypes() { Assert.IsFalse(Type.IsInstanceOfType(new object(), typeof(IsAssignableFromTypes.C1))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.C1(), typeof(object))); Assert.IsFalse(Type.IsInstanceOfType(new object(), typeof(IsAssignableFromTypes.I1))); Assert.IsFalse(Type.IsInstanceOfType(new IsAssignableFromTypes.C1(), typeof(IsAssignableFromTypes.D1))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D1(), typeof(IsAssignableFromTypes.C1))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D1(), typeof(IsAssignableFromTypes.I1))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D2<int>(), typeof(IsAssignableFromTypes.C2<int>))); Assert.IsFalse(Type.IsInstanceOfType(new IsAssignableFromTypes.D2<int>(), typeof(IsAssignableFromTypes.C2<string>))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D2<int>(), typeof(IsAssignableFromTypes.I2<int>))); Assert.IsFalse(Type.IsInstanceOfType(new IsAssignableFromTypes.D2<int>(), typeof(IsAssignableFromTypes.I2<string>))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D2<int>(), typeof(IsAssignableFromTypes.I1))); Assert.IsFalse(Type.IsInstanceOfType(new IsAssignableFromTypes.D3(), typeof(IsAssignableFromTypes.C2<string>))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D3(), typeof(IsAssignableFromTypes.C2<int>))); Assert.IsFalse(Type.IsInstanceOfType(new IsAssignableFromTypes.D3(), typeof(IsAssignableFromTypes.I2<int>))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D3(), typeof(IsAssignableFromTypes.I2<string>))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D4(), typeof(IsAssignableFromTypes.I1))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D4(), typeof(IsAssignableFromTypes.I3))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.D4(), typeof(IsAssignableFromTypes.I4))); Assert.IsTrue (Type.IsInstanceOfType(new IsAssignableFromTypes.X2(), typeof(IsAssignableFromTypes.I1))); Assert.IsFalse(Type.IsInstanceOfType(new IsAssignableFromTypes.D3(), typeof(IsAssignableFromTypes.C2<>))); Assert.IsTrue (Type.IsInstanceOfType(new E2(), typeof(E1))); Assert.IsTrue (Type.IsInstanceOfType(new E1(), typeof(int))); Assert.IsTrue (Type.IsInstanceOfType(new E1(), typeof(object))); Assert.IsFalse(Type.IsInstanceOfType(null, typeof(object))); Assert.IsFalse(typeof(IsAssignableFromTypes.C1).IsInstanceOfType(new object())); Assert.IsTrue (typeof(object).IsInstanceOfType(new IsAssignableFromTypes.C1())); Assert.IsFalse(typeof(IsAssignableFromTypes.I1).IsInstanceOfType(new object())); Assert.IsFalse(typeof(IsAssignableFromTypes.D1).IsInstanceOfType(new IsAssignableFromTypes.C1())); Assert.IsTrue (typeof(IsAssignableFromTypes.C1).IsInstanceOfType(new IsAssignableFromTypes.D1())); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsInstanceOfType(new IsAssignableFromTypes.D1())); Assert.IsTrue (typeof(IsAssignableFromTypes.C2<int>).IsInstanceOfType(new IsAssignableFromTypes.D2<int>())); Assert.IsFalse(typeof(IsAssignableFromTypes.C2<string>).IsInstanceOfType(new IsAssignableFromTypes.D2<int>())); Assert.IsTrue (typeof(IsAssignableFromTypes.I2<int>).IsInstanceOfType(new IsAssignableFromTypes.D2<int>())); Assert.IsFalse(typeof(IsAssignableFromTypes.I2<string>).IsInstanceOfType(new IsAssignableFromTypes.D2<int>())); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsInstanceOfType(new IsAssignableFromTypes.D2<int>())); Assert.IsFalse(typeof(IsAssignableFromTypes.C2<string>).IsInstanceOfType(new IsAssignableFromTypes.D3())); Assert.IsTrue (typeof(IsAssignableFromTypes.C2<int>).IsInstanceOfType(new IsAssignableFromTypes.D3())); Assert.IsFalse(typeof(IsAssignableFromTypes.I2<int>).IsInstanceOfType(new IsAssignableFromTypes.D3())); Assert.IsTrue (typeof(IsAssignableFromTypes.I2<string>).IsInstanceOfType(new IsAssignableFromTypes.D3())); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsInstanceOfType(new IsAssignableFromTypes.D4())); Assert.IsTrue (typeof(IsAssignableFromTypes.I3).IsInstanceOfType(new IsAssignableFromTypes.D4())); Assert.IsTrue (typeof(IsAssignableFromTypes.I4).IsInstanceOfType(new IsAssignableFromTypes.D4())); Assert.IsTrue (typeof(IsAssignableFromTypes.I1).IsInstanceOfType(new IsAssignableFromTypes.X2())); Assert.IsFalse(typeof(IsAssignableFromTypes.C2<>).IsInstanceOfType(new IsAssignableFromTypes.D3())); Assert.IsTrue (typeof(E1).IsInstanceOfType(new E2())); Assert.IsTrue (typeof(int).IsInstanceOfType(new E1())); Assert.IsTrue (typeof(object).IsInstanceOfType(new E1())); Assert.IsFalse(typeof(object).IsInstanceOfType(null)); } public class BaseUnnamedConstructorWithoutArgumentsTypes { public class B { public string messageB; public B() { messageB = "X"; } } public class D : B { public string messageD; public D() { messageD = "Y"; } } } [Test] public void InvokingBaseUnnamedConstructorWithoutArgumentsWorks() { var d = new BaseUnnamedConstructorWithoutArgumentsTypes.D(); Assert.AreEqual(d.messageB + "|" + d.messageD, "X|Y"); } public class BaseUnnamedConstructorWithArgumentsTypes { public class B { public string messageB; public B(int x, int y) { messageB = x + " " + y; } } public class D : B { public string messageD; public D(int x, int y) : base(x + 1, y + 1) { messageD = x + " " + y; } } } [Test] public void InvokingBaseUnnamedConstructorWithArgumentsWorks() { var d = new BaseUnnamedConstructorWithArgumentsTypes.D(5, 8); Assert.AreEqual(d.messageB + "|" + d.messageD, "6 9|5 8"); } public class BaseNamedConstructorWithoutArgumentsTypes { public class B { public string messageB; [ScriptName("myCtor")] public B() { messageB = "X"; } } public class D : B { public string messageD; public D() { messageD = "Y"; } } } [Test] public void InvokingBaseNamedConstructorWithoutArgumentsWorks() { var d = new BaseNamedConstructorWithoutArgumentsTypes.D(); Assert.AreEqual(d.messageB + "|" + d.messageD, "X|Y"); } public class BaseNamedConstructorWithArgumentsTypes { public class B { public string messageB; [ScriptName("myCtor")] public B(int x, int y) { messageB = x + " " + y; } } public class D : B { public string messageD; public D(int x, int y) : base(x + 1, y + 1) { messageD = x + " " + y; } } } [Test] public void InvokingBaseNamedConstructorWithArgumentsWorks() { var d = new BaseNamedConstructorWithArgumentsTypes.D(5, 8); Assert.AreEqual(d.messageB + "|" + d.messageD, "6 9|5 8"); } public class ConstructingInstanceWithNamedConstructorTypes { public class D { public string GetMessage() { return "The message " + f; } private string f; [ScriptName("myCtor")] public D() { f = "from ctor"; } } } [Test] public void ConstructingInstanceWithNamedConstructorWorks() { var d = new ConstructingInstanceWithNamedConstructorTypes.D(); Assert.AreEqual(d.GetType(), typeof(ConstructingInstanceWithNamedConstructorTypes.D)); Assert.AreEqual(d.GetMessage(), "The message from ctor"); } public class BaseMethodInvocationTypes { public class B { public virtual int F(int x, int y) { return x - y; } [IncludeGenericArguments] public virtual int G<T>(int x, int y) { return x - y; } } public class D : B { public override int F(int x, int y) { return x + y; } public override int G<T>(int x, int y) { return x + y; } public int DoIt(int x, int y) { return base.F(x, y); } public int DoItGeneric(int x, int y) { return base.G<string>(x, y); } } } [Test] public void InvokingBaseMethodWorks() { Assert.AreEqual(new BaseMethodInvocationTypes.D().DoIt(5, 3), 2); } [Test] public void InvokingGenericBaseMethodWorks() { Assert.AreEqual(new BaseMethodInvocationTypes.D().DoItGeneric(5, 3), 2); } public class MethodGroupConversionTypes { public class C { private int m; public int F(int x, int y) { return x + y + m; } [IncludeGenericArguments] public string G<T>(int x, int y) { return x + y + m + typeof(T).Name; } public C(int m) { this.m = m; } public Func<int, int, int> GetF() { return F; } public Func<int, int, string> GetG() { return G<string>; } } public class B { public int m; public virtual int F(int x, int y) { return x + y + m; } [IncludeGenericArguments] public virtual string G<T>(int x, int y) { return x + y + m + typeof(T).Name; } public B(int m) { this.m = m; } } public class D : B { public override int F(int x, int y) { return x - y - m; } public override string G<T>(int x, int y) { return x - y - m + typeof(T).Name; } public Func<int, int, int> GetF() { return base.F; } public Func<int, int, string> GetG() { return base.G<string>; } public D(int m) : base(m) { } } } [Test] public void MethodGroupConversionWorks() { var f = new MethodGroupConversionTypes.C(4).GetF(); Assert.AreEqual(f(5, 3), 12); } [Test] public void MethodGroupConversionOnGenericMethodWorks() { var f = new MethodGroupConversionTypes.C(4).GetG(); Assert.AreEqual(f(5, 3), "12String"); } [Test] public void MethodGroupConversionOnBaseMethodWorks() { var f = new MethodGroupConversionTypes.D(4).GetF(); Assert.AreEqual(f(3, 5), 12); } [Test] public void MethodGroupConversionOnGenericBaseMethodWorks() { var g = new MethodGroupConversionTypes.C(4).GetG(); Assert.AreEqual(g(5, 3), "12String"); } [Test] public void ImportedInterfaceAppearsAsObjectWhenUsedAsGenericArgument() { Assert.AreStrictEqual(typeof(BX<IImported>), typeof(BX<object>)); } [Test] public void FalseIsFunctionShouldReturnFalse() { Assert.IsFalse((object)false is Function); } [Test] public void CastingUndefinedToOtherTypeShouldReturnUndefined() { Assert.AreEqual(Type.GetScriptType((C)Script.Undefined), "undefined"); } [Test] public void NonSerializableTypeCanInheritFromSerializableType() { var d = new DS(42); Assert.AreEqual(d.X, 42, "d.X"); Assert.AreEqual(d.GetX(), 42, "d.GetX"); } [Test] public void InheritingFromRecordWorks() { var c = new CS2() { X = 42 }; Assert.AreEqual(c.X, 42); } [Test] public void InstanceOfWorksForSerializableTypesWithCustomTypeCheckCode() { object o1 = new { x = 1 }; object o2 = new { x = 1, y = 2 }; Assert.IsFalse(typeof(DS2).IsInstanceOfType(o1), "o1 should not be of type"); Assert.IsTrue (typeof(DS2).IsInstanceOfType(o2), "o2 should be of type"); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using NLog.Config; /// <summary> /// Utilities for dealing with <see cref="StackTraceUsage"/> values. /// </summary> internal static class StackTraceUsageUtils { private static readonly Assembly nlogAssembly = typeof(StackTraceUsageUtils).GetAssembly(); private static readonly Assembly mscorlibAssembly = typeof(string).GetAssembly(); private static readonly Assembly systemAssembly = typeof(Debug).GetAssembly(); internal static StackTraceUsage Max(StackTraceUsage u1, StackTraceUsage u2) { return (StackTraceUsage)Math.Max((int)u1, (int)u2); } public static int GetFrameCount(this StackTrace strackTrace) { #if !NETSTANDARD1_0 return strackTrace.FrameCount; #else return strackTrace.GetFrames().Length; #endif } public static string GetStackFrameMethodName(MethodBase method, bool includeMethodInfo, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if (method == null) return null; string methodName = method.Name; var callerClassType = method.DeclaringType; if (cleanAsyncMoveNext && methodName == "MoveNext" && callerClassType?.DeclaringType != null && callerClassType.Name.StartsWith("<")) { // NLog.UnitTests.LayoutRenderers.CallSiteTests+<CleanNamesOfAsyncContinuations>d_3'1.MoveNext int endIndex = callerClassType.Name.IndexOf('>', 1); if (endIndex > 1) { methodName = callerClassType.Name.Substring(1, endIndex - 1); if (methodName.StartsWith("<")) methodName = methodName.Substring(1, methodName.Length - 1); // Local functions, and anonymous-methods in Task.Run() } } // Clean up the function name if it is an anonymous delegate // <.ctor>b__0 // <Main>b__2 if (cleanAnonymousDelegates && (methodName.StartsWith("<") && methodName.Contains("__") && methodName.Contains(">"))) { int startIndex = methodName.IndexOf('<') + 1; int endIndex = methodName.IndexOf('>'); methodName = methodName.Substring(startIndex, endIndex - startIndex); } if (includeMethodInfo && methodName == method.Name) { methodName = method.ToString(); } return methodName; } public static string GetStackFrameMethodClassName(MethodBase method, bool includeNameSpace, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if (method == null) return null; var callerClassType = method.DeclaringType; if (cleanAsyncMoveNext && method.Name == "MoveNext" && callerClassType?.DeclaringType != null && callerClassType.Name.StartsWith("<")) { // NLog.UnitTests.LayoutRenderers.CallSiteTests+<CleanNamesOfAsyncContinuations>d_3'1 int endIndex = callerClassType.Name.IndexOf('>', 1); if (endIndex > 1) { callerClassType = callerClassType.DeclaringType; } } if (!includeNameSpace && callerClassType?.DeclaringType != null && callerClassType.IsNested && callerClassType.GetCustomAttribute<CompilerGeneratedAttribute>() != null) { return callerClassType.DeclaringType.Name; } string className = includeNameSpace ? callerClassType?.FullName : callerClassType?.Name; if (cleanAnonymousDelegates && className != null) { // NLog.UnitTests.LayoutRenderers.CallSiteTests+<>c__DisplayClassa int index = className.IndexOf("+<>", StringComparison.Ordinal); if (index >= 0) { className = className.Substring(0, index); } } return className; } /// <summary> /// Gets the fully qualified name of the class invoking the calling method, including the /// namespace but not the assembly. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static string GetClassFullName() { int framesToSkip = 2; string className = string.Empty; #if SILVERLIGHT var stackFrame = new StackFrame(framesToSkip); className = GetClassFullName(stackFrame); #elif !NETSTANDARD1_0 var stackFrame = new StackFrame(framesToSkip, false); className = GetClassFullName(stackFrame); #else var stackTrace = Environment.StackTrace; var stackTraceLines = stackTrace.Replace("\r", "").SplitAndTrimTokens('\n'); for (int i = 0; i < stackTraceLines.Length; ++i) { var callingClassAndMethod = stackTraceLines[i].Split(new[] { " ", "<>", "(", ")" }, StringSplitOptions.RemoveEmptyEntries)[1]; int methodStartIndex = callingClassAndMethod.LastIndexOf(".", StringComparison.Ordinal); if (methodStartIndex > 0) { // Trim method name. var callingClass = callingClassAndMethod.Substring(0, methodStartIndex); // Needed because of extra dot, for example if method was .ctor() className = callingClass.TrimEnd('.'); if (!className.StartsWith("System.Environment") && framesToSkip != 0) { i += framesToSkip - 1; framesToSkip = 0; continue; } if (!className.StartsWith("System.")) break; } } #endif return className; } #if !NETSTANDARD1_0 /// <summary> /// Gets the fully qualified name of the class invoking the calling method, including the /// namespace but not the assembly. /// </summary> /// <param name="stackFrame">StackFrame from the calling method</param> /// <returns>Fully qualified class name</returns> public static string GetClassFullName(StackFrame stackFrame) { string className = LookupClassNameFromStackFrame(stackFrame); if (string.IsNullOrEmpty(className)) { #if SILVERLIGHT var stackTrace = new StackTrace(); #else var stackTrace = new StackTrace(false); #endif className = GetClassFullName(stackTrace); if (string.IsNullOrEmpty(className)) className = stackFrame.GetMethod()?.Name ?? string.Empty; } return className; } #endif private static string GetClassFullName(StackTrace stackTrace) { foreach (StackFrame frame in stackTrace.GetFrames()) { string className = LookupClassNameFromStackFrame(frame); if (!string.IsNullOrEmpty(className)) { return className; } } return string.Empty; } /// <summary> /// Returns the assembly from the provided StackFrame (If not internal assembly) /// </summary> /// <returns>Valid assembly, or null if assembly was internal</returns> public static Assembly LookupAssemblyFromStackFrame(StackFrame stackFrame) { var method = stackFrame.GetMethod(); if (method == null) { return null; } var assembly = method.DeclaringType?.GetAssembly() ?? method.Module?.Assembly; // skip stack frame if the method declaring type assembly is from hidden assemblies list if (assembly == nlogAssembly) { return null; } if (assembly == mscorlibAssembly) { return null; } if (assembly == systemAssembly) { return null; } return assembly; } /// <summary> /// Returns the classname from the provided StackFrame (If not from internal assembly) /// </summary> /// <param name="stackFrame"></param> /// <returns>Valid class name, or empty string if assembly was internal</returns> public static string LookupClassNameFromStackFrame(StackFrame stackFrame) { var method = stackFrame.GetMethod(); if (method != null && LookupAssemblyFromStackFrame(stackFrame) != null) { string className = GetStackFrameMethodClassName(method, true, true, true); if (!string.IsNullOrEmpty(className)) { if (!className.StartsWith("System.", StringComparison.Ordinal)) return className; } else { className = method.Name ?? string.Empty; if (className != "lambda_method" && className != "MoveNext") return className; } } return string.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using Microsoft.Xml.Serialization; using System.Diagnostics; namespace Microsoft.Xml.Schema { using System; using Microsoft.Xml; /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSchemaElement : XmlSchemaParticle { private bool _isAbstract; private bool _hasAbstractAttribute; private bool _isNillable; private bool _hasNillableAttribute; private bool _isLocalTypeDerivationChecked; private XmlSchemaDerivationMethod _block = XmlSchemaDerivationMethod.None; private XmlSchemaDerivationMethod _final = XmlSchemaDerivationMethod.None; private XmlSchemaForm _form = XmlSchemaForm.None; private string _defaultValue; private string _fixedValue; private string _name; private XmlQualifiedName _refName = XmlQualifiedName.Empty; private XmlQualifiedName _substitutionGroup = XmlQualifiedName.Empty; private XmlQualifiedName _typeName = XmlQualifiedName.Empty; private XmlSchemaType _type = null; private XmlQualifiedName _qualifiedName = XmlQualifiedName.Empty; private XmlSchemaType _elementType; private XmlSchemaDerivationMethod _blockResolved; private XmlSchemaDerivationMethod _finalResolved; private XmlSchemaObjectCollection _constraints; private SchemaElementDecl _elementDecl; /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.IsAbstract"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("abstract"), DefaultValue(false)] public bool IsAbstract { get { return _isAbstract; } set { _isAbstract = value; _hasAbstractAttribute = true; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.Block"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("block"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod Block { get { return _block; } set { _block = value; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.DefaultValue"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("default")] [DefaultValue(null)] public string DefaultValue { get { return _defaultValue; } set { _defaultValue = value; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.Final"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("final"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod Final { get { return _final; } set { _final = value; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.FixedValue"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("fixed")] [DefaultValue(null)] public string FixedValue { get { return _fixedValue; } set { _fixedValue = value; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.Form"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("form"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm Form { get { return _form; } set { _form = value; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.Name"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("name"), DefaultValue("")] public string Name { get { return _name; } set { _name = value; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.IsNillable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("nillable"), DefaultValue(false)] public bool IsNillable { get { return _isNillable; } set { _isNillable = value; _hasNillableAttribute = true; } } [XmlIgnore] internal bool HasNillableAttribute { get { return _hasNillableAttribute; } } [XmlIgnore] internal bool HasAbstractAttribute { get { return _hasAbstractAttribute; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.RefName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("ref")] public XmlQualifiedName RefName { get { return _refName; } set { _refName = (value == null ? XmlQualifiedName.Empty : value); } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.SubstitutionGroup"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("substitutionGroup")] public XmlQualifiedName SubstitutionGroup { get { return _substitutionGroup; } set { _substitutionGroup = (value == null ? XmlQualifiedName.Empty : value); } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.SchemaTypeName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("type")] public XmlQualifiedName SchemaTypeName { get { return _typeName; } set { _typeName = (value == null ? XmlQualifiedName.Empty : value); } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.SchemaType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("complexType", typeof(XmlSchemaComplexType)), XmlElement("simpleType", typeof(XmlSchemaSimpleType))] public XmlSchemaType SchemaType { get { return _type; } set { _type = value; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.Constraints"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("key", typeof(XmlSchemaKey)), XmlElement("keyref", typeof(XmlSchemaKeyref)), XmlElement("unique", typeof(XmlSchemaUnique))] public XmlSchemaObjectCollection Constraints { get { if (_constraints == null) { _constraints = new XmlSchemaObjectCollection(); } return _constraints; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.QualifiedName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlQualifiedName QualifiedName { get { return _qualifiedName; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.ElementType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] [Obsolete("This property has been deprecated. Please use ElementSchemaType property that returns a strongly typed element type. http://go.microsoft.com/fwlink/?linkid=14202")] public object ElementType { get { if (_elementType == null) return null; if (_elementType.QualifiedName.Namespace == XmlReservedNs.NsXs) { return _elementType.Datatype; //returns XmlSchemaDatatype; } return _elementType; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.ElementType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaType ElementSchemaType { get { return _elementType; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.BlockResolved"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaDerivationMethod BlockResolved { get { return _blockResolved; } } /// <include file='doc\XmlSchemaElement.uex' path='docs/doc[@for="XmlSchemaElement.FinalResolved"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaDerivationMethod FinalResolved { get { return _finalResolved; } } internal XmlReader Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) { if (schemaSet != null) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = schemaSet; readerSettings.ValidationEventHandler += valEventHandler; return new XsdValidatingReader(reader, resolver, readerSettings, this); } return null; } internal void SetQualifiedName(XmlQualifiedName value) { _qualifiedName = value; } internal void SetElementType(XmlSchemaType value) { _elementType = value; } internal void SetBlockResolved(XmlSchemaDerivationMethod value) { _blockResolved = value; } internal void SetFinalResolved(XmlSchemaDerivationMethod value) { _finalResolved = value; } [XmlIgnore] internal bool HasDefault { get { return _defaultValue != null && _defaultValue.Length > 0; } } internal bool HasConstraints { get { return _constraints != null && _constraints.Count > 0; } } internal bool IsLocalTypeDerivationChecked { get { return _isLocalTypeDerivationChecked; } set { _isLocalTypeDerivationChecked = value; } } internal SchemaElementDecl ElementDecl { get { return _elementDecl; } set { _elementDecl = value; } } [XmlIgnore] internal override string NameAttribute { get { return Name; } set { Name = value; } } [XmlIgnore] internal override string NameString { get { return _qualifiedName.ToString(); } } internal override XmlSchemaObject Clone() { System.Diagnostics.Debug.Assert(false, "Should never call Clone() on XmlSchemaElement. Call Clone(XmlSchema) instead."); return Clone(null); } internal XmlSchemaObject Clone(XmlSchema parentSchema) { XmlSchemaElement newElem = (XmlSchemaElement)MemberwiseClone(); //Deep clone the QNames as these will be updated on chameleon includes newElem._refName = _refName.Clone(); newElem._substitutionGroup = _substitutionGroup.Clone(); newElem._typeName = _typeName.Clone(); newElem._qualifiedName = _qualifiedName.Clone(); // If this element has a complex type which is anonymous (declared in place with the element) // it needs to be cloned as well, since it may contain named elements and such. And these names // will need to be cloned since they may change their namespace on chameleon includes XmlSchemaComplexType complexType = _type as XmlSchemaComplexType; if (complexType != null && complexType.QualifiedName.IsEmpty) { newElem._type = (XmlSchemaType)complexType.Clone(parentSchema); } //Clear compiled tables newElem._constraints = null; return newElem; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using Volte.Utils; namespace Volte.Data.Json { [Serializable] public class JSONObject { const string ZFILE_NAME = "JSONObject"; // Methods public JSONObject() { _Dictionary = new Dictionary<string, JSONObjectPair>(StringComparer.InvariantCultureIgnoreCase); } public JSONObject(string cData) { _Dictionary = new Dictionary<string, JSONObjectPair>(StringComparer.InvariantCultureIgnoreCase); if (!string.IsNullOrEmpty(cData)) { Parser(cData); } } public JSONObject(string Name, string Value) { _Dictionary = new Dictionary<string, JSONObjectPair>(StringComparer.InvariantCultureIgnoreCase); this.SetValue(Name, Value); } internal JSONObject(Lexer _Lexer) { _Dictionary = new Dictionary<string, JSONObjectPair>(StringComparer.InvariantCultureIgnoreCase); this.Read(_Lexer); } internal void Read(Lexer _Lexer) { if (_Lexer.MatchChar('{')) { _Lexer.NextToken(); if (_Lexer.MatchChar('}')) { _Lexer.NextToken(); return; } for (; ; ) { JSONObjectPair variable1 = new JSONObjectPair(_Lexer); _Dictionary[variable1.Name] = variable1; if (_Lexer.MatchChar(',')) { _Lexer.NextToken(); } else { break; } } _Lexer.NextToken(); } } internal void Write(StringBuilder writer) { writer.AppendLine("{"); if (_Dictionary.Count > 0) { int i = 0; foreach (string name in _Dictionary.Keys) { if (!string.IsNullOrEmpty(name)) { if (i > 0) { writer.AppendLine(","); } _Dictionary[name].Write(writer); i++; } } } writer.AppendLine(""); writer.AppendLine("}"); } public void Parser(string cString) { if (string.IsNullOrEmpty(cString)) { return; } this.Read(new Lexer(cString)); } public void Merge(JSONObject obj) { foreach (string name in obj.Names) { if (obj.IsJSONObject(name)) { this.SetValue(name, obj.GetJSONObject(name)); } else if (obj.IsJSONArray(name)) { this.SetValue(name, obj.GetJSONArray(name)); } else { this.SetValue(name, obj.GetValue(name)); } } } public override string ToString() { StringBuilder s = new StringBuilder(); this.Write(s); return s.ToString(); } public bool ContainsKey(string name) { return _Dictionary.ContainsKey(name); } public void SetDateTime(string name, DateTime value) { this.SetValue(name, value, "datetime"); } public void SetDateTime(string name, DateTime? value) { if (value.HasValue) { this.SetValue(name, value.Value, "datetime"); } else { this.SetValue(name, "", "datetime"); } } public void SetValue(string name, DateTime value) { this.SetValue(name, value, "datetime"); } public DateTime GetDateTime(string Name) { object o = GetValue(Name); try { return Util.ToDateTime(o); } catch { return Util.DateTime_MinValue; } } public bool GetBoolean(string Name) { return GetBoolean(Name , false); } public bool GetBoolean(string Name , bool bDefault) { object o = GetValue(Name); try { return Convert.ToBoolean(o); } catch { return bDefault; } } public int GetInteger(string Name) { return GetInteger(Name , 0); } public int GetInteger(string Name, int nDefault) { object o = GetValue(Name); if (o == null || string.IsNullOrEmpty(o.ToString())) { return nDefault; } return Util.ToInt32(o); } public long GetLong(string Name) { return GetLong(Name , 0); } public long GetLong(string Name, int nDefault) { object o = GetValue(Name); if (o == null || string.IsNullOrEmpty(o.ToString())) { return nDefault; } return Util.ToLong(o); } public decimal GetDecimal(string Name) { return GetDecimal(Name , 0M); } public decimal GetDecimal(string Name,decimal nDefault) { object o = GetValue(Name); if (o == null || string.IsNullOrEmpty(o.ToString())) { return nDefault; } return Util.ToDecimal(o); } public void SetDouble(string name, double value) { this.SetValue(name, value, "decimal"); } public double GetDouble(string name) { return GetDouble(name,0); } public double GetDouble(string name , double nDefault) { object o = GetValue(name); if (o == null || string.IsNullOrEmpty(o.ToString())) { return nDefault; } return Convert.ToDouble(o); } public void SetDecimal(string name, decimal value) { this.SetValue(name, value, "decimal"); } public bool IsJSONObject(string name) { return this.GetType(name) == "v"; } public bool IsJSONArray(string name) { return this.GetType(name) == "l"; } public JSONObject GetJSONObject(string Name) { JSONObject _JSONObject = new JSONObject(); if (this.GetType(Name) == "v") { if (_Dictionary.ContainsKey(Name)) { _JSONObject = (JSONObject)_Dictionary[Name].Value; } } return _JSONObject; } public JSONArray GetJSONArray(string Name) { JSONArray _JSONArray = new JSONArray(); if (this.GetType(Name) == "l") { if (_Dictionary.ContainsKey(Name)) { _JSONArray = (JSONArray)_Dictionary[Name].Value; } } return _JSONArray; } public string Concat(string names, string split) { string[] aValue = names.Split((new char[1] { ',' })); string sReturn = ""; int i = 1; foreach (string sName in aValue) { if (sName != "") { string s = this.GetValue(sName); if (s != "") { sReturn = sReturn + s; if (i < aValue.Length) { sReturn = sReturn + split; } } } i++; } return sReturn; } public bool HasAttr(string name) { if (string.IsNullOrEmpty(name)) { return false; } int p = name.IndexOf("."); if (p > 0) { string f = name.Substring(0, p); string n = name.Substring(p + 1); return GetJSONObject(f).HasAttr(n); } else { return ContainsKey(name); } } public void Attr(string name , string value) { if (string.IsNullOrEmpty(name)) { return; } int p = name.IndexOf("."); if (p > 0) { string f = name.Substring(0, p); string n = name.Substring(p + 1); GetJSONObject(f).Attr(n , value); } else { SetValue(name , value); } } public string Attr(string name) { if (string.IsNullOrEmpty(name)) { return ""; } int p = name.IndexOf("."); if (p > 0) { string f = name.Substring(0, p); string n = name.Substring(p + 1); return GetJSONObject(f).Attr(n); } else { return GetValue(name); } } public string GetValue(string name) { return GetValue(name , ""); } public string GetValue(string name , string sDefault) { JSONObjectPair result = null; if (_Dictionary.TryGetValue(name, out result)) { if (result.Value == null) { return sDefault; } else { return result.Value.ToString(); } } return sDefault; } public string GetType(string name) { if (_Dictionary.ContainsKey(name)) { JSONObjectPair variable1 = _Dictionary[name]; return variable1.Type; } else { return "string"; } } public void SetValue(string name, JSONArray value) { _Dictionary[name] = new JSONObjectPair(name, value, "l"); } public void SetValue(string name, JSONObject value) { _Dictionary[name] = new JSONObjectPair(name, value, "v"); } public void SetValue(string name, bool value) { this.SetBoolean(name, value); } public void SetValue(string name, int value) { this.SetInteger(name, value); } public void SetValue(string name, long value) { this.SetLong(name, value); } public void SetBoolean(string name, bool value) { _Dictionary[name] = new JSONObjectPair(name, value, "boolean"); } public void SetLong(string name, long value) { _Dictionary[name] = new JSONObjectPair(name, value, "integer"); } public void SetInteger(string name, int value) { _Dictionary[name] = new JSONObjectPair(name, value, "integer"); } public void SetValue(string name, string value) { this.SetValue(name, value, ""); } public void Add(object key, object value) { SetValue(key.ToString(), value, "string"); } public void Remove(object key) { _Dictionary.Remove(key.ToString()); } public void SetValue(string name, object value) { _Dictionary[name] = new JSONObjectPair(name, value); } public void SetValue(string name, object value, string cType) { _Dictionary[name] = new JSONObjectPair(name, value, cType); } public void Clear() { _Dictionary = new Dictionary<string, JSONObjectPair>(StringComparer.InvariantCultureIgnoreCase); } public JSONObject Clone() { StringBuilder s = new StringBuilder(); this.Write(s); return new JSONObject(s.ToString()); } public List<string> Names { get { List<string> _Names = new List<string>(); foreach (string name in _Dictionary.Keys) { _Names.Add(name); } return _Names; } } public object this[object name] { get { return this[name.ToString()]; } set { } } public object this[string name] { get { JSONObjectPair result = null; if (_Dictionary.TryGetValue(name , out result)) { return result.Value; } return result; } set { string t = "string"; if (value is string) { t = "string"; }else if (value is DateTime) { t = "datetime"; } else if (value is decimal) { t = "decimal"; } else if (value is int) { t = "integer"; } _Dictionary[name] = new JSONObjectPair(name, value, t); } } public int Count { get { return _Dictionary.Count; } } private Dictionary<string, JSONObjectPair> _Dictionary = new Dictionary<string, JSONObjectPair>(StringComparer.InvariantCultureIgnoreCase); } }
using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.IO; using System.Text.RegularExpressions; using System.Text; using System.Diagnostics; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { public class ExternalGitSourceProvider : GitSourceProvider { public override string RepositoryType => TeamFoundation.DistributedTask.Pipelines.RepositoryTypes.ExternalGit; // external git repository won't use auth header cmdline arg, since we don't know the auth scheme. public override bool GitUseAuthHeaderCmdlineArg => false; public override bool GitLfsUseAuthHeaderCmdlineArg => false; public override void RequirementCheck(IExecutionContext executionContext, ServiceEndpoint endpoint) { #if OS_WINDOWS // check git version for SChannel SSLBackend (Windows Only) bool schannelSslBackend = HostContext.GetService<IConfigurationStore>().GetAgentRuntimeOptions()?.GitUseSecureChannel ?? false; if (schannelSslBackend) { _gitCommandManager.EnsureGitVersion(_minGitVersionSupportSSLBackendOverride, throwOnNotMatch: true); } #endif } public override string GenerateAuthHeader(string username, string password) { // can't generate auth header for external git. throw new NotSupportedException(nameof(ExternalGitSourceProvider.GenerateAuthHeader)); } } public abstract class AuthenticatedGitSourceProvider : GitSourceProvider { public override bool GitUseAuthHeaderCmdlineArg { get { // v2.9 git exist use auth header. ArgUtil.NotNull(_gitCommandManager, nameof(_gitCommandManager)); return _gitCommandManager.EnsureGitVersion(_minGitVersionSupportAuthHeader, throwOnNotMatch: false); } } public override bool GitLfsUseAuthHeaderCmdlineArg { get { // v2.1 git-lfs exist use auth header. ArgUtil.NotNull(_gitCommandManager, nameof(_gitCommandManager)); return _gitCommandManager.EnsureGitLFSVersion(_minGitLfsVersionSupportAuthHeader, throwOnNotMatch: false); } } public override void RequirementCheck(IExecutionContext executionContext, ServiceEndpoint endpoint) { #if OS_WINDOWS // check git version for SChannel SSLBackend (Windows Only) bool schannelSslBackend = HostContext.GetService<IConfigurationStore>().GetAgentRuntimeOptions()?.GitUseSecureChannel ?? false; if (schannelSslBackend) { _gitCommandManager.EnsureGitVersion(_minGitVersionSupportSSLBackendOverride, throwOnNotMatch: true); } #endif } public override string GenerateAuthHeader(string username, string password) { // use basic auth header with username:password in base64encoding. string authHeader = $"{username ?? string.Empty}:{password ?? string.Empty}"; string base64encodedAuthHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(authHeader)); // add base64 encoding auth header into secretMasker. HostContext.SecretMasker.AddValue(base64encodedAuthHeader); return $"basic {base64encodedAuthHeader}"; } } public sealed class GitHubSourceProvider : AuthenticatedGitSourceProvider { public override string RepositoryType => TeamFoundation.DistributedTask.Pipelines.RepositoryTypes.GitHub; } public sealed class GitHubEnterpriseSourceProvider : AuthenticatedGitSourceProvider { public override string RepositoryType => TeamFoundation.DistributedTask.Pipelines.RepositoryTypes.GitHubEnterprise; } public sealed class BitbucketSourceProvider : AuthenticatedGitSourceProvider { public override string RepositoryType => TeamFoundation.DistributedTask.Pipelines.RepositoryTypes.Bitbucket; } public sealed class TfsGitSourceProvider : GitSourceProvider { public override string RepositoryType => TeamFoundation.DistributedTask.Pipelines.RepositoryTypes.Git; public override bool GitUseAuthHeaderCmdlineArg { get { // v2.9 git exist use auth header for tfsgit repository. ArgUtil.NotNull(_gitCommandManager, nameof(_gitCommandManager)); return _gitCommandManager.EnsureGitVersion(_minGitVersionSupportAuthHeader, throwOnNotMatch: false); } } public override bool GitLfsUseAuthHeaderCmdlineArg { get { // v2.1 git-lfs exist use auth header for github repository. ArgUtil.NotNull(_gitCommandManager, nameof(_gitCommandManager)); return _gitCommandManager.EnsureGitLFSVersion(_minGitLfsVersionSupportAuthHeader, throwOnNotMatch: false); } } // When the repository is a TfsGit, figure out the endpoint is hosted vsts git or on-prem tfs git // if repository is on-prem tfs git, make sure git version greater than 2.9 // we have to use http.extraheader option to provide auth header for on-prem tfs git public override void RequirementCheck(IExecutionContext executionContext, ServiceEndpoint endpoint) { ArgUtil.NotNull(_gitCommandManager, nameof(_gitCommandManager)); var selfManageGitCreds = executionContext.Variables.GetBoolean(Constants.Variables.System.SelfManageGitCreds) ?? false; if (selfManageGitCreds) { // Customer choose to own git creds by themselves, we don't have to worry about git version anymore. return; } // Since that variable is added around TFS 2015 Qu2. // Old TFS AT will not send this variable to build agent, and VSTS will always send it to build agent. bool? onPremTfsGit = true; string onPremTfsGitString; if (endpoint.Data.TryGetValue(EndpointData.OnPremTfsGit, out onPremTfsGitString)) { onPremTfsGit = StringUtil.ConvertToBoolean(onPremTfsGitString); } // ensure git version and git-lfs version for on-prem tfsgit. if (onPremTfsGit.Value) { _gitCommandManager.EnsureGitVersion(_minGitVersionSupportAuthHeader, throwOnNotMatch: true); bool gitLfsSupport = false; if (endpoint.Data.ContainsKey("GitLfsSupport")) { gitLfsSupport = StringUtil.ConvertToBoolean(endpoint.Data["GitLfsSupport"]); } // prefer feature variable over endpoint data gitLfsSupport = executionContext.Variables.GetBoolean(Constants.Variables.Features.GitLfsSupport) ?? gitLfsSupport; if (gitLfsSupport) { _gitCommandManager.EnsureGitLFSVersion(_minGitLfsVersionSupportAuthHeader, throwOnNotMatch: true); } } #if OS_WINDOWS // check git version for SChannel SSLBackend (Windows Only) bool schannelSslBackend = HostContext.GetService<IConfigurationStore>().GetAgentRuntimeOptions()?.GitUseSecureChannel ?? false; if (schannelSslBackend) { _gitCommandManager.EnsureGitVersion(_minGitVersionSupportSSLBackendOverride, throwOnNotMatch: true); } #endif } public override string GenerateAuthHeader(string username, string password) { // tfsgit use bearer auth header with JWToken from systemconnection. ArgUtil.NotNullOrEmpty(password, nameof(password)); return $"bearer {password}"; } } public abstract class GitSourceProvider : SourceProvider, ISourceProvider { // refs prefix // TODO: how to deal with limited refs? private const string _refsPrefix = "refs/heads/"; private const string _remoteRefsPrefix = "refs/remotes/origin/"; private const string _pullRefsPrefix = "refs/pull/"; private const string _remotePullRefsPrefix = "refs/remotes/pull/"; private readonly Dictionary<string, string> _configModifications = new Dictionary<string, string>(); private bool _selfManageGitCreds = false; private Uri _repositoryUrlWithCred = null; private Uri _proxyUrlWithCred = null; private string _proxyUrlWithCredString = null; private Uri _gitLfsUrlWithCred = null; private bool _useSelfSignedCACert = false; private bool _useClientCert = false; private string _clientCertPrivateKeyAskPassFile = null; protected IGitCommandManager _gitCommandManager; // min git version that support add extra auth header. protected Version _minGitVersionSupportAuthHeader = new Version(2, 9); #if OS_WINDOWS // min git version that support override sslBackend setting. protected Version _minGitVersionSupportSSLBackendOverride = new Version(2, 14, 2); #endif // min git-lfs version that support add extra auth header. protected Version _minGitLfsVersionSupportAuthHeader = new Version(2, 1); public abstract bool GitUseAuthHeaderCmdlineArg { get; } public abstract bool GitLfsUseAuthHeaderCmdlineArg { get; } public abstract void RequirementCheck(IExecutionContext executionContext, ServiceEndpoint endpoint); public abstract string GenerateAuthHeader(string username, string password); public async Task GetSourceAsync( IExecutionContext executionContext, ServiceEndpoint endpoint, CancellationToken cancellationToken) { Trace.Entering(); // Validate args. ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(endpoint, nameof(endpoint)); executionContext.Output($"Syncing repository: {endpoint.Name} ({RepositoryType})"); Uri repositoryUrl = endpoint.Url; if (!repositoryUrl.IsAbsoluteUri) { throw new InvalidOperationException("Repository url need to be an absolute uri."); } var agentCert = HostContext.GetService<IAgentCertificateManager>(); string targetPath = GetEndpointData(endpoint, Constants.EndpointData.SourcesDirectory); string sourceBranch = GetEndpointData(endpoint, Constants.EndpointData.SourceBranch); string sourceVersion = GetEndpointData(endpoint, Constants.EndpointData.SourceVersion); bool clean = false; if (endpoint.Data.ContainsKey(EndpointData.Clean)) { clean = StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.Clean]); } bool checkoutSubmodules = false; if (endpoint.Data.ContainsKey(EndpointData.CheckoutSubmodules)) { checkoutSubmodules = StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.CheckoutSubmodules]); } bool checkoutNestedSubmodules = false; if (endpoint.Data.ContainsKey(EndpointData.CheckoutNestedSubmodules)) { checkoutNestedSubmodules = StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.CheckoutNestedSubmodules]); } bool acceptUntrustedCerts = false; if (endpoint.Data.ContainsKey(EndpointData.AcceptUntrustedCertificates)) { acceptUntrustedCerts = StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.AcceptUntrustedCertificates]); } acceptUntrustedCerts = acceptUntrustedCerts || agentCert.SkipServerCertificateValidation; int fetchDepth = 0; if (endpoint.Data.ContainsKey(EndpointData.FetchDepth) && (!int.TryParse(endpoint.Data[EndpointData.FetchDepth], out fetchDepth) || fetchDepth < 0)) { fetchDepth = 0; } // prefer feature variable over endpoint data fetchDepth = executionContext.Variables.GetInt(Constants.Variables.Features.GitShallowDepth) ?? fetchDepth; bool gitLfsSupport = false; if (endpoint.Data.ContainsKey(EndpointData.GitLfsSupport)) { gitLfsSupport = StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.GitLfsSupport]); } // prefer feature variable over endpoint data gitLfsSupport = executionContext.Variables.GetBoolean(Constants.Variables.Features.GitLfsSupport) ?? gitLfsSupport; bool exposeCred = executionContext.Variables.GetBoolean(Constants.Variables.System.EnableAccessToken) ?? false; Trace.Info($"Repository url={repositoryUrl}"); Trace.Info($"targetPath={targetPath}"); Trace.Info($"sourceBranch={sourceBranch}"); Trace.Info($"sourceVersion={sourceVersion}"); Trace.Info($"clean={clean}"); Trace.Info($"checkoutSubmodules={checkoutSubmodules}"); Trace.Info($"checkoutNestedSubmodules={checkoutNestedSubmodules}"); Trace.Info($"exposeCred={exposeCred}"); Trace.Info($"fetchDepth={fetchDepth}"); Trace.Info($"gitLfsSupport={gitLfsSupport}"); Trace.Info($"acceptUntrustedCerts={acceptUntrustedCerts}"); bool preferGitFromPath; #if OS_WINDOWS bool schannelSslBackend = HostContext.GetService<IConfigurationStore>().GetAgentRuntimeOptions()?.GitUseSecureChannel ?? false; Trace.Info($"schannelSslBackend={schannelSslBackend}"); // Determine which git will be use // On windows, we prefer the built-in portable git within the agent's externals folder, // set system.prefergitfrompath=true can change the behavior, agent will find git.exe from %PATH% var definitionSetting = executionContext.Variables.GetBoolean(Constants.Variables.System.PreferGitFromPath); if (definitionSetting != null) { preferGitFromPath = definitionSetting.Value; } else { bool.TryParse(Environment.GetEnvironmentVariable(Constants.Variables.System.PreferGitFromPath), out preferGitFromPath); } #else // On Linux, we will always use git find in %PATH% regardless of system.prefergitfrompath preferGitFromPath = true; #endif // Determine do we need to provide creds to git operation _selfManageGitCreds = executionContext.Variables.GetBoolean(Constants.Variables.System.SelfManageGitCreds) ?? false; if (_selfManageGitCreds) { // Customer choose to own git creds by themselves. executionContext.Output(StringUtil.Loc("SelfManageGitCreds")); } // Initialize git command manager _gitCommandManager = HostContext.GetService<IGitCommandManager>(); await _gitCommandManager.LoadGitExecutionInfo(executionContext, useBuiltInGit: !preferGitFromPath); // Make sure the build machine met all requirements for the git repository // For now, the requirement we have are: // 1. git version greater than 2.9 and git-lfs version greater than 2.1 for on-prem tfsgit // 2. git version greater than 2.14.2 if use SChannel for SSL backend (Windows only) RequirementCheck(executionContext, endpoint); // retrieve credential from endpoint. string username = string.Empty; string password = string.Empty; if (!_selfManageGitCreds && endpoint.Authorization != null) { switch (endpoint.Authorization.Scheme) { case EndpointAuthorizationSchemes.OAuth: username = EndpointAuthorizationSchemes.OAuth; if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out password)) { password = string.Empty; } break; case EndpointAuthorizationSchemes.PersonalAccessToken: username = EndpointAuthorizationSchemes.PersonalAccessToken; if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out password)) { password = string.Empty; } break; case EndpointAuthorizationSchemes.Token: username = "x-access-token"; if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out password)) { username = EndpointAuthorizationSchemes.Token; if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.ApiToken, out password)) { password = string.Empty; } } break; case EndpointAuthorizationSchemes.UsernamePassword: if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out username)) { // leave the username as empty, the username might in the url, like: http://username@repository.git username = string.Empty; } if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out password)) { // we have username, but no password password = string.Empty; } break; default: executionContext.Warning($"Unsupport endpoint authorization schemes: {endpoint.Authorization.Scheme}"); break; } } // prepare credentail embedded urls _repositoryUrlWithCred = UrlUtil.GetCredentialEmbeddedUrl(repositoryUrl, username, password); var agentProxy = HostContext.GetService<IVstsAgentWebProxy>(); if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.WebProxy.IsBypassed(repositoryUrl)) { _proxyUrlWithCred = UrlUtil.GetCredentialEmbeddedUrl(new Uri(executionContext.Variables.Agent_ProxyUrl), executionContext.Variables.Agent_ProxyUsername, executionContext.Variables.Agent_ProxyPassword); // uri.absoluteuri will not contains port info if the scheme is http/https and the port is 80/443 // however, git.exe always require you provide port info, if nothing passed in, it will use 1080 as default // as result, we need prefer the uri.originalstring when it's different than uri.absoluteuri. if (string.Equals(_proxyUrlWithCred.AbsoluteUri, _proxyUrlWithCred.OriginalString, StringComparison.OrdinalIgnoreCase)) { _proxyUrlWithCredString = _proxyUrlWithCred.AbsoluteUri; } else { _proxyUrlWithCredString = _proxyUrlWithCred.OriginalString; } } // prepare askpass for client cert private key var configUrl = new Uri(HostContext.GetService<IConfigurationStore>().GetSettings().ServerUrl); if (Uri.Compare(repositoryUrl, configUrl, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0) { if (!string.IsNullOrEmpty(agentCert.CACertificateFile)) { _useSelfSignedCACert = true; } if (!string.IsNullOrEmpty(agentCert.ClientCertificateFile) && !string.IsNullOrEmpty(agentCert.ClientCertificatePrivateKeyFile)) { _useClientCert = true; // prepare askpass for client cert password if (!string.IsNullOrEmpty(agentCert.ClientCertificatePassword)) { _clientCertPrivateKeyAskPassFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Temp), $"{Guid.NewGuid()}.sh"); List<string> askPass = new List<string>(); askPass.Add("#!/bin/sh"); askPass.Add($"echo \"{agentCert.ClientCertificatePassword}\""); File.WriteAllLines(_clientCertPrivateKeyAskPassFile, askPass); #if !OS_WINDOWS string toolPath = WhichUtil.Which("chmod", true); string argLine = $"775 {_clientCertPrivateKeyAskPassFile}"; executionContext.Command($"chmod {argLine}"); var processInvoker = HostContext.CreateService<IProcessInvoker>(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { if (!string.IsNullOrEmpty(args.Data)) { executionContext.Output(args.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { if (!string.IsNullOrEmpty(args.Data)) { executionContext.Output(args.Data); } }; await processInvoker.ExecuteAsync(HostContext.GetDirectory(WellKnownDirectory.Work), toolPath, argLine, null, true, CancellationToken.None); #endif } } } if (gitLfsSupport) { // Construct git-lfs url UriBuilder gitLfsUrl = new UriBuilder(_repositoryUrlWithCred); if (gitLfsUrl.Path.EndsWith(".git")) { gitLfsUrl.Path = gitLfsUrl.Path + "/info/lfs"; } else { gitLfsUrl.Path = gitLfsUrl.Path + ".git/info/lfs"; } _gitLfsUrlWithCred = gitLfsUrl.Uri; } // Check the current contents of the root folder to see if there is already a repo // If there is a repo, see if it matches the one we are expecting to be there based on the remote fetch url // if the repo is not what we expect, remove the folder if (!await IsRepositoryOriginUrlMatch(executionContext, targetPath, repositoryUrl)) { // Delete source folder IOUtil.DeleteDirectory(targetPath, cancellationToken); } else { // delete the index.lock file left by previous canceled build or any operation cause git.exe crash last time. string lockFile = Path.Combine(targetPath, ".git\\index.lock"); if (File.Exists(lockFile)) { try { File.Delete(lockFile); } catch (Exception ex) { executionContext.Debug($"Unable to delete the index.lock file: {lockFile}"); executionContext.Debug(ex.ToString()); } } // delete the shallow.lock file left by previous canceled build or any operation cause git.exe crash last time. string shallowLockFile = Path.Combine(targetPath, ".git\\shallow.lock"); if (File.Exists(shallowLockFile)) { try { File.Delete(shallowLockFile); } catch (Exception ex) { executionContext.Debug($"Unable to delete the shallow.lock file: {shallowLockFile}"); executionContext.Debug(ex.ToString()); } } // When repo.clean is selected for a git repo, execute git clean -ffdx and git reset --hard HEAD on the current repo. // This will help us save the time to reclone the entire repo. // If any git commands exit with non-zero return code or any exception happened during git.exe invoke, fall back to delete the repo folder. if (clean) { Boolean softCleanSucceed = true; // git clean -ffdx int exitCode_clean = await _gitCommandManager.GitClean(executionContext, targetPath); if (exitCode_clean != 0) { executionContext.Debug($"'git clean -ffdx' failed with exit code {exitCode_clean}, this normally caused by:\n 1) Path too long\n 2) Permission issue\n 3) File in use\nFor futher investigation, manually run 'git clean -ffdx' on repo root: {targetPath} after each build."); softCleanSucceed = false; } // git reset --hard HEAD if (softCleanSucceed) { int exitCode_reset = await _gitCommandManager.GitReset(executionContext, targetPath); if (exitCode_reset != 0) { executionContext.Debug($"'git reset --hard HEAD' failed with exit code {exitCode_reset}\nFor futher investigation, manually run 'git reset --hard HEAD' on repo root: {targetPath} after each build."); softCleanSucceed = false; } } // git clean -ffdx and git reset --hard HEAD for each submodule if (checkoutSubmodules) { if (softCleanSucceed) { int exitCode_submoduleclean = await _gitCommandManager.GitSubmoduleClean(executionContext, targetPath); if (exitCode_submoduleclean != 0) { executionContext.Debug($"'git submodule foreach git clean -ffdx' failed with exit code {exitCode_submoduleclean}\nFor futher investigation, manually run 'git submodule foreach git clean -ffdx' on repo root: {targetPath} after each build."); softCleanSucceed = false; } } if (softCleanSucceed) { int exitCode_submodulereset = await _gitCommandManager.GitSubmoduleReset(executionContext, targetPath); if (exitCode_submodulereset != 0) { executionContext.Debug($"'git submodule foreach git reset --hard HEAD' failed with exit code {exitCode_submodulereset}\nFor futher investigation, manually run 'git submodule foreach git reset --hard HEAD' on repo root: {targetPath} after each build."); softCleanSucceed = false; } } } if (!softCleanSucceed) { //fall back executionContext.Warning("Unable to run \"git clean -ffdx\" and \"git reset --hard HEAD\" successfully, delete source folder instead."); IOUtil.DeleteDirectory(targetPath, cancellationToken); } } } // if the folder is missing, create it if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } // if the folder contains a .git folder, it means the folder contains a git repo that matches the remote url and in a clean state. // we will run git fetch to update the repo. if (!Directory.Exists(Path.Combine(targetPath, ".git"))) { // init git repository int exitCode_init = await _gitCommandManager.GitInit(executionContext, targetPath); if (exitCode_init != 0) { throw new InvalidOperationException($"Unable to use git.exe init repository under {targetPath}, 'git init' failed with exit code: {exitCode_init}"); } int exitCode_addremote = await _gitCommandManager.GitRemoteAdd(executionContext, targetPath, "origin", repositoryUrl.AbsoluteUri); if (exitCode_addremote != 0) { throw new InvalidOperationException($"Unable to use git.exe add remote 'origin', 'git remote add' failed with exit code: {exitCode_addremote}"); } } cancellationToken.ThrowIfCancellationRequested(); executionContext.Progress(0, "Starting fetch..."); // disable git auto gc int exitCode_disableGC = await _gitCommandManager.GitDisableAutoGC(executionContext, targetPath); if (exitCode_disableGC != 0) { executionContext.Warning("Unable turn off git auto garbage collection, git fetch operation may trigger auto garbage collection which will affect the performance of fetching."); } // always remove any possible left extraheader setting from git config. if (await _gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader")) { executionContext.Debug("Remove any extraheader setting from git config."); await RemoveGitConfig(executionContext, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader", string.Empty); } // always remove any possible left proxy setting from git config, the proxy setting may contains credential if (await _gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.proxy")) { executionContext.Debug("Remove any proxy setting from git config."); await RemoveGitConfig(executionContext, targetPath, $"http.proxy", string.Empty); } List<string> additionalFetchArgs = new List<string>(); List<string> additionalLfsFetchArgs = new List<string>(); if (!_selfManageGitCreds) { // v2.9 git support provide auth header as cmdline arg. // as long 2.9 git exist, VSTS repo, TFS repo and Github repo will use this to handle auth challenge. if (GitUseAuthHeaderCmdlineArg) { additionalFetchArgs.Add($"-c http.extraheader=\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\""); } else { // Otherwise, inject credential into fetch/push url // inject credential into fetch url executionContext.Debug("Inject credential into git remote url."); ArgUtil.NotNull(_repositoryUrlWithCred, nameof(_repositoryUrlWithCred)); // inject credential into fetch url executionContext.Debug("Inject credential into git remote fetch url."); int exitCode_seturl = await _gitCommandManager.GitRemoteSetUrl(executionContext, targetPath, "origin", _repositoryUrlWithCred.AbsoluteUri); if (exitCode_seturl != 0) { throw new InvalidOperationException($"Unable to use git.exe inject credential to git remote fetch url, 'git remote set-url' failed with exit code: {exitCode_seturl}"); } // inject credential into push url executionContext.Debug("Inject credential into git remote push url."); exitCode_seturl = await _gitCommandManager.GitRemoteSetPushUrl(executionContext, targetPath, "origin", _repositoryUrlWithCred.AbsoluteUri); if (exitCode_seturl != 0) { throw new InvalidOperationException($"Unable to use git.exe inject credential to git remote push url, 'git remote set-url --push' failed with exit code: {exitCode_seturl}"); } } // Prepare proxy config for fetch. if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.WebProxy.IsBypassed(repositoryUrl)) { executionContext.Debug($"Config proxy server '{executionContext.Variables.Agent_ProxyUrl}' for git fetch."); ArgUtil.NotNullOrEmpty(_proxyUrlWithCredString, nameof(_proxyUrlWithCredString)); additionalFetchArgs.Add($"-c http.proxy=\"{_proxyUrlWithCredString}\""); additionalLfsFetchArgs.Add($"-c http.proxy=\"{_proxyUrlWithCredString}\""); } // Prepare ignore ssl cert error config for fetch. if (acceptUntrustedCerts) { additionalFetchArgs.Add($"-c http.sslVerify=false"); additionalLfsFetchArgs.Add($"-c http.sslVerify=false"); } // Prepare self-signed CA cert config for fetch from TFS. if (_useSelfSignedCACert) { executionContext.Debug($"Use self-signed certificate '{agentCert.CACertificateFile}' for git fetch."); additionalFetchArgs.Add($"-c http.sslcainfo=\"{agentCert.CACertificateFile}\""); additionalLfsFetchArgs.Add($"-c http.sslcainfo=\"{agentCert.CACertificateFile}\""); } // Prepare client cert config for fetch from TFS. if (_useClientCert) { executionContext.Debug($"Use client certificate '{agentCert.ClientCertificateFile}' for git fetch."); if (!string.IsNullOrEmpty(_clientCertPrivateKeyAskPassFile)) { additionalFetchArgs.Add($"-c http.sslcert=\"{agentCert.ClientCertificateFile}\" -c http.sslkey=\"{agentCert.ClientCertificatePrivateKeyFile}\" -c http.sslCertPasswordProtected=true -c core.askpass=\"{_clientCertPrivateKeyAskPassFile}\""); additionalLfsFetchArgs.Add($"-c http.sslcert=\"{agentCert.ClientCertificateFile}\" -c http.sslkey=\"{agentCert.ClientCertificatePrivateKeyFile}\" -c http.sslCertPasswordProtected=true -c core.askpass=\"{_clientCertPrivateKeyAskPassFile}\""); } else { additionalFetchArgs.Add($"-c http.sslcert=\"{agentCert.ClientCertificateFile}\" -c http.sslkey=\"{agentCert.ClientCertificatePrivateKeyFile}\""); additionalLfsFetchArgs.Add($"-c http.sslcert=\"{agentCert.ClientCertificateFile}\" -c http.sslkey=\"{agentCert.ClientCertificatePrivateKeyFile}\""); } } #if OS_WINDOWS if (schannelSslBackend) { executionContext.Debug("Use SChannel SslBackend for git fetch."); additionalFetchArgs.Add("-c http.sslbackend=\"schannel\""); additionalLfsFetchArgs.Add("-c http.sslbackend=\"schannel\""); } #endif // Prepare gitlfs url for fetch and checkout if (gitLfsSupport) { // Initialize git lfs by execute 'git lfs install' executionContext.Debug("Setup the local Git hooks for Git LFS."); int exitCode_lfsInstall = await _gitCommandManager.GitLFSInstall(executionContext, targetPath); if (exitCode_lfsInstall != 0) { throw new InvalidOperationException($"Git-lfs installation failed with exit code: {exitCode_lfsInstall}"); } if (GitLfsUseAuthHeaderCmdlineArg) { string authorityUrl = repositoryUrl.AbsoluteUri.Replace(repositoryUrl.PathAndQuery, string.Empty); additionalLfsFetchArgs.Add($"-c http.{authorityUrl}.extraheader=\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\""); } else { // Inject credential into lfs fetch/push url executionContext.Debug("Inject credential into git-lfs remote url."); ArgUtil.NotNull(_gitLfsUrlWithCred, nameof(_gitLfsUrlWithCred)); // inject credential into fetch url executionContext.Debug("Inject credential into git-lfs remote fetch url."); _configModifications["remote.origin.lfsurl"] = _gitLfsUrlWithCred.AbsoluteUri; int exitCode_configlfsurl = await _gitCommandManager.GitConfig(executionContext, targetPath, "remote.origin.lfsurl", _gitLfsUrlWithCred.AbsoluteUri); if (exitCode_configlfsurl != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_configlfsurl}"); } // inject credential into push url executionContext.Debug("Inject credential into git-lfs remote push url."); _configModifications["remote.origin.lfspushurl"] = _gitLfsUrlWithCred.AbsoluteUri; int exitCode_configlfspushurl = await _gitCommandManager.GitConfig(executionContext, targetPath, "remote.origin.lfspushurl", _gitLfsUrlWithCred.AbsoluteUri); if (exitCode_configlfspushurl != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_configlfspushurl}"); } } } } // If this is a build for a pull request, then include // the pull request reference as an additional ref. List<string> additionalFetchSpecs = new List<string>(); if (IsPullRequest(sourceBranch)) { additionalFetchSpecs.Add("+refs/heads/*:refs/remotes/origin/*"); additionalFetchSpecs.Add(StringUtil.Format("+{0}:{1}", sourceBranch, GetRemoteRefName(sourceBranch))); } int exitCode_fetch = await _gitCommandManager.GitFetch(executionContext, targetPath, "origin", fetchDepth, additionalFetchSpecs, string.Join(" ", additionalFetchArgs), cancellationToken); if (exitCode_fetch != 0) { throw new InvalidOperationException($"Git fetch failed with exit code: {exitCode_fetch}"); } // Checkout // sourceToBuild is used for checkout // if sourceBranch is a PR branch or sourceVersion is null, make sure branch name is a remote branch. we need checkout to detached head. // (change refs/heads to refs/remotes/origin, refs/pull to refs/remotes/pull, or leave it as it when the branch name doesn't contain refs/...) // if sourceVersion provide, just use that for checkout, since when you checkout a commit, it will end up in detached head. cancellationToken.ThrowIfCancellationRequested(); executionContext.Progress(80, "Starting checkout..."); string sourcesToBuild; if (IsPullRequest(sourceBranch) || string.IsNullOrEmpty(sourceVersion)) { sourcesToBuild = GetRemoteRefName(sourceBranch); } else { sourcesToBuild = sourceVersion; } // fetch lfs object upfront, this will avoid fetch lfs object during checkout which cause checkout taking forever // since checkout will fetch lfs object 1 at a time, while git lfs fetch will fetch lfs object in parallel. if (gitLfsSupport) { int exitCode_lfsFetch = await _gitCommandManager.GitLFSFetch(executionContext, targetPath, "origin", sourcesToBuild, string.Join(" ", additionalLfsFetchArgs), cancellationToken); if (exitCode_lfsFetch != 0) { // git lfs fetch failed, get lfs log, the log is critical for debug. int exitCode_lfsLogs = await _gitCommandManager.GitLFSLogs(executionContext, targetPath); throw new InvalidOperationException($"Git lfs fetch failed with exit code: {exitCode_lfsFetch}. Git lfs logs returned with exit code: {exitCode_lfsLogs}."); } } // Finally, checkout the sourcesToBuild (if we didn't find a valid git object this will throw) int exitCode_checkout = await _gitCommandManager.GitCheckout(executionContext, targetPath, sourcesToBuild, cancellationToken); if (exitCode_checkout != 0) { // local repository is shallow repository, checkout may fail due to lack of commits history. // this will happen when the checkout commit is older than tip -> fetchDepth if (fetchDepth > 0) { executionContext.Warning(StringUtil.Loc("ShallowCheckoutFail", fetchDepth, sourcesToBuild)); } throw new InvalidOperationException($"Git checkout failed with exit code: {exitCode_checkout}"); } // Submodule update if (checkoutSubmodules) { cancellationToken.ThrowIfCancellationRequested(); executionContext.Progress(90, "Updating submodules..."); int exitCode_submoduleSync = await _gitCommandManager.GitSubmoduleSync(executionContext, targetPath, checkoutNestedSubmodules, cancellationToken); if (exitCode_submoduleSync != 0) { throw new InvalidOperationException($"Git submodule sync failed with exit code: {exitCode_submoduleSync}"); } List<string> additionalSubmoduleUpdateArgs = new List<string>(); if (!_selfManageGitCreds) { if (GitUseAuthHeaderCmdlineArg) { string authorityUrl = repositoryUrl.AbsoluteUri.Replace(repositoryUrl.PathAndQuery, string.Empty); additionalSubmoduleUpdateArgs.Add($"-c http.{authorityUrl}.extraheader=\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\""); } // Prepare proxy config for submodule update. if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.WebProxy.IsBypassed(repositoryUrl)) { executionContext.Debug($"Config proxy server '{executionContext.Variables.Agent_ProxyUrl}' for git submodule update."); ArgUtil.NotNullOrEmpty(_proxyUrlWithCredString, nameof(_proxyUrlWithCredString)); additionalSubmoduleUpdateArgs.Add($"-c http.proxy=\"{_proxyUrlWithCredString}\""); } // Prepare ignore ssl cert error config for fetch. if (acceptUntrustedCerts) { additionalSubmoduleUpdateArgs.Add($"-c http.sslVerify=false"); } // Prepare self-signed CA cert config for submodule update. if (_useSelfSignedCACert) { executionContext.Debug($"Use self-signed CA certificate '{agentCert.CACertificateFile}' for git submodule update."); string authorityUrl = repositoryUrl.AbsoluteUri.Replace(repositoryUrl.PathAndQuery, string.Empty); additionalSubmoduleUpdateArgs.Add($"-c http.{authorityUrl}.sslcainfo=\"{agentCert.CACertificateFile}\""); } // Prepare client cert config for submodule update. if (_useClientCert) { executionContext.Debug($"Use client certificate '{agentCert.ClientCertificateFile}' for git submodule update."); string authorityUrl = repositoryUrl.AbsoluteUri.Replace(repositoryUrl.PathAndQuery, string.Empty); if (!string.IsNullOrEmpty(_clientCertPrivateKeyAskPassFile)) { additionalSubmoduleUpdateArgs.Add($"-c http.{authorityUrl}.sslcert=\"{agentCert.ClientCertificateFile}\" -c http.{authorityUrl}.sslkey=\"{agentCert.ClientCertificatePrivateKeyFile}\" -c http.{authorityUrl}.sslCertPasswordProtected=true -c core.askpass=\"{_clientCertPrivateKeyAskPassFile}\""); } else { additionalSubmoduleUpdateArgs.Add($"-c http.{authorityUrl}.sslcert=\"{agentCert.ClientCertificateFile}\" -c http.{authorityUrl}.sslkey=\"{agentCert.ClientCertificatePrivateKeyFile}\""); } } #if OS_WINDOWS if (schannelSslBackend) { executionContext.Debug("Use SChannel SslBackend for git submodule update."); additionalSubmoduleUpdateArgs.Add("-c http.sslbackend=\"schannel\""); } #endif } int exitCode_submoduleUpdate = await _gitCommandManager.GitSubmoduleUpdate(executionContext, targetPath, fetchDepth, string.Join(" ", additionalSubmoduleUpdateArgs), checkoutNestedSubmodules, cancellationToken); if (exitCode_submoduleUpdate != 0) { throw new InvalidOperationException($"Git submodule update failed with exit code: {exitCode_submoduleUpdate}"); } } // handle expose creds, related to 'Allow Scripts to Access OAuth Token' option if (!_selfManageGitCreds) { if (GitUseAuthHeaderCmdlineArg && exposeCred) { string configKey = $"http.{repositoryUrl.AbsoluteUri}.extraheader"; string configValue = $"\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\""; _configModifications[configKey] = configValue.Trim('\"'); int exitCode_config = await _gitCommandManager.GitConfig(executionContext, targetPath, configKey, configValue); if (exitCode_config != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_config}"); } } if (!GitUseAuthHeaderCmdlineArg && !exposeCred) { // remove cached credential from origin's fetch/push url. await RemoveCachedCredential(executionContext, targetPath, repositoryUrl, "origin"); } if (exposeCred) { // save proxy setting to git config. if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.WebProxy.IsBypassed(repositoryUrl)) { executionContext.Debug($"Save proxy config for proxy server '{executionContext.Variables.Agent_ProxyUrl}' into git config."); ArgUtil.NotNullOrEmpty(_proxyUrlWithCredString, nameof(_proxyUrlWithCredString)); string proxyConfigKey = "http.proxy"; string proxyConfigValue = $"\"{_proxyUrlWithCredString}\""; _configModifications[proxyConfigKey] = proxyConfigValue.Trim('\"'); int exitCode_proxyconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, proxyConfigKey, proxyConfigValue); if (exitCode_proxyconfig != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_proxyconfig}"); } } // save ignore ssl cert error setting to git config. if (acceptUntrustedCerts) { executionContext.Debug($"Save ignore ssl cert error config into git config."); string sslVerifyConfigKey = "http.sslVerify"; string sslVerifyConfigValue = "\"false\""; _configModifications[sslVerifyConfigKey] = sslVerifyConfigValue.Trim('\"'); int exitCode_sslconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, sslVerifyConfigKey, sslVerifyConfigValue); if (exitCode_sslconfig != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_sslconfig}"); } } // save CA cert setting to git config. if (_useSelfSignedCACert) { executionContext.Debug($"Save CA cert config into git config."); string sslCaInfoConfigKey = "http.sslcainfo"; string sslCaInfoConfigValue = $"\"{agentCert.CACertificateFile}\""; _configModifications[sslCaInfoConfigKey] = sslCaInfoConfigValue.Trim('\"'); int exitCode_sslconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, sslCaInfoConfigKey, sslCaInfoConfigValue); if (exitCode_sslconfig != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_sslconfig}"); } } // save client cert setting to git config. if (_useClientCert) { executionContext.Debug($"Save client cert config into git config."); string sslCertConfigKey = "http.sslcert"; string sslCertConfigValue = $"\"{agentCert.ClientCertificateFile}\""; string sslKeyConfigKey = "http.sslkey"; string sslKeyConfigValue = $"\"{agentCert.CACertificateFile}\""; _configModifications[sslCertConfigKey] = sslCertConfigValue.Trim('\"'); _configModifications[sslKeyConfigKey] = sslKeyConfigValue.Trim('\"'); int exitCode_sslconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, sslCertConfigKey, sslCertConfigValue); if (exitCode_sslconfig != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_sslconfig}"); } exitCode_sslconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, sslKeyConfigKey, sslKeyConfigValue); if (exitCode_sslconfig != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_sslconfig}"); } // the client private key has a password if (!string.IsNullOrEmpty(_clientCertPrivateKeyAskPassFile)) { string sslCertPasswordProtectedConfigKey = "http.sslcertpasswordprotected"; string sslCertPasswordProtectedConfigValue = "true"; string askPassConfigKey = "core.askpass"; string askPassConfigValue = $"\"{_clientCertPrivateKeyAskPassFile}\""; _configModifications[sslCertPasswordProtectedConfigKey] = sslCertPasswordProtectedConfigValue.Trim('\"'); _configModifications[askPassConfigKey] = askPassConfigValue.Trim('\"'); exitCode_sslconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, sslCertPasswordProtectedConfigKey, sslCertPasswordProtectedConfigValue); if (exitCode_sslconfig != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_sslconfig}"); } exitCode_sslconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, askPassConfigKey, askPassConfigValue); if (exitCode_sslconfig != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_sslconfig}"); } } } } if (gitLfsSupport) { if (GitLfsUseAuthHeaderCmdlineArg && exposeCred) { string configKey = $"http.{repositoryUrl.AbsoluteUri}.extraheader"; string configValue = $"\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\""; _configModifications[configKey] = configValue.Trim('\"'); int exitCode_config = await _gitCommandManager.GitConfig(executionContext, targetPath, configKey, configValue); if (exitCode_config != 0) { throw new InvalidOperationException($"Git config failed with exit code: {exitCode_config}"); } } if (!GitLfsUseAuthHeaderCmdlineArg && !exposeCred) { // remove cached credential from origin's lfs fetch/push url. executionContext.Debug("Remove git-lfs fetch and push url setting from git config."); await RemoveGitConfig(executionContext, targetPath, "remote.origin.lfsurl", _gitLfsUrlWithCred.AbsoluteUri); _configModifications.Remove("remote.origin.lfsurl"); await RemoveGitConfig(executionContext, targetPath, "remote.origin.lfspushurl", _gitLfsUrlWithCred.AbsoluteUri); _configModifications.Remove("remote.origin.lfspushurl"); } } if (_useClientCert && !string.IsNullOrEmpty(_clientCertPrivateKeyAskPassFile) && !exposeCred) { executionContext.Debug("Remove git.sslkey askpass file."); IOUtil.DeleteFile(_clientCertPrivateKeyAskPassFile); } } } public async Task PostJobCleanupAsync(IExecutionContext executionContext, ServiceEndpoint endpoint) { Trace.Entering(); ArgUtil.NotNull(endpoint, nameof(endpoint)); executionContext.Output($"Cleaning any cached credential from repository: {endpoint.Name} (Git)"); Uri repositoryUrl = endpoint.Url; string targetPath = GetEndpointData(endpoint, Constants.EndpointData.SourcesDirectory); executionContext.Debug($"Repository url={repositoryUrl}"); executionContext.Debug($"targetPath={targetPath}"); if (!_selfManageGitCreds) { executionContext.Debug("Remove any extraheader, proxy and client cert setting from git config."); foreach (var config in _configModifications) { await RemoveGitConfig(executionContext, targetPath, config.Key, config.Value); } await RemoveCachedCredential(executionContext, targetPath, repositoryUrl, "origin"); } // delete client cert askpass file. if (_useClientCert && !string.IsNullOrEmpty(_clientCertPrivateKeyAskPassFile)) { IOUtil.DeleteFile(_clientCertPrivateKeyAskPassFile); } } public override async Task RunMaintenanceOperations(IExecutionContext executionContext, string repositoryPath) { Trace.Entering(); // Validate args. ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNullOrEmpty(repositoryPath, nameof(repositoryPath)); executionContext.Output($"Run maintenance operation on repository: {repositoryPath}"); // Initialize git command manager _gitCommandManager = HostContext.GetService<IGitCommandManager>(); #if OS_WINDOWS // On Windows, we will always find git from externals await _gitCommandManager.LoadGitExecutionInfo(executionContext, useBuiltInGit: true); #else // On linux/OSX, we will always find git from %PATH% await _gitCommandManager.LoadGitExecutionInfo(executionContext, useBuiltInGit: false); #endif // if the folder is missing, skip it if (!Directory.Exists(repositoryPath) || !Directory.Exists(Path.Combine(repositoryPath, ".git"))) { return; } // add a timer to track how much time we used for git-repack Stopwatch timer = Stopwatch.StartNew(); try { // git count-objects before git repack executionContext.Output("Repository status before executing 'git repack'"); int exitCode_countobjectsbefore = await _gitCommandManager.GitCountObjects(executionContext, repositoryPath); if (exitCode_countobjectsbefore != 0) { throw new InvalidOperationException($"Git count-objects failed with exit code: {exitCode_countobjectsbefore}"); } // git repack int exitCode_repack = await _gitCommandManager.GitRepack(executionContext, repositoryPath); if (exitCode_repack != 0) { throw new InvalidOperationException($"Git repack failed with exit code: {exitCode_repack}"); } // git prune int exitCode_prune = await _gitCommandManager.GitPrune(executionContext, repositoryPath); if (exitCode_prune != 0) { throw new InvalidOperationException($"Git prune failed with exit code: {exitCode_prune}"); } // git count-objects after git repack executionContext.Output("Repository status after executing 'git repack'"); int exitCode_countobjectsafter = await _gitCommandManager.GitCountObjects(executionContext, repositoryPath); if (exitCode_countobjectsafter != 0) { throw new InvalidOperationException($"Git count-objects failed with exit code: {exitCode_countobjectsafter}"); } } finally { timer.Stop(); executionContext.Output($"Total time for executing maintenance for repository '{repositoryPath}': {timer.Elapsed.TotalSeconds} seconds."); } } public override void SetVariablesInEndpoint(IExecutionContext executionContext, ServiceEndpoint endpoint) { base.SetVariablesInEndpoint(executionContext, endpoint); endpoint.Data.Add(Constants.EndpointData.SourceBranch, executionContext.Variables.Build_SourceBranch); } private async Task<bool> IsRepositoryOriginUrlMatch(IExecutionContext context, string repositoryPath, Uri expectedRepositoryOriginUrl) { context.Debug($"Checking if the repo on {repositoryPath} matches the expected repository origin URL. expected Url: {expectedRepositoryOriginUrl.AbsoluteUri}"); if (!Directory.Exists(Path.Combine(repositoryPath, ".git"))) { // There is no repo directory context.Debug($"Repository is not found since '.git' directory does not exist under. {repositoryPath}"); return false; } Uri remoteUrl; remoteUrl = await _gitCommandManager.GitGetFetchUrl(context, repositoryPath); if (remoteUrl == null) { // origin fetch url not found. context.Debug("Repository remote origin fetch url is empty."); return false; } context.Debug($"Repository remote origin fetch url is {remoteUrl}"); // compare the url passed in with the remote url found if (expectedRepositoryOriginUrl.Equals(remoteUrl)) { context.Debug("URLs match."); return true; } else { context.Debug($"The remote.origin.url of the repository under root folder '{repositoryPath}' doesn't matches source repository url."); return false; } } private async Task RemoveGitConfig(IExecutionContext executionContext, string targetPath, string configKey, string configValue) { int exitCode_configUnset = await _gitCommandManager.GitConfigUnset(executionContext, targetPath, configKey); if (exitCode_configUnset != 0) { // if unable to use git.exe unset http.extraheader, http.proxy or core.askpass, modify git config file on disk. make sure we don't left credential. if (!string.IsNullOrEmpty(configValue)) { executionContext.Warning(StringUtil.Loc("AttemptRemoveCredFromConfig")); string gitConfig = Path.Combine(targetPath, ".git/config"); if (File.Exists(gitConfig)) { string gitConfigContent = File.ReadAllText(Path.Combine(targetPath, ".git", "config")); if (gitConfigContent.Contains(configKey)) { string setting = $"extraheader = {configValue}"; gitConfigContent = Regex.Replace(gitConfigContent, setting, string.Empty, RegexOptions.IgnoreCase); setting = $"proxy = {configValue}"; gitConfigContent = Regex.Replace(gitConfigContent, setting, string.Empty, RegexOptions.IgnoreCase); setting = $"askpass = {configValue}"; gitConfigContent = Regex.Replace(gitConfigContent, setting, string.Empty, RegexOptions.IgnoreCase); File.WriteAllText(gitConfig, gitConfigContent); } } } else { executionContext.Warning(StringUtil.Loc("FailToRemoveGitConfig", configKey, configKey, targetPath)); } } } private async Task RemoveCachedCredential(IExecutionContext context, string repositoryPath, Uri repositoryUrl, string remoteName) { // there is nothing cached in repository Url. if (_repositoryUrlWithCred == null) { return; } //remove credential from fetch url context.Debug("Remove injected credential from git remote fetch url."); int exitCode_seturl = await _gitCommandManager.GitRemoteSetUrl(context, repositoryPath, remoteName, repositoryUrl.AbsoluteUri); context.Debug("Remove injected credential from git remote push url."); int exitCode_setpushurl = await _gitCommandManager.GitRemoteSetPushUrl(context, repositoryPath, remoteName, repositoryUrl.AbsoluteUri); if (exitCode_seturl != 0 || exitCode_setpushurl != 0) { // if unable to use git.exe set fetch url back, modify git config file on disk. make sure we don't left credential. context.Warning("Unable to use git.exe remove injected credential from git remote fetch url, modify git config file on disk to remove injected credential."); string gitConfig = Path.Combine(repositoryPath, ".git/config"); if (File.Exists(gitConfig)) { string gitConfigContent = File.ReadAllText(Path.Combine(repositoryPath, ".git", "config")); gitConfigContent = gitConfigContent.Replace(_repositoryUrlWithCred.AbsoluteUri, repositoryUrl.AbsoluteUri); File.WriteAllText(gitConfig, gitConfigContent); } } } private bool IsPullRequest(string sourceBranch) { return !string.IsNullOrEmpty(sourceBranch) && (sourceBranch.StartsWith(_pullRefsPrefix, StringComparison.OrdinalIgnoreCase) || sourceBranch.StartsWith(_remotePullRefsPrefix, StringComparison.OrdinalIgnoreCase)); } private string GetRemoteRefName(string refName) { if (string.IsNullOrEmpty(refName)) { // If the refName is empty return the remote name for master refName = _remoteRefsPrefix + "master"; } else if (refName.Equals("master", StringComparison.OrdinalIgnoreCase)) { // If the refName is master return the remote name for master refName = _remoteRefsPrefix + refName; } else if (refName.StartsWith(_refsPrefix, StringComparison.OrdinalIgnoreCase)) { // If the refName is refs/heads change it to the remote version of the name refName = _remoteRefsPrefix + refName.Substring(_refsPrefix.Length); } else if (refName.StartsWith(_pullRefsPrefix, StringComparison.OrdinalIgnoreCase)) { // If the refName is refs/pull change it to the remote version of the name refName = refName.Replace(_pullRefsPrefix, _remotePullRefsPrefix); } return refName; } } }
/** * Copyright 2013 Mehran Ziadloo * WSS: A WebSocket Server written in C# and .Net (Mono) * (https://github.com/ziadloo/WSS) * * 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 Base; using System.Net.Sockets; using System.Net; using System.Threading; using System.Text.RegularExpressions; using System.Text; using System.Collections; using System.Collections.Generic; using Protocol; using System.Threading.Tasks; namespace WebSocketServer { public class Connection : IConnection { protected TcpClient socket; protected NetworkStream socketStream; private static int clientCounter = 0; private int clientId = -1; private object clientLock = new object(); protected bool connected = false; protected Server server; protected Application application; protected Header header; protected Draft draft; protected List<byte> buffer = new List<byte>(); protected byte[] message = new byte[4096]; protected object extra = null; protected Session session = new Session(); public Connection(TcpClient socket, Server server) { this.socket = socket; this.server = server; socketStream = socket.GetStream(); lock (clientLock) { clientId = ++clientCounter; } startRead(); } protected virtual void startRead() { socketStream.BeginRead(message, 0, message.Length, handleAsyncRead, socketStream); } protected void handleAsyncRead(IAsyncResult res) { try { if (socket.Connected) { int bytesRead = socketStream.EndRead(res); if (bytesRead > 0) { byte[] temp = new byte[bytesRead]; Array.Copy(message, temp, bytesRead); startRead(); //listen for new connections again digestIncomingMessage(temp); return; } } ((IConnection)this).Close(); } catch (Exception ex) { ((ILogger)server).error("Reading from client failed. Removing the client from list. Error message: " + ex.Message); ((IConnection)this).Close(); } } private bool digestIncomingMessage(byte[] _buffer) { if (_buffer.Length == 0) { //the client has disconnected from the server return false; } //message has successfully been received try { for (int i=0; i<_buffer.Length; i++) { buffer.Add(_buffer[i]); } if (draft == null) { foreach (Draft d in server.Drafts) { try { header = d.ParseClientRequestHandshake(buffer); draft = d; if (header.URL == "/") { application = server; } else { //Extracting application's name Regex regex = new Regex("/?([^/\\?\\*\\+\\\\]+)[/\\?]?.*"); Match mtch = regex.Match(header.URL); string appName = mtch.Groups[1].Value; application = ((IServer)server).GetApplication(appName); if (application == null) { ((ILogger)server).error("Invalid application: " + appName + ", URL: " + header.URL); sendHttpResponse(404); ((IConnection)this).Close(); return false; } } byte[] b = d.CreateServerResponseHandshake(header); socketStream.Write(b, 0, b.Length); socketStream.Flush(); #if LOGGER ((ILogger)server).log("Handshake was sent to:" + ((IConnection)this).IP.ToString()); #endif connected = true; application.AddConnection(this); // server.AddConnection(this); break; } catch (Exception ex) { } } } if (draft != null) { Frame f; while ((f = draft.ParseClientFrameBytes(buffer)) != null) { f.Connection = this; if (f.OpCode == Frame.OpCodeType.Close) { ((IConnection)this).Close(); break; } else if (f.OpCode == Frame.OpCodeType.Ping) { ((IConnection)this).Send(new Frame(Frame.OpCodeType.Pong)); } else if (f.OpCode == Frame.OpCodeType.Pong) { server.OnPonged(this); } if (application != null) { application.EnqueueIncomingFrame(f); } } } } catch { } return true; } public void sendHttpResponse(int httpStatusCode = 400) { string httpHeader = "HTTP/1.1 "; switch (httpStatusCode) { case 400: httpHeader += "400 Bad Request"; break; case 401: httpHeader += "401 Unauthorized"; break; case 403: httpHeader += "403 Forbidden"; break; case 404: httpHeader += "404 Not Found"; break; case 501: httpHeader += "501 Not Implemented"; break; } httpHeader += "\r\n"; byte[] b = System.Text.Encoding.UTF8.GetBytes(httpHeader); socketStream.Write(b, 0, b.Length); socketStream.Flush(); } #region IConnection implementation void IConnection.Send(Frame frame) { try { if (connected) { byte[] b = draft.CreateServerFrameBytes(frame); if (b != null) { socketStream.BeginWrite(b, 0, b.Length, null, null); } } } catch (Exception ex) { ((ILogger)server).error("Writing to client failed. Removing the client from list. Error message: " + ex.Message); ((IConnection)this).Close(); } } string IConnection.IP { get { return ((IPEndPoint)(socket.Client.RemoteEndPoint)).Address.ToString(); } } int IConnection.Port { get { return ((IPEndPoint)(socket.Client.RemoteEndPoint)).Port; } } int IConnection.ConnectionId { get { return clientId; } } bool IConnection.Connected { get { return connected && socket.Connected; } } bool IConnection.IsABridge { get { return false; } } Application IConnection.Application { get { return application; } } IServer IConnection.Server { get { return server; } } void IConnection.Close(bool SayBye) { if (connected) { connected = false; #if LOGGER ((ILogger)server).log("Connection is closed, " + ((IConnection)this).IP.ToString()); #endif if (SayBye) { try { byte[] b = draft.CreateServerFrameBytes(new Frame(Frame.OpCodeType.Close)); socketStream.Write(b, 0, b.Length); } catch (Exception) {} } try { socket.Close(); } catch (Exception) {} if (application != null) { application.RemoveConnection(this); } // if (application != server) { // server.RemoveConnection(this); // } } } object IConnection.Extra { get { return extra; } set { extra = value; } } Session IConnection.Session { get { return session; } set { session = value; } } #endregion } }
/* * API V1 * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using NUnit.Framework; using IO.Swagger.Client; using IO.Swagger.Api; using IO.Swagger.Model; namespace IO.Swagger.Test { /// <summary> /// Class for testing UserApi /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the API endpoint. /// </remarks> [TestFixture] public class UserApiTests { private UserApi instance; /// <summary> /// Setup before each unit test /// </summary> [SetUp] public void Init() { instance = new UserApi(Common.DefaultConfig); Common.Prepare(); } /// <summary> /// Clean up after each unit test /// </summary> [TearDown] public void Cleanup() { Common.Cleanup(); } /// <summary> /// Test an instance of UserApi /// </summary> [Test] public void InstanceTest() { Assert.IsInstanceOf(typeof(UserApi), instance, "instance is a UserApi"); } /// <summary> /// Test ApiUserByNameDelete /// </summary> [Test] public void ApiUserByNameDeleteTestWithRights() { string name = Common.UserName; string authorization = Common.AdminAuth; Assert.IsNotNull(instance.ApiUserByNameGet(name, authorization)); instance.ApiUserByNameDelete(name, authorization); var ex2 = Assert.Catch(() => instance.ApiUserByNameGet(name, authorization)) as ApiException; Assert.AreEqual(Common.NotFoundCode, ex2.ErrorCode); } /// <summary> /// Test ApiUserByNameDelete /// </summary> [Test] public void ApiUserByNameDeleteTestWithNoRights() { string name = Common.UserName; string checkAuthorization = Common.AdminAuth; string authorization = Common.UserAuth; Assert.IsNotNull(instance.ApiUserByNameGet(name, checkAuthorization)); var ex = Assert.Catch(() => instance.ApiUserByNameDelete(name, authorization)) as ApiException; Assert.AreEqual(Common.ForbiddenCode, ex.ErrorCode); Assert.IsNotNull(instance.ApiUserByNameGet(name, checkAuthorization)); } /// <summary> /// Test ApiUserByNameDelete /// </summary> [Test] public void ApiUserByNameDeleteTestWithBadRights() { string name = Common.UserName; string checkAuthorization = Common.AdminAuth; string authorization = Common.OtherAuth; Assert.IsNotNull(instance.ApiUserByNameGet(name, checkAuthorization)); var ex = Assert.Catch(() => instance.ApiUserByNameDelete(name, authorization)) as ApiException; Assert.AreEqual(Common.NeedAuthCode, ex.ErrorCode); Assert.IsNotNull(instance.ApiUserByNameGet(name, checkAuthorization)); } /// <summary> /// Test ApiUserByNameGet /// </summary> [Test] public void ApiUserByNameGetTestWithRights() { string name = Common.UserName; string authorization = Common.AdminAuth; var user = instance.ApiUserByNameGet(name, authorization); Assert.AreEqual(Common.UserName, user.Name); } /// <summary> /// Test ApiUserByNameGet /// </summary> [Test] public void ApiUserByNameGetTestWithNoRights() { string name = Common.UserName; string authorization = Common.OtherAuth; var ex = Assert.Catch(() => instance.ApiUserByNameGet(name, authorization)) as ApiException; Assert.AreEqual(Common.NeedAuthCode, ex.ErrorCode); } /// <summary> /// Test ApiUserByNameGet /// </summary> [Test] public void ApiUserByNameGetTestWithBadRights() { string name = Common.UserName; string authorization = Common.UserAuth; var ex = Assert.Catch(() => instance.ApiUserByNameGet(name, authorization)) as ApiException; Assert.AreEqual(Common.ForbiddenCode, ex.ErrorCode); } /// <summary> /// Test ApiUserByNamePatch /// </summary> [Test] public void ApiUserByNamePatchTestWithRights() { string name = Common.UserName; string authorization = Common.AdminAuth; var newPass = name + "123"; User item = new User(name, newPass); instance.ApiUserByNamePatch(name, authorization, item); var user = instance.ApiUserByNameGet(name, authorization); Assert.AreEqual(newPass, user.Password); } /// <summary> /// Test ApiUserByNamePatch /// </summary> [Test] public void ApiUserByNamePatchTestWithNoRights() { string name = Common.UserName; string authorization = Common.UserAuth; string chechAuthorization = Common.AdminAuth; var newPass = name + "123"; User item = new User(name, newPass); var ex = Assert.Catch(() => instance.ApiUserByNamePatch(name, authorization, item)) as ApiException; Assert.AreEqual(Common.ForbiddenCode, ex.ErrorCode); var user = instance.ApiUserByNameGet(name, chechAuthorization); Assert.AreNotEqual(newPass, user.Password); } /// <summary> /// Test ApiUserByNamePatch /// </summary> [Test] public void ApiUserByNamePatchTestWithBadRights() { string name = Common.UserName; string authorization = Common.OtherAuth; string chechAuthorization = Common.AdminAuth; var newPass = name + "123"; User item = new User(name, newPass); var ex = Assert.Catch(() => instance.ApiUserByNamePatch(name, authorization, item)) as ApiException; Assert.AreEqual(Common.NeedAuthCode, ex.ErrorCode); var user = instance.ApiUserByNameGet(name, chechAuthorization); Assert.AreNotEqual(newPass, user.Password); } /// <summary> /// Test ApiUserGet /// </summary> [Test] public void ApiUserGetTestWithRights() { string authorization = Common.AdminAuth; var response = instance.ApiUserGet(authorization); Assert.IsInstanceOf<List<User>> (response, "response is List<User>"); } /// <summary> /// Test ApiUserGet /// </summary> [Test] public void ApiUserGetTestWithNoRights() { string authorization = Common.UserAuth; var ex = Assert.Catch(() => instance.ApiUserGet(authorization)) as ApiException; Assert.AreEqual(Common.ForbiddenCode, ex.ErrorCode); } /// <summary> /// Test ApiUserGet /// </summary> [Test] public void ApiUserGetTestWithBadAuth() { string authorization = Common.OtherAuth; var ex = Assert.Catch(() => instance.ApiUserGet(authorization)) as ApiException; Assert.AreEqual(Common.NeedAuthCode, ex.ErrorCode); } /// <summary> /// Test ApiUserPost /// </summary> [Test] public void ApiUserPostTestWithRights() { string authorization = Common.AdminAuth; var userName = "NewUser"; User item = new User(userName, userName); instance.ApiUserPost(authorization, item); Assert.IsNotNull(instance.ApiUserByNameGet(userName, authorization)); } /// <summary> /// Test ApiUserPost /// </summary> [Test] public void ApiUserPostTestWithNoRights() { string authorization = Common.UserAuth; string checkAuthorization = Common.AdminAuth; var userName = "NewUser"; User item = new User(userName, userName); var ex = Assert.Catch(() => instance.ApiUserPost(authorization, item)) as ApiException; Assert.AreEqual(Common.ForbiddenCode, ex.ErrorCode); var ex2 = Assert.Catch(() => instance.ApiUserByNameGet(userName, checkAuthorization)) as ApiException; Assert.AreEqual(Common.NotFoundCode, ex2.ErrorCode); } /// <summary> /// Test ApiUserPost /// </summary> [Test] public void ApiUserPostTestWithBadRights() { string authorization = Common.OtherAuth; string checkAuthorization = Common.AdminAuth; var userName = "NewUser"; User item = new User(userName, userName); var ex = Assert.Catch(() => instance.ApiUserPost(authorization, item)) as ApiException; Assert.AreEqual(Common.NeedAuthCode, ex.ErrorCode); var ex2 = Assert.Catch(() => instance.ApiUserByNameGet(userName, checkAuthorization)) as ApiException; Assert.AreEqual(Common.NotFoundCode, ex2.ErrorCode); } /// <summary> /// Test ApiUserPost /// </summary> [Test] public void ApiUserPostTestCheckNewUserWithNoRights() { string authorization = Common.AdminAuth; var userName = "NewUser"; User item = new User(userName, userName); instance.ApiUserPost(authorization, item); Assert.IsNotNull(instance.ApiUserByNameGet(userName, authorization)); var newUserAuth = Common.GetAuthHeader(userName, userName); var ex = Assert.Catch(() => instance.ApiUserGet(newUserAuth)) as ApiException; Assert.AreEqual(Common.ForbiddenCode, ex.ErrorCode); } /// <summary> /// Test ApiUserPost /// </summary> [Test] public void ApiUserPostTestCheckNewUserWithRights() { string authorization = Common.AdminAuth; var userName = "NewUser"; var roles = new List<UserRole>() { new UserRole(UserRole.PermissionsEnum.NUMBER_8) }; User item = new User(userName, userName, roles); instance.ApiUserPost(authorization, item); Assert.IsNotNull(instance.ApiUserByNameGet(userName, authorization)); var newUserAuth = Common.GetAuthHeader(userName, userName); instance.ApiUserGet(newUserAuth); } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Collections.Generic; using System.Threading; using System.ComponentModel; using System.Reactive.Subjects; namespace InteractiveDataDisplay.WPF { /// <summary> /// Base class for renderers, which can prepare its render results in a separate thread. /// </summary> public abstract class BackgroundBitmapRenderer : Plot { private Image outputImage; /// <summary>Cartesian coordinates of image currently on the screen.</summary> private DataRect imageCartesianRect; /// <summary>Size of image currently on the screen.</summary> private Size imageSize; private int maxTasks; private Queue<long> tasks = new Queue<long>(); private delegate void RenderFunc(RenderResult r, RenderTaskState state); private List<RenderTaskState> runningTasks; private long nextID = 0; /// <summary> /// Initializes new instance of <see cref="BackgroundBitmapRenderer"/> class, performing all basic preparings for inheriting classes. /// </summary> protected BackgroundBitmapRenderer() { maxTasks = Math.Max(1, System.Environment.ProcessorCount - 1); runningTasks = new List<RenderTaskState>(); outputImage = new Image(); outputImage.Stretch = Stretch.None; outputImage.VerticalAlignment = System.Windows.VerticalAlignment.Center; outputImage.HorizontalAlignment = System.Windows.HorizontalAlignment.Center; Children.Add(outputImage); Unloaded += BackgroundBitmapRendererUnloaded; } void BackgroundBitmapRendererUnloaded(object sender, RoutedEventArgs e) { CancelAll(); } private Size prevSize = new Size(Double.NaN, Double.NaN); private double prevScaleX = Double.NaN, prevScaleY = Double.NaN, prevOffsetX = Double.NaN, prevOffsetY = Double.NaN; /// <summary> /// Measures the size in layout required for child elements and determines a size for parent. /// </summary> /// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param> /// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns> protected override Size MeasureOverride(Size availableSize) { availableSize = base.MeasureOverride(availableSize); outputImage.Measure(availableSize); // From resize or navigation? if (prevSize != availableSize || prevOffsetX != masterField.OffsetX || prevOffsetY != masterField.OffsetY || prevScaleX != masterField.ScaleX || prevScaleY != masterField.ScaleY) { prevSize = availableSize; prevOffsetX = masterField.OffsetX; prevOffsetY = masterField.OffsetY; prevScaleX = masterField.ScaleX; prevScaleY = masterField.ScaleY; CancelAll(); if (imageSize.Width > 0 && imageSize.Height > 0) { var newLT = new Point(LeftFromX(imageCartesianRect.XMin), TopFromY(imageCartesianRect.YMax)); var newRB = new Point(LeftFromX(imageCartesianRect.XMax), TopFromY(imageCartesianRect.YMin)); Canvas.SetLeft(outputImage, newLT.X); Canvas.SetTop(outputImage, newLT.Y); outputImage.RenderTransform = new ScaleTransform { ScaleX = (newRB.X - newLT.X) / imageSize.Width, ScaleY = (newRB.Y - newLT.Y) / imageSize.Height }; } QueueRenderTask(); } return availableSize; } private void EnqueueTask(long id/*Func<RenderTaskState, RenderResult> task*/) { if (runningTasks.Count < maxTasks) { Size screenSize = new Size(Math.Abs(LeftFromX(ActualPlotRect.XMax) - LeftFromX(ActualPlotRect.XMin)), Math.Abs(TopFromY(ActualPlotRect.YMax) - TopFromY(ActualPlotRect.YMin))); RenderTaskState state = new RenderTaskState(ActualPlotRect, screenSize); state.Id = id; state.Bounds = ComputeBounds(); runningTasks.Add(state); if (!DesignerProperties.GetIsInDesignMode(this)) { ThreadPool.QueueUserWorkItem(s => { var rr = RenderFrame((RenderTaskState)s); Dispatcher.BeginInvoke(new RenderFunc(OnTaskCompleted), rr, s); }, state); } else { var rr = RenderFrame(state); OnTaskCompleted(rr, state); } } else tasks.Enqueue(id); } /// <summary> /// Renders frame and returns it as a render result. /// </summary> /// <param name="state">Render task state for rendering frame.</param> /// <returns>Render result of rendered frame.</returns> protected virtual RenderResult RenderFrame(RenderTaskState state) { //if (!state.IsCancelled) // return new RenderResult(HeatMap.BuildHeatMap(state.Transform.ScreenRect, new DataRect(state.Transform.ViewportRect), DataSource.X, DataSource.Y, DataSource.Data, 0)); //else return null; } /// <summary>Creates new render task and puts it to queue.</summary> /// <returns>Async operation ID.</returns> protected long QueueRenderTask() { long id = nextID++; EnqueueTask(id); return id; } private void OnTaskCompleted(RenderResult r, RenderTaskState state) { if (r != null && !state.IsCanceled) { WriteableBitmap wr = new WriteableBitmap((int)r.Output.Width, (int)r.Output.Height, 96, 96, PixelFormats.Bgra32, null); // Calculate the number of bytes per pixel. int bytesPerPixel = (wr.Format.BitsPerPixel + 7) / 8; // Stride is bytes per pixel times the number of pixels. // Stride is the byte width of a single rectangle row. int stride = wr.PixelWidth * bytesPerPixel; wr.WritePixels(new Int32Rect(0, 0, wr.PixelWidth, wr.PixelHeight), r.Image, stride, 0); outputImage.Source = wr; Canvas.SetLeft(outputImage, r.Output.Left); Canvas.SetTop(outputImage, r.Output.Top); imageCartesianRect = r.Visible; imageSize = new Size(r.Output.Width, r.Output.Height); outputImage.RenderTransform = null; } RaiseTaskCompletion(state.Id); runningTasks.Remove(state); while (tasks.Count > 1) { long id = tasks.Dequeue(); RaiseTaskCompletion(id); } if (tasks.Count > 0 && runningTasks.Count < maxTasks) { EnqueueTask(tasks.Dequeue()); } InvalidateMeasure(); } /// <summary> /// Cancel all tasks, which are in quere. /// </summary> public void CancelAll() { foreach (var s in runningTasks) s.Stop(); } private Subject<RenderCompletion> renderCompletion = new Subject<RenderCompletion>(); /// <summary> /// Gets event which is occured when render task is finished /// </summary> public IObservable<RenderCompletion> RenderCompletion { get { return renderCompletion; } } /// <summary> /// Raises RenderCompletion event when task with the specified id is finished /// </summary> /// <param name="id">ID of finished task</param> protected void RaiseTaskCompletion(long id) { renderCompletion.OnNext(new RenderCompletion { TaskId = id }); } } /// <summary> /// Represents contents of render result. /// </summary> public class RenderResult { private DataRect visible; private Rect output; private int[] image; /// <summary> /// Initializes new instance of RenderResult class form given parameters. /// </summary> /// <param name="image">Array of image pixels.</param> /// <param name="visible">Visible rect for graph.</param> /// <param name="offset">Image start offset.</param> /// <param name="width">Image width.</param> /// <param name="height">image height.</param> public RenderResult(int[] image, DataRect visible, Point offset, double width, double height) { this.visible = visible; this.output = new Rect(offset, new Size(width, height)); this.image = image; } /// <summary> /// Gets the current visible rect. /// </summary> public DataRect Visible { get { return visible; } } /// <summary> /// Gets an array of image pixels. /// </summary> public int[] Image { get { return image; } } /// <summary> /// Gets the image output rect. /// </summary> public Rect Output { get { return output; } } } /// <summary>This class holds all information about rendering request.</summary> public class RenderTaskState { bool isCanceled = false; /// <summary> /// Initializes new instance of RenderTaskState class from given coordinate tranform. /// </summary> public RenderTaskState(DataRect actualPlotRect, Size screenSize) { ScreenSize = screenSize; ActualPlotRect = actualPlotRect; } /// <summary> /// Gets or sets the state Id. /// </summary> public long Id { get; set; } /// <summary> /// Gets the screen size of the output image /// </summary> public Size ScreenSize { get; private set; } /// <summary> /// Gets plot rectangle of the visible area /// </summary> public DataRect ActualPlotRect { get; private set; } /// <summary> /// Gets or sets the current bounds. /// </summary> public DataRect Bounds { get; set; } /// <summary> /// Gets a value indicating whether the task is cancelled or not. /// </summary> public bool IsCanceled { get { return isCanceled; } } /// <summary> /// Sets state as canceled. /// </summary> public void Stop() { isCanceled = true; } } ///<summary> ///Contains reference to completed tasks. ///</summary> public class RenderCompletion { ///<summary> ///Gets or sets the Id of render task. ///</summary> public long TaskId { get; set; } } }
// // 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.RemoteApp; using Microsoft.WindowsAzure.Management.RemoteApp.Models; namespace Microsoft.WindowsAzure.Management.RemoteApp { /// <summary> /// RmoteApp management client /// </summary> public static partial class PrincipalOperationsExtensions { /// <summary> /// Adds a list of principals to the given collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to add. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static SecurityPrincipalOperationsResult Add(this IPrincipalOperations operations, string collectionName, SecurityPrincipalList securityPrincipalList) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).AddAsync(collectionName, securityPrincipalList); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Adds a list of principals to the given collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to add. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static Task<SecurityPrincipalOperationsResult> AddAsync(this IPrincipalOperations operations, string collectionName, SecurityPrincipalList securityPrincipalList) { return operations.AddAsync(collectionName, securityPrincipalList, CancellationToken.None); } /// <summary> /// Adds a list of principals to the given collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to add to the published /// app. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static SecurityPrincipalOperationsResult AddToApp(this IPrincipalOperations operations, string collectionName, string appAlias, SecurityPrincipalList securityPrincipalList) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).AddToAppAsync(collectionName, appAlias, securityPrincipalList); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Adds a list of principals to the given collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to add to the published /// app. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static Task<SecurityPrincipalOperationsResult> AddToAppAsync(this IPrincipalOperations operations, string collectionName, string appAlias, SecurityPrincipalList securityPrincipalList) { return operations.AddToAppAsync(collectionName, appAlias, securityPrincipalList, CancellationToken.None); } /// <summary> /// Deletes a list of principals from the given collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to delete. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static SecurityPrincipalOperationsResult Delete(this IPrincipalOperations operations, string collectionName, SecurityPrincipalList securityPrincipalList) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).DeleteAsync(collectionName, securityPrincipalList); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a list of principals from the given collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to delete. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static Task<SecurityPrincipalOperationsResult> DeleteAsync(this IPrincipalOperations operations, string collectionName, SecurityPrincipalList securityPrincipalList) { return operations.DeleteAsync(collectionName, securityPrincipalList, CancellationToken.None); } /// <summary> /// Deletes a list of principals from the given app. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to delete from the /// published app. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static SecurityPrincipalOperationsResult DeleteFromApp(this IPrincipalOperations operations, string collectionName, string appAlias, SecurityPrincipalList securityPrincipalList) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).DeleteFromAppAsync(collectionName, appAlias, securityPrincipalList); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a list of principals from the given app. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <param name='securityPrincipalList'> /// Required. A list of RemoteApp principals to delete from the /// published app. /// </param> /// <returns> /// The response for the collection user operation. /// </returns> public static Task<SecurityPrincipalOperationsResult> DeleteFromAppAsync(this IPrincipalOperations operations, string collectionName, string appAlias, SecurityPrincipalList securityPrincipalList) { return operations.DeleteFromAppAsync(collectionName, appAlias, securityPrincipalList, CancellationToken.None); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <returns> /// The list of principals with consent status. /// </returns> public static SecurityPrincipalInfoListResult List(this IPrincipalOperations operations, string collectionName) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).ListAsync(collectionName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <returns> /// The list of principals with consent status. /// </returns> public static Task<SecurityPrincipalInfoListResult> ListAsync(this IPrincipalOperations operations, string collectionName) { return operations.ListAsync(collectionName, CancellationToken.None); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// app in a collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <returns> /// The list of principals with consent status. /// </returns> public static SecurityPrincipalInfoListResult ListForApp(this IPrincipalOperations operations, string collectionName, string appAlias) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).ListForAppAsync(collectionName, appAlias); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// app in a collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <returns> /// The list of principals with consent status. /// </returns> public static Task<SecurityPrincipalInfoListResult> ListForAppAsync(this IPrincipalOperations operations, string collectionName, string appAlias) { return operations.ListForAppAsync(collectionName, appAlias, CancellationToken.None); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// app in a collection using continuation token. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <param name='previousContinuationToken'> /// Optional. Continuation token. /// </param> /// <returns> /// The list of principals with consent status and continuation token. /// </returns> public static SecurityPrincipalInfoListWithTokenResult ListForAppWithToken(this IPrincipalOperations operations, string collectionName, string appAlias, string previousContinuationToken) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).ListForAppWithTokenAsync(collectionName, appAlias, previousContinuationToken); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// app in a collection using continuation token. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='appAlias'> /// Required. Application alias. /// </param> /// <param name='previousContinuationToken'> /// Optional. Continuation token. /// </param> /// <returns> /// The list of principals with consent status and continuation token. /// </returns> public static Task<SecurityPrincipalInfoListWithTokenResult> ListForAppWithTokenAsync(this IPrincipalOperations operations, string collectionName, string appAlias, string previousContinuationToken) { return operations.ListForAppWithTokenAsync(collectionName, appAlias, previousContinuationToken, CancellationToken.None); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// collection using continuation token. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='previousContinuationToken'> /// Optional. Continuation token. /// </param> /// <returns> /// The list of principals with consent status and continuation token. /// </returns> public static SecurityPrincipalInfoListWithTokenResult ListWithToken(this IPrincipalOperations operations, string collectionName, string previousContinuationToken) { return Task.Factory.StartNew((object s) => { return ((IPrincipalOperations)s).ListWithTokenAsync(collectionName, previousContinuationToken); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of all RemoteApp principals associated with the given /// collection using continuation token. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPrincipalOperations. /// </param> /// <param name='collectionName'> /// Required. The RemoteApp collection name. /// </param> /// <param name='previousContinuationToken'> /// Optional. Continuation token. /// </param> /// <returns> /// The list of principals with consent status and continuation token. /// </returns> public static Task<SecurityPrincipalInfoListWithTokenResult> ListWithTokenAsync(this IPrincipalOperations operations, string collectionName, string previousContinuationToken) { return operations.ListWithTokenAsync(collectionName, previousContinuationToken, CancellationToken.None); } } }
// 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { private sealed partial class WorkCoordinator { private sealed partial class IncrementalAnalyzerProcessor { private sealed class NormalPriorityProcessor : GlobalOperationAwareIdleProcessor { private readonly AsyncDocumentWorkItemQueue _workItemQueue; private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers; private readonly ConcurrentDictionary<DocumentId, IDisposable> _higherPriorityDocumentsNotProcessed; private readonly HashSet<ProjectId> _currentSnapshotVersionTrackingSet; private ProjectId _currentProjectProcessing; private Solution _processingSolution; private IDisposable _projectCache; // whether this processor is running or not private Task _running; public NormalPriorityProcessor( IAsynchronousOperationListener listener, IncrementalAnalyzerProcessor processor, Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers, IGlobalOperationNotificationService globalOperationNotificationService, int backOffTimeSpanInMs, CancellationToken shutdownToken) : base(listener, processor, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken) { _lazyAnalyzers = lazyAnalyzers; _running = SpecializedTasks.EmptyTask; _workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter); _higherPriorityDocumentsNotProcessed = new ConcurrentDictionary<DocumentId, IDisposable>(concurrencyLevel: 2, capacity: 20); _currentProjectProcessing = default(ProjectId); _processingSolution = null; _currentSnapshotVersionTrackingSet = new HashSet<ProjectId>(); Start(); } internal ImmutableArray<IIncrementalAnalyzer> Analyzers { get { return _lazyAnalyzers.Value; } } public void Enqueue(WorkItem item) { Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item"); this.UpdateLastAccessTime(); var added = _workItemQueue.AddOrReplace(item); Logger.Log(FunctionId.WorkCoordinator_DocumentWorker_Enqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added); CheckHigherPriorityDocument(item); SolutionCrawlerLogger.LogWorkItemEnqueue( this.Processor._logAggregator, item.Language, item.DocumentId, item.InvocationReasons, item.IsLowPriority, item.ActiveMember, added); } private void CheckHigherPriorityDocument(WorkItem item) { if (item.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened) || item.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed)) { AddHigherPriorityDocument(item.DocumentId); } } private void AddHigherPriorityDocument(DocumentId id) { var cache = Processor.EnableCaching(id.ProjectId); if (!_higherPriorityDocumentsNotProcessed.TryAdd(id, cache)) { // we already have the document in the queue. cache.Dispose(); } SolutionCrawlerLogger.LogHigherPriority(this.Processor._logAggregator, id.Id); } protected override Task WaitAsync(CancellationToken cancellationToken) { if (!_workItemQueue.HasAnyWork) { DisposeProjectCache(); } return _workItemQueue.WaitAsync(cancellationToken); } public Task Running { get { return _running; } } public bool HasAnyWork { get { return _workItemQueue.HasAnyWork; } } protected override async Task ExecuteAsync() { if (this.CancellationToken.IsCancellationRequested) { return; } var source = new TaskCompletionSource<object>(); try { // mark it as running _running = source.Task; await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false); // okay, there must be at least one item in the map await ResetStatesAsync().ConfigureAwait(false); if (await TryProcessOneHigherPriorityDocumentAsync().ConfigureAwait(false)) { // successfully processed a high priority document. return; } // process one of documents remaining var documentCancellation = default(CancellationTokenSource); WorkItem workItem; if (!_workItemQueue.TryTakeAnyWork(_currentProjectProcessing, this.Processor.DependencyGraph, out workItem, out documentCancellation)) { return; } // check whether we have been shutdown if (this.CancellationToken.IsCancellationRequested) { return; } // check whether we have moved to new project SetProjectProcessing(workItem.ProjectId); // process the new document await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // mark it as done running source.SetResult(null); } } protected override Task HigherQueueOperationTask { get { return this.Processor._highPriorityProcessor.Running; } } protected override bool HigherQueueHasWorkItem { get { return this.Processor._highPriorityProcessor.HasAnyWork; } } protected override void PauseOnGlobalOperation() { _workItemQueue.RequestCancellationOnRunningTasks(); } private void SetProjectProcessing(ProjectId currentProject) { EnableProjectCacheIfNecessary(currentProject); _currentProjectProcessing = currentProject; } private void EnableProjectCacheIfNecessary(ProjectId currentProject) { if (_projectCache != null && currentProject == _currentProjectProcessing) { return; } DisposeProjectCache(); _projectCache = Processor.EnableCaching(currentProject); } private static void DisposeProjectCache(IDisposable projectCache) { projectCache?.Dispose(); } private void DisposeProjectCache() { DisposeProjectCache(_projectCache); _projectCache = null; } private IEnumerable<DocumentId> GetPrioritizedPendingDocuments() { if (this.Processor._documentTracker != null) { // First the active document var activeDocumentId = this.Processor._documentTracker.GetActiveDocument(); if (activeDocumentId != null && _higherPriorityDocumentsNotProcessed.ContainsKey(activeDocumentId)) { yield return activeDocumentId; } // Now any visible documents foreach (var visibleDocumentId in this.Processor._documentTracker.GetVisibleDocuments()) { if (_higherPriorityDocumentsNotProcessed.ContainsKey(visibleDocumentId)) { yield return visibleDocumentId; } } } // Any other opened documents foreach (var documentId in _higherPriorityDocumentsNotProcessed.Keys) { yield return documentId; } } private async Task<bool> TryProcessOneHigherPriorityDocumentAsync() { try { // this is an best effort algorithm with some shortcommings. // // the most obvious issue is if there is a new work item (without a solution change - but very unlikely) // for a opened document we already processed, the work item will be treated as a regular one rather than higher priority one // (opened document) CancellationTokenSource documentCancellation; foreach (var documentId in this.GetPrioritizedPendingDocuments()) { if (this.CancellationToken.IsCancellationRequested) { return true; } // see whether we have work item for the document WorkItem workItem; if (!_workItemQueue.TryTake(documentId, out workItem, out documentCancellation)) { RemoveHigherPriorityDocument(documentId); continue; } // okay now we have work to do await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false); RemoveHigherPriorityDocument(documentId); return true; } return false; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private void RemoveHigherPriorityDocument(DocumentId documentId) { // remove opened document processed IDisposable projectCache; if (_higherPriorityDocumentsNotProcessed.TryRemove(documentId, out projectCache)) { DisposeProjectCache(projectCache); } } private async Task ProcessDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source) { if (this.CancellationToken.IsCancellationRequested) { return; } var processedEverything = false; var documentId = workItem.DocumentId; try { using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token)) { var cancellationToken = source.Token; var document = _processingSolution.GetDocument(documentId); if (document != null) { await TrackSemanticVersionsAsync(document, workItem, cancellationToken).ConfigureAwait(false); // if we are called because a document is opened, we invalidate the document so that // it can be re-analyzed. otherwise, since newly opened document has same version as before // analyzer will simply return same data back if (workItem.MustRefresh && !workItem.IsRetry) { var isOpen = document.IsOpen(); await ProcessOpenDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false); await ProcessCloseDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false); } // check whether we are having special reanalyze request await ProcessReanalyzeDocumentAsync(workItem, document, cancellationToken).ConfigureAwait(false); await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false); } else { SolutionCrawlerLogger.LogProcessDocumentNotExist(this.Processor._logAggregator); RemoveDocument(documentId); } if (!cancellationToken.IsCancellationRequested) { processedEverything = true; } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // we got cancelled in the middle of processing the document. // let's make sure newly enqueued work item has all the flag needed. if (!processedEverything) { _workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem"))); } SolutionCrawlerLogger.LogProcessDocument(this.Processor._logAggregator, documentId.Id, processedEverything); // remove one that is finished running _workItemQueue.RemoveCancellationSource(workItem.DocumentId); } } private async Task TrackSemanticVersionsAsync(Document document, WorkItem workItem, CancellationToken cancellationToken) { if (workItem.IsRetry || workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentAdded) || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged)) { return; } var service = document.Project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (service == null) { return; } // we already reported about this project for same snapshot, don't need to do it again if (_currentSnapshotVersionTrackingSet.Contains(document.Project.Id)) { return; } await service.RecordSemanticVersionsAsync(document.Project, cancellationToken).ConfigureAwait(false); // mark this project as already processed. _currentSnapshotVersionTrackingSet.Add(document.Project.Id); } private async Task ProcessOpenDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken) { if (!isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened)) { return; } SolutionCrawlerLogger.LogProcessOpenDocument(this.Processor._logAggregator, document.Id.Id); await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentOpenAsync(d, c), cancellationToken).ConfigureAwait(false); } private async Task ProcessCloseDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken) { if (isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed)) { return; } SolutionCrawlerLogger.LogProcessCloseDocument(this.Processor._logAggregator, document.Id.Id); await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentCloseAsync(d, c), cancellationToken).ConfigureAwait(false); } private async Task ProcessReanalyzeDocumentAsync(WorkItem workItem, Document document, CancellationToken cancellationToken) { try { #if DEBUG Contract.Requires(!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze) || workItem.Analyzers.Count > 0); #endif // no-reanalyze request or we already have a request to re-analyze every thing if (workItem.MustRefresh || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze)) { return; } // First reset the document state in analyzers. var reanalyzers = workItem.Analyzers.ToImmutableArray(); await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.DocumentResetAsync(d, c), cancellationToken).ConfigureAwait(false); // no request to re-run syntax change analysis. run it here if (!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged)) { await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeSyntaxAsync(d, c), cancellationToken).ConfigureAwait(false); } // no request to re-run semantic change analysis. run it here if (!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private void RemoveDocument(DocumentId documentId) { RemoveDocument(this.Analyzers, documentId); } private static void RemoveDocument(IEnumerable<IIncrementalAnalyzer> analyzers, DocumentId documentId) { foreach (var analyzer in analyzers) { analyzer.RemoveDocument(documentId); } } private void ResetLogAggregatorIfNeeded(Solution currentSolution) { if (currentSolution == null || _processingSolution == null || currentSolution.Id == _processingSolution.Id) { return; } SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics( this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers); this.Processor.ResetLogAggregator(); } private async Task ResetStatesAsync() { try { var currentSolution = this.Processor.CurrentSolution; if (currentSolution != _processingSolution) { ResetLogAggregatorIfNeeded(currentSolution); // clear version tracking set we already reported. _currentSnapshotVersionTrackingSet.Clear(); _processingSolution = currentSolution; await RunAnalyzersAsync(this.Analyzers, currentSolution, (a, s, c) => a.NewSolutionSnapshotAsync(s, c), this.CancellationToken).ConfigureAwait(false); foreach (var id in this.Processor.GetOpenDocumentIds()) { AddHigherPriorityDocument(id); } SolutionCrawlerLogger.LogResetStates(this.Processor._logAggregator); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override void Shutdown() { base.Shutdown(); SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers); _workItemQueue.Dispose(); if (_projectCache != null) { _projectCache.Dispose(); _projectCache = null; } } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items) { CancellationTokenSource source = new CancellationTokenSource(); _processingSolution = this.Processor.CurrentSolution; foreach (var item in items) { ProcessDocumentAsync(analyzers, item, source).Wait(); } } internal void WaitUntilCompletion_ForTestingPurposesOnly() { // this shouldn't happen. would like to get some diagnostic while (_workItemQueue.HasAnyWork) { Environment.FailFast("How?"); } } } } } } }
using System.Collections.Generic; using System.Net; using System.Net.Http; using FluentAssert; using Microsoft.VisualStudio.TestTools.UnitTesting; using Rest.Net.Authenticators; using Rest.Net.Interfaces; namespace Rest.Net.Tests { [TestClass] public class RestNetTests { public RestNetTests() { } [TestMethod] public void ShouldBeAbleToExecuteGetRequestWithSpecificPoperty() { RestClient client = new RestClient("https://dummyapi.io/api/"); IRestResponse<List<User>> result = client.GetAsync<List<User>>("user", "data").Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); result.Data.ShouldNotBeNull(); result.Data.Count.ShouldBeGreaterThan(0); result.Data[0].ShouldNotBeNull(); } [TestMethod] public void ShouldBeAbleToExecuteGetRequest() { RestClient client = new RestClient("https://jsonplaceholder.typicode.com/"); IRestResponse<List<Post>> result = client.GetAsync<List<Post>>("posts").Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); result.Data.ShouldNotBeNull(); result.Data.Count.ShouldBeGreaterThan(0); result.Data[0].ShouldNotBeNull(); } [TestMethod] public void ShouldBeAbleToExecuteGetRequestWithAnonymousDefinition() { var userDef = new { Id = 0, NameTitle = string.Empty, FirstName = string.Empty, LastName = string.Empty, Image = string.Empty }; RestClient client = new RestClient("https://dummyapi.io/api"); var result = client.GetAsync("user/1", userDef).Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); result.Data.ShouldNotBeNull(); result.Data.Id.ShouldBeEqualTo(1); } [TestMethod] public void ShouldBeAbleToExecutePostRequest() { var postDef = new { Id = 0 }; RestClient client = new RestClient("https://jsonplaceholder.typicode.com/"); var result = client.PostAsync("posts", null, postDef).Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.Created); result.Data.ShouldNotBeNull(); result.Data.Id.ShouldBeGreaterThan(0); } [TestMethod] public void ShouldBeAbleToExecutePutRequest() { var postDef = new { Id = 0 }; RestClient client = new RestClient("https://jsonplaceholder.typicode.com/"); var result = client.PutAsync("posts/1", null, postDef).Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); result.Data.ShouldNotBeNull(); result.Data.Id.ShouldBeGreaterThan(0); } [TestMethod] public void ShouldBeAbleToExecuteDeleteRequest() { var postDef = new { Id = 0 }; RestClient client = new RestClient("https://jsonplaceholder.typicode.com/"); var result = client.DeleteAsync("posts/1", null, postDef).Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); } [TestMethod] public void ShouldBeAbleToUseOAuth2AuthenticatorUsingClientCredentialsFlow() { RestClient client = new RestClient("http://localhost:5000/"); client.Authentication = new OAuth2Authenticator("http://localhost:5000", "client", "secret"); IRestResponse<List<string>> result = client.GetAsync<List<string>>("/api/values/").Result; result = client.GetAsync<List<string>>("/api/values/").Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); result.Data.ShouldNotBeNull(); result.Data.Count.ShouldBeGreaterThan(0); } [TestMethod] public void ShouldBeAbleToUseOAuth2AuthenticatorUsingPasswordFlow() { RestClient client = new RestClient("http://localhost:5000/"); client.Authentication = new OAuth2Authenticator("http://localhost:5000", "ro.client", "secret", "alice", "password"); IRestResponse <List<string>> result = client.GetAsync<List<string>>("/api/values/").Result; result = client.GetAsync<List<string>>("/api/values/").Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); result.Data.ShouldNotBeNull(); result.Data.Count.ShouldBeGreaterThan(0); } [TestMethod] public void ShouldBeAbleToUseOAuth2AuthenticatorUsingRefreshToken() { string refreshToken = GetRefreshToken("ro.client", "secret", "alice", "password"); RestClient client = new RestClient("http://localhost:5000/"); client.Authentication = new OAuth2Authenticator("http://localhost:5000", "ro.client", "secret", refreshToken); IRestResponse<List<string>> result = client.GetAsync<List<string>>("/api/values/").Result; result = client.GetAsync<List<string>>("/api/values/").Result; result.ShouldNotBeNull(); result.IsError.ShouldBeFalse(); result.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); result.Data.ShouldNotBeNull(); result.Data.Count.ShouldBeGreaterThan(0); } private string GetRefreshToken(string clientId, string clientSecret, string username, string password) { IRestClient client = new RestClient("http://localhost:5000"); IRestRequest authRequest = new RestRequest("/connect/token", Http.Method.POST); authRequest.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); authRequest.RequiresAuthentication = false; Dictionary<string, string> formContent = new Dictionary<string, string>() { {"grant_type", "password"}, {"client_id", clientId}, {"client_secret", clientSecret}, {"username", username}, {"password", password} }; var autoResponseDef = new { access_token = "", refresh_token = "", expires_in = "", error = "" }; authRequest.SetContent(new FormUrlEncodedContent(formContent)); var response = client.ExecuteAsync(authRequest, autoResponseDef).Result; response.ShouldNotBeNull(); response.IsError.ShouldBeFalse(); response.StatusCode.ShouldBeEqualTo(HttpStatusCode.OK); response.Data.ShouldNotBeNull(); return response.Data.refresh_token; } } }
using System.IO; using System.Linq; using System.Text; using LibGit2Sharp.Tests.TestHelpers; using Xunit; namespace LibGit2Sharp.Tests { public class DiffTreeToTargetFixture : BaseFixture { private static void SetUpSimpleDiffContext(Repository repo) { var fullpath = Path.Combine(repo.Info.WorkingDirectory, "file.txt"); File.WriteAllText(fullpath, "hello\n"); repo.Index.Stage(fullpath); repo.Commit("Initial commit", DummySignature, DummySignature); File.AppendAllText(fullpath, "world\n"); repo.Index.Stage(fullpath); File.AppendAllText(fullpath, "!!!\n"); } [Fact] /* * No direct git equivalent but should output * * diff --git a/file.txt b/file.txt * index ce01362..4f125e3 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1,3 @@ * hello * +world * +!!! */ public void CanCompareASimpleTreeAgainstTheWorkDir() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { SetUpSimpleDiffContext(repo); TreeChanges changes = repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory); var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..4f125e3 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,3 @@\n") .Append(" hello\n") .Append("+world\n") .Append("+!!!\n"); Assert.Equal(expected.ToString(), changes.Patch); } } [Fact] public void CanCompareAMoreComplexTreeAgainstTheWorkdir() { using (var repo = new Repository(StandardTestRepoPath)) { Tree tree = repo.Head.Tip.Tree; TreeChanges changes = repo.Diff.Compare(tree, DiffTargets.WorkingDirectory); Assert.NotNull(changes); Assert.Equal(6, changes.Count()); Assert.Equal(new[] { "deleted_staged_file.txt", "deleted_unstaged_file.txt" }, changes.Deleted.Select(tec => tec.Path)); Assert.Equal(new[] { "new_tracked_file.txt", "new_untracked_file.txt" }, changes.Added.Select(tec => tec.Path)); Assert.Equal(new[] { "modified_staged_file.txt", "modified_unstaged_file.txt" }, changes.Modified.Select(tec => tec.Path)); } } [Fact] /* * $ git diff HEAD * diff --git a/file.txt b/file.txt * index ce01362..4f125e3 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1,3 @@ * hello * +world * +!!! */ public void CanCompareASimpleTreeAgainstTheWorkDirAndTheIndex() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { SetUpSimpleDiffContext(repo); TreeChanges changes = repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.Index | DiffTargets.WorkingDirectory); var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..4f125e3 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,3 @@\n") .Append(" hello\n") .Append("+world\n") .Append("+!!!\n"); Assert.Equal(expected.ToString(), changes.Patch); } } [Fact] /* * $ git diff * * $ git diff HEAD * diff --git a/file.txt b/file.txt * deleted file mode 100644 * index ce01362..0000000 * --- a/file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -hello * * $ git diff --cached * diff --git a/file.txt b/file.txt * deleted file mode 100644 * index ce01362..0000000 * --- a/file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -hello */ public void ShowcaseTheDifferenceBetweenTheTwoKindOfComparison() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { SetUpSimpleDiffContext(repo); var fullpath = Path.Combine(repo.Info.WorkingDirectory, "file.txt"); File.Move(fullpath, fullpath + ".bak"); repo.Index.Stage(fullpath); File.Move(fullpath + ".bak", fullpath); FileStatus state = repo.Index.RetrieveStatus("file.txt"); Assert.Equal(FileStatus.Removed | FileStatus.Untracked, state); TreeChanges wrkDirToIdxToTree = repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.Index | DiffTargets.WorkingDirectory); var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("deleted file mode 100644\n") .Append("index ce01362..0000000\n") .Append("--- a/file.txt\n") .Append("+++ /dev/null\n") .Append("@@ -1 +0,0 @@\n") .Append("-hello\n"); Assert.Equal(expected.ToString(), wrkDirToIdxToTree.Patch); TreeChanges wrkDirToTree = repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory); expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..4f125e3 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,3 @@\n") .Append(" hello\n") .Append("+world\n") .Append("+!!!\n"); Assert.Equal(expected.ToString(), wrkDirToTree.Patch); } } [Fact] /* * $ git diff --cached * diff --git a/file.txt b/file.txt * index ce01362..94954ab 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1,2 @@ * hello * +world */ public void CanCompareASimpleTreeAgainstTheIndex() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { SetUpSimpleDiffContext(repo); TreeChanges changes = repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.Index); var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..94954ab 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,2 @@\n") .Append(" hello\n") .Append("+world\n"); Assert.Equal(expected.ToString(), changes.Patch); } } /* * $ git diff --cached * diff --git a/deleted_staged_file.txt b/deleted_staged_file.txt * deleted file mode 100644 * index 5605472..0000000 * --- a/deleted_staged_file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -things * diff --git a/modified_staged_file.txt b/modified_staged_file.txt * index 15d2ecc..e68bcc7 100644 * --- a/modified_staged_file.txt * +++ b/modified_staged_file.txt * @@ -1 +1,2 @@ * +a change * more files! * diff --git a/new_tracked_file.txt b/new_tracked_file.txt * new file mode 100644 * index 0000000..935a81d * --- /dev/null * +++ b/new_tracked_file.txt * @@ -0,0 +1 @@ * +a new file */ [Fact] public void CanCompareAMoreComplexTreeAgainstTheIndex() { using (var repo = new Repository(StandardTestRepoPath)) { Tree tree = repo.Head.Tip.Tree; TreeChanges changes = repo.Diff.Compare(tree, DiffTargets.Index); Assert.NotNull(changes); Assert.Equal(3, changes.Count()); Assert.Equal("deleted_staged_file.txt", changes.Deleted.Single().Path); Assert.Equal("new_tracked_file.txt", changes.Added.Single().Path); Assert.Equal("modified_staged_file.txt", changes.Modified.Single().Path); } } /* * $ git diff --cached -- "deleted_staged_file.txt" "1/branch_file.txt" "I-do/not-exist" * diff --git a/deleted_staged_file.txt b/deleted_staged_file.txt * deleted file mode 100644 * index 5605472..0000000 * --- a/deleted_staged_file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -things */ [Fact] public void CanCompareASubsetofTheTreeAgainstTheIndex() { using (var repo = new Repository(StandardTestRepoPath)) { Tree tree = repo.Head.Tip.Tree; TreeChanges changes = repo.Diff.Compare(tree, DiffTargets.Index, new[] { "deleted_staged_file.txt", "1/branch_file.txt", "I-do/not-exist" }); Assert.NotNull(changes); Assert.Equal(1, changes.Count()); Assert.Equal("deleted_staged_file.txt", changes.Deleted.Single().Path); } } [Fact] /* * $ git init . * $ echo -ne 'a' > file.txt * $ git add . * $ git commit -m "No line ending" * $ echo -ne '\n' >> file.txt * $ git add . * $ git diff --cached * diff --git a/file.txt b/file.txt * index 2e65efe..7898192 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1 @@ * -a * \ No newline at end of file * +a */ public void CanCopeWithEndOfFileNewlineChanges() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { var fullpath = Path.Combine(repo.Info.WorkingDirectory, "file.txt"); File.WriteAllText(fullpath, "a"); repo.Index.Stage("file.txt"); repo.Commit("Add file without line ending", DummySignature, DummySignature); File.AppendAllText(fullpath, "\n"); repo.Index.Stage("file.txt"); TreeChanges changes = repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.Index); Assert.Equal(1, changes.Modified.Count()); Assert.Equal(1, changes.LinesAdded); Assert.Equal(1, changes.LinesDeleted); var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index 2e65efe..7898192 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1 @@\n") .Append("-a\n") .Append("\\ No newline at end of file\n") .Append("+a\n"); Assert.Equal(expected.ToString(), changes.Patch); } } [Fact] public void ComparingATreeInABareRepositoryAgainstTheWorkDirOrTheIndexThrows() { using (var repo = new Repository(BareTestRepoPath)) { Assert.Throws<BareRepositoryException>( () => repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory)); Assert.Throws<BareRepositoryException>( () => repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.Index)); Assert.Throws<BareRepositoryException>( () => repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory | DiffTargets.Index)); } } [Fact] public void CanCompareANullTreeAgainstTheIndex() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { SetUpSimpleDiffContext(repo); TreeChanges changes = repo.Diff.Compare(null, DiffTargets.Index); Assert.Equal(1, changes.Count()); Assert.Equal(1, changes.Added.Count()); Assert.Equal("file.txt", changes.Added.Single().Path); Assert.Equal(2, changes.Added.Single().LinesAdded); } } [Fact] public void CanCompareANullTreeAgainstTheWorkdir() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { SetUpSimpleDiffContext(repo); TreeChanges changes = repo.Diff.Compare(null, DiffTargets.WorkingDirectory); Assert.Equal(1, changes.Count()); Assert.Equal(1, changes.Added.Count()); Assert.Equal("file.txt", changes.Added.Single().Path); Assert.Equal(3, changes.Added.Single().LinesAdded); } } [Fact] public void CanCompareANullTreeAgainstTheWorkdirAndTheIndex() { var scd = BuildSelfCleaningDirectory(); using (var repo = Repository.Init(scd.RootedDirectoryPath)) { SetUpSimpleDiffContext(repo); TreeChanges changes = repo.Diff.Compare(null, DiffTargets.WorkingDirectory | DiffTargets.Index); Assert.Equal(1, changes.Count()); Assert.Equal(1, changes.Added.Count()); Assert.Equal("file.txt", changes.Added.Single().Path); Assert.Equal(3, changes.Added.Single().LinesAdded); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Security.Cryptography.Apple; using Internal.Cryptography; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS public partial class RSA : AsymmetricAlgorithm { public static new RSA Create() { return new RSAImplementation.RSASecurityTransforms(); } } #endif internal static partial class RSAImplementation { public sealed partial class RSASecurityTransforms : RSA { private SecKeyPair _keys; public RSASecurityTransforms() : this(2048) { } public RSASecurityTransforms(int keySize) { KeySize = keySize; } internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey) { SetKey(SecKeyPair.PublicOnly(publicKey)); } internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey) { SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey)); } public override KeySizes[] LegalKeySizes { get { return new KeySizes[] { // All values are in bits. // 1024 was achieved via experimentation. // 1024 and 1024+8 both generated successfully, 1024-8 produced errSecParam. new KeySizes(minSize: 1024, maxSize: 16384, skipSize: 8), }; } } public override int KeySize { get { return base.KeySize; } set { if (KeySize == value) return; // Set the KeySize before freeing the key so that an invalid value doesn't throw away the key base.KeySize = value; if (_keys != null) { _keys.Dispose(); _keys = null; } } } public override RSAParameters ExportParameters(bool includePrivateParameters) { SecKeyPair keys = GetKeys(); SafeSecKeyRefHandle keyHandle = includePrivateParameters ? keys.PrivateKey : keys.PublicKey; if (keyHandle == null) { throw new CryptographicException(SR.Cryptography_OpenInvalidHandle); } DerSequenceReader keyReader = Interop.AppleCrypto.SecKeyExport(keyHandle, includePrivateParameters); RSAParameters parameters = new RSAParameters(); if (includePrivateParameters) { keyReader.ReadPkcs8Blob(ref parameters); } else { // When exporting a key handle opened from a certificate, it seems to // export as a PKCS#1 blob instead of an X509 SubjectPublicKeyInfo blob. // So, check for that. if (keyReader.PeekTag() == (byte)DerSequenceReader.DerTag.Integer) { keyReader.ReadPkcs1PublicBlob(ref parameters); } else { keyReader.ReadSubjectPublicKeyInfo(ref parameters); } } return parameters; } public override void ImportParameters(RSAParameters parameters) { bool isPrivateKey = parameters.D != null; if (isPrivateKey) { // Start with the private key, in case some of the private key fields // don't match the public key fields. // // Public import should go off without a hitch. SafeSecKeyRefHandle privateKey = ImportKey(parameters); RSAParameters publicOnly = new RSAParameters { Modulus = parameters.Modulus, Exponent = parameters.Exponent, }; SafeSecKeyRefHandle publicKey; try { publicKey = ImportKey(publicOnly); } catch { privateKey.Dispose(); throw; } SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey)); } else { SafeSecKeyRefHandle publicKey = ImportKey(parameters); SetKey(SecKeyPair.PublicOnly(publicKey)); } } public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } return Interop.AppleCrypto.RsaEncrypt(GetKeys().PublicKey, data, padding); } public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { if (padding == null) { throw new ArgumentNullException(nameof(padding)); } return Interop.AppleCrypto.TryRsaEncrypt(GetKeys().PublicKey, data, destination, padding, out bytesWritten); } public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } return Interop.AppleCrypto.RsaDecrypt(keys.PrivateKey, data, padding); } public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { if (padding == null) { throw new ArgumentNullException(nameof(padding)); } SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } return Interop.AppleCrypto.TryRsaDecrypt(keys.PrivateKey, data, destination, padding, out bytesWritten); } public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw new CryptographicException(SR.Cryptography_InvalidPaddingMode); SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } int expectedSize; Interop.AppleCrypto.PAL_HashAlgorithm palAlgId = PalAlgorithmFromAlgorithmName(hashAlgorithm, out expectedSize); if (hash.Length != expectedSize) { // Windows: NTE_BAD_DATA ("Bad Data.") // OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length") throw new CryptographicException( SR.Format( SR.Cryptography_BadHashSize_ForAlgorithm, hash.Length, expectedSize, hashAlgorithm.Name)); } return Interop.AppleCrypto.GenerateSignature( keys.PrivateKey, hash, palAlgId); } public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } if (padding != RSASignaturePadding.Pkcs1) { throw new CryptographicException(SR.Cryptography_InvalidPaddingMode); } SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } Interop.AppleCrypto.PAL_HashAlgorithm palAlgId = PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize); if (hash.Length != expectedSize) { // Windows: NTE_BAD_DATA ("Bad Data.") // OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length") throw new CryptographicException( SR.Format( SR.Cryptography_BadHashSize_ForAlgorithm, hash.Length, expectedSize, hashAlgorithm.Name)); } return Interop.AppleCrypto.TryGenerateSignature(keys.PrivateKey, hash, destination, palAlgId, out bytesWritten); } public override bool VerifyHash( byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) { throw new ArgumentNullException(nameof(hash)); } if (signature == null) { throw new ArgumentNullException(nameof(signature)); } return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding); } public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } if (padding != RSASignaturePadding.Pkcs1) { throw new CryptographicException(SR.Cryptography_InvalidPaddingMode); } Interop.AppleCrypto.PAL_HashAlgorithm palAlgId = PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize); return Interop.AppleCrypto.VerifySignature(GetKeys().PublicKey, hash, signature, palAlgId); } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm); protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm); protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) => AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten); protected override void Dispose(bool disposing) { if (disposing) { if (_keys != null) { _keys.Dispose(); _keys = null; } } base.Dispose(disposing); } private static Interop.AppleCrypto.PAL_HashAlgorithm PalAlgorithmFromAlgorithmName( HashAlgorithmName hashAlgorithmName, out int hashSizeInBytes) { if (hashAlgorithmName == HashAlgorithmName.MD5) { hashSizeInBytes = 128 >> 3; return Interop.AppleCrypto.PAL_HashAlgorithm.Md5; } else if (hashAlgorithmName == HashAlgorithmName.SHA1) { hashSizeInBytes = 160 >> 3; return Interop.AppleCrypto.PAL_HashAlgorithm.Sha1; } else if (hashAlgorithmName == HashAlgorithmName.SHA256) { hashSizeInBytes = 256 >> 3; return Interop.AppleCrypto.PAL_HashAlgorithm.Sha256; } else if (hashAlgorithmName == HashAlgorithmName.SHA384) { hashSizeInBytes = 384 >> 3; return Interop.AppleCrypto.PAL_HashAlgorithm.Sha384; } else if (hashAlgorithmName == HashAlgorithmName.SHA512) { hashSizeInBytes = 512 >> 3; return Interop.AppleCrypto.PAL_HashAlgorithm.Sha512; } throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name); } internal SecKeyPair GetKeys() { SecKeyPair current = _keys; if (current != null) { return current; } SafeSecKeyRefHandle publicKey; SafeSecKeyRefHandle privateKey; Interop.AppleCrypto.RsaGenerateKey(KeySizeValue, out publicKey, out privateKey); current = SecKeyPair.PublicPrivatePair(publicKey, privateKey); _keys = current; return current; } private void SetKey(SecKeyPair newKeyPair) { SecKeyPair current = _keys; _keys = newKeyPair; current?.Dispose(); if (newKeyPair != null) { KeySizeValue = Interop.AppleCrypto.GetSimpleKeySizeInBits(newKeyPair.PublicKey); } } private static SafeSecKeyRefHandle ImportKey(RSAParameters parameters) { bool isPrivateKey = parameters.D != null; byte[] pkcs1Blob = isPrivateKey ? parameters.ToPkcs1Blob() : parameters.ToSubjectPublicKeyInfo(); return Interop.AppleCrypto.ImportEphemeralKey(pkcs1Blob, isPrivateKey); } } private static Exception HashAlgorithmNameNullOrEmpty() => new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } internal static class RsaKeyBlobHelpers { private const string RsaOid = "1.2.840.113549.1.1.1"; // The PKCS#1 version blob for an RSA key based on 2 primes. private static readonly byte[] s_versionNumberBytes = { 0 }; // The AlgorithmIdentifier structure for RSA contains an explicit NULL, for legacy/compat reasons. private static readonly byte[][] s_encodedRsaAlgorithmIdentifier = DerEncoder.ConstructSegmentedSequence( DerEncoder.SegmentedEncodeOid(new Oid(RsaOid)), // DER:NULL (0x05 0x00) new byte[][] { new byte[] { (byte)DerSequenceReader.DerTag.Null }, new byte[] { 0 }, Array.Empty<byte>(), }); internal static byte[] ToPkcs1Blob(this RSAParameters parameters) { if (parameters.Exponent == null || parameters.Modulus == null) throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); if (parameters.D == null) { if (parameters.P != null || parameters.DP != null || parameters.Q != null || parameters.DQ != null || parameters.InverseQ != null) { throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); } return DerEncoder.ConstructSequence( DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Modulus), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Exponent)); } if (parameters.P == null || parameters.DP == null || parameters.Q == null || parameters.DQ == null || parameters.InverseQ == null) { throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); } return DerEncoder.ConstructSequence( DerEncoder.SegmentedEncodeUnsignedInteger(s_versionNumberBytes), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Modulus), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Exponent), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.D), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.P), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Q), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.DP), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.DQ), DerEncoder.SegmentedEncodeUnsignedInteger(parameters.InverseQ)); } internal static void ReadPkcs8Blob(this DerSequenceReader reader, ref RSAParameters parameters) { // OneAsymmetricKey ::= SEQUENCE { // version Version, // privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, // privateKey PrivateKey, // attributes [0] Attributes OPTIONAL, // ..., // [[2: publicKey [1] PublicKey OPTIONAL ]], // ... // } // // PrivateKeyInfo ::= OneAsymmetricKey // // PrivateKey ::= OCTET STRING int version = reader.ReadInteger(); // We understand both version 0 and 1 formats, // which are now known as v1 and v2, respectively. if (version > 1) { throw new CryptographicException(); } { // Ensure we're reading RSA DerSequenceReader algorithm = reader.ReadSequence(); string algorithmOid = algorithm.ReadOidAsString(); if (algorithmOid != RsaOid) { throw new CryptographicException(); } } byte[] privateKeyBytes = reader.ReadOctetString(); // Because this was an RSA private key, the key format is PKCS#1. ReadPkcs1PrivateBlob(privateKeyBytes, ref parameters); // We don't care about the rest of the blob here, but it's expected to not exist. } internal static byte[] ToSubjectPublicKeyInfo(this RSAParameters parameters) { Debug.Assert(parameters.D == null); // SubjectPublicKeyInfo::= SEQUENCE { // algorithm AlgorithmIdentifier, // subjectPublicKey BIT STRING } return DerEncoder.ConstructSequence( s_encodedRsaAlgorithmIdentifier, DerEncoder.SegmentedEncodeBitString( parameters.ToPkcs1Blob())); } internal static void ReadSubjectPublicKeyInfo(this DerSequenceReader keyInfo, ref RSAParameters parameters) { // SubjectPublicKeyInfo::= SEQUENCE { // algorithm AlgorithmIdentifier, // subjectPublicKey BIT STRING } DerSequenceReader algorithm = keyInfo.ReadSequence(); string algorithmOid = algorithm.ReadOidAsString(); if (algorithmOid != RsaOid) { throw new CryptographicException(); } byte[] subjectPublicKeyBytes = keyInfo.ReadBitString(); DerSequenceReader subjectPublicKey = new DerSequenceReader(subjectPublicKeyBytes); subjectPublicKey.ReadPkcs1PublicBlob(ref parameters); } internal static void ReadPkcs1PublicBlob(this DerSequenceReader subjectPublicKey, ref RSAParameters parameters) { parameters.Modulus = KeyBlobHelpers.TrimPaddingByte(subjectPublicKey.ReadIntegerBytes()); parameters.Exponent = KeyBlobHelpers.TrimPaddingByte(subjectPublicKey.ReadIntegerBytes()); if (subjectPublicKey.HasData) throw new CryptographicException(); } private static void ReadPkcs1PrivateBlob(byte[] privateKeyBytes, ref RSAParameters parameters) { // RSAPrivateKey::= SEQUENCE { // version Version, // modulus INTEGER, --n // publicExponent INTEGER, --e // privateExponent INTEGER, --d // prime1 INTEGER, --p // prime2 INTEGER, --q // exponent1 INTEGER, --d mod(p - 1) // exponent2 INTEGER, --d mod(q - 1) // coefficient INTEGER, --(inverse of q) mod p // otherPrimeInfos OtherPrimeInfos OPTIONAL // } DerSequenceReader privateKey = new DerSequenceReader(privateKeyBytes); int version = privateKey.ReadInteger(); if (version != 0) { throw new CryptographicException(); } parameters.Modulus = KeyBlobHelpers.TrimPaddingByte(privateKey.ReadIntegerBytes()); parameters.Exponent = KeyBlobHelpers.TrimPaddingByte(privateKey.ReadIntegerBytes()); int modulusLen = parameters.Modulus.Length; // Add one so that odd byte-length values (RSA 1032) get padded correctly. int halfModulus = (modulusLen + 1) / 2; parameters.D = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), modulusLen); parameters.P = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus); parameters.Q = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus); parameters.DP = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus); parameters.DQ = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus); parameters.InverseQ = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus); if (privateKey.HasData) { throw new CryptographicException(); } } } }
using Microsoft.Extensions.Configuration; using nHydrate.Generator.Common; using nHydrate.Generator.Common.Util; using nHydrate.ModelManagement; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace nHydrate.Command.Core { class Program { private const string ModelKey = "model"; private const string OutputKey = "output"; private const string GeneratorsKey = "generators"; private static GenStats _stats = new GenStats(); /* --model=C:\code\nHydrateTestAug\ConsoleApp1\Model1.nhydrate --output=C:\code\nHydrateTestAug --generators=nHydrate.Generator.EFCodeFirstNetCore.EFCodeFirstNetCoreProjectGenerator,nHydrate.Generator.PostgresInstaller.PostgresDatabaseProjectGenerator,nHydrate.Generator.SQLInstaller.Core.DatabaseProjectGenerator */ static int Main(string[] args) { IConfiguration Configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true) .AddCommandLine(args) .Build(); var modelFile = string.Empty; var output = string.Empty; var generators = new string[0]; //AppSettings var allValues = Configuration.GetChildren().Select(x => new { x.Key, x.Value }).ToDictionary(x => x.Key.ToString(), x => x.Value?.ToString()); if (allValues.ContainsKey(ModelKey)) modelFile = allValues[ModelKey]; if (allValues.ContainsKey(OutputKey)) output = allValues[OutputKey]; if (allValues.ContainsKey(GeneratorsKey)) generators = allValues[GeneratorsKey].Split(",", StringSplitOptions.RemoveEmptyEntries); if (modelFile.IsEmpty()) return ShowError("The model is required."); if (output.IsEmpty()) return ShowError("The output folder is required."); //If there are no generators specified on the command line then check for the file "nhydrate.generators" if (!generators.Any()) { var folderName = (new FileInfo(modelFile)).DirectoryName; var genDefFile = Path.Combine(folderName, "nhydrate.generators"); if (File.Exists(genDefFile)) generators = File.ReadAllLines(genDefFile).Where(x => x.Trim() != string.Empty).ToArray(); if (!generators.Any()) return ShowError("The generators are required."); } Console.WriteLine($"modelFile='{modelFile}'"); Console.WriteLine($"output='{output}'"); Console.WriteLine($"generators='{string.Join(",", generators)}'"); //NOTE: Yaml Model files must end with ".nhydrate.yaml" //Old Xml file ends with ".nhydrate" //Specified a folder so look for the file string actualFile = null; if (Directory.Exists(modelFile)) { var folderName = modelFile; //Look for new Yaml file var f = Directory.GetFiles(folderName, "*" + FileManagement.ModelExtension).FirstOrDefault(); if (File.Exists(f)) actualFile = f; //Look for old xml file if (actualFile.IsEmpty()) { f = Directory.GetFiles(folderName, "*" + FileManagement.OldModelExtension).FirstOrDefault(); if (File.Exists(f)) actualFile = f; } if (actualFile.IsEmpty()) { //Back 1 folder folderName = (new DirectoryInfo(folderName)).Parent.FullName; f = Directory.GetFiles(folderName, "*" + FileManagement.ModelExtension).FirstOrDefault(); if (File.Exists(f)) actualFile = f; //Look for old xml file if (actualFile.IsEmpty()) { f = Directory.GetFiles(folderName, "*" + FileManagement.OldModelExtension).FirstOrDefault(); if (File.Exists(f)) actualFile = f; } } } else { //Is this the Yaml model? if (modelFile.EndsWith(FileManagement.ModelExtension)) actualFile = modelFile; //Is this the Xml model? if (modelFile.EndsWith(FileManagement.OldModelExtension)) actualFile = modelFile; //Look one folder back for Yaml if (actualFile.IsEmpty()) { var folderName = (new FileInfo(modelFile)).Directory.Parent.FullName; var f = Directory.GetFiles(folderName, "*" + FileManagement.ModelExtension).FirstOrDefault(); if (File.Exists(f)) actualFile = f; } } if (actualFile.IsEmpty()) return ShowError("Model file not found."); modelFile = actualFile; var timer = System.Diagnostics.Stopwatch.StartNew(); var formatModel = (allValues.ContainsKey("formatmodel") && allValues["formatmodel"] == "true"); //TODO: when model files missing ID, it generates all fields as first one nHydrate.Generator.Common.Models.ModelRoot model = null; try { Console.WriteLine(); Console.WriteLine("Loading model..."); model = ModelHelper.CreatePOCOModel(modelFile, formatModel); } catch (ModelException ex) { //All YAML validation errors will come here Console.WriteLine(ex.Message); return 1; } catch (Exception ex) { Console.WriteLine("Unknown error."); return 1; } //Generate if (model != null && !formatModel) { Console.WriteLine("Loading generators..."); var genHelper = new nHydrate.Command.Core.GeneratorHelper(output); genHelper.ProjectItemGenerated += new nHydrate.Generator.Common.GeneratorFramework.ProjectItemGeneratedEventHandler(g_ProjectItemGenerated); var genList = new List<nHydrateGeneratorProject>(); var genProject = new nHydrateGeneratorProject(); genList.Add(genProject); model.ResetKey(model.Key); model.GeneratorProject = genProject; genProject.Model = model; genProject.FileName = $"{modelFile}.generating"; var document = new System.Xml.XmlDocument(); document.LoadXml($"<modelRoot guid=\"{model.Key}\" type=\"nHydrate.Generator.nHydrateGeneratorProject\" assembly=\"nHydrate.Generator.dll\"><ModelRoot></ModelRoot></modelRoot>"); ((nHydrate.Generator.Common.GeneratorFramework.IXMLable)model).XmlAppend(document.DocumentElement.ChildNodes[0]); System.IO.File.WriteAllText(genProject.FileName, document.ToIndentedString()); var allgenerators = genHelper.GetProjectGenerators(genProject); var excludeList = allgenerators.Where(x => !generators.Contains(x.FullName)).ToList(); //Get the last version we generated on this machine //We will use this to determine if any other generations have been performed on other machines var cacheFile = new nHydrate.Generator.Common.ModelCacheFile(genList.First()); var cachedGeneratedVersion = cacheFile.GeneratedVersion; var generatedVersion = cachedGeneratedVersion + 1; model.GeneratedVersion = generatedVersion; Console.WriteLine($"Generating code..."); foreach (var item in genList) { genHelper.GenerateAll(item, excludeList); } //Save local copy of last generated version cacheFile.GeneratedVersion = generatedVersion; cacheFile.ModelerVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; cacheFile.Save(); if (File.Exists(genProject.FileName)) File.Delete(genProject.FileName); //Write stats Console.WriteLine(); Console.WriteLine("Generation Summary"); Console.WriteLine($"Total Files: {_stats.ProcessedFileCount}"); Console.WriteLine($"Files Success: {_stats.FilesSuccess}"); Console.WriteLine($"Files Skipped: {_stats.FilesSkipped}"); Console.WriteLine($"Files Failed: {_stats.FilesFailed}"); Console.WriteLine(); } else if (!formatModel) { Console.WriteLine("The model could not be loaded."); } timer.Stop(); Console.WriteLine($"Generation complete. Elapsed={timer.ElapsedMilliseconds}ms"); return 0; } private static int ShowError(string message) { Console.WriteLine(message); return 1; } private static void g_ProjectItemGenerated(object sender, nHydrate.Generator.Common.EventArgs.ProjectItemGeneratedEventArgs e) { _stats.ProcessedFileCount++; if (e.FileState == FileStateConstants.Skipped) _stats.FilesSkipped++; if (e.FileState == FileStateConstants.Success) _stats.FilesSuccess++; if (e.FileState == FileStateConstants.Failed) _stats.FilesFailed++; _stats.GeneratedFileList.Add(e); Console.WriteLine($"Generated File: {e.FullName} ({e.FileState})"); } private class GenStats { public int ProcessedFileCount { get; set; } public int FilesSkipped { get; set; } public int FilesSuccess { get; set; } public int FilesFailed { get; set; } public List<nHydrate.Generator.Common.EventArgs.ProjectItemGeneratedEventArgs> GeneratedFileList { get; private set; } = new List<Generator.Common.EventArgs.ProjectItemGeneratedEventArgs>(); } } }
// 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. #if NETFRAMEWORK_4_0 // File System.Web.HttpBrowserCapabilitiesBase.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 { abstract public partial class HttpBrowserCapabilitiesBase : System.Web.UI.IFilterResolutionService { #region Methods and constructors public virtual new void AddBrowser (string browserName) { } public virtual new int CompareFilters (string filter1, string filter2) { return default(int); } public virtual new System.Web.UI.HtmlTextWriter CreateHtmlTextWriter (TextWriter w) { return default(System.Web.UI.HtmlTextWriter); } public virtual new void DisableOptimizedCacheKey () { } public virtual new bool EvaluateFilter (string filterName) { return default(bool); } public virtual new Version[] GetClrVersions () { return default(Version[]); } protected HttpBrowserCapabilitiesBase () { } public virtual new bool IsBrowser (string browserName) { return default(bool); } #endregion #region Properties and indexers public virtual new bool ActiveXControls { get { return default(bool); } } public virtual new System.Collections.IDictionary Adapters { get { return default(System.Collections.IDictionary); } } public virtual new bool AOL { get { return default(bool); } } public virtual new bool BackgroundSounds { get { return default(bool); } } public virtual new bool Beta { get { return default(bool); } } public virtual new string Browser { get { return default(string); } } public virtual new System.Collections.ArrayList Browsers { get { return default(System.Collections.ArrayList); } } public virtual new bool CanCombineFormsInDeck { get { return default(bool); } } public virtual new bool CanInitiateVoiceCall { get { return default(bool); } } public virtual new bool CanRenderAfterInputOrSelectElement { get { return default(bool); } } public virtual new bool CanRenderEmptySelects { get { return default(bool); } } public virtual new bool CanRenderInputAndSelectElementsTogether { get { return default(bool); } } public virtual new bool CanRenderMixedSelects { get { return default(bool); } } public virtual new bool CanRenderOneventAndPrevElementsTogether { get { return default(bool); } } public virtual new bool CanRenderPostBackCards { get { return default(bool); } } public virtual new bool CanRenderSetvarZeroWithMultiSelectionList { get { return default(bool); } } public virtual new bool CanSendMail { get { return default(bool); } } public virtual new System.Collections.IDictionary Capabilities { get { return default(System.Collections.IDictionary); } set { } } public virtual new bool CDF { get { return default(bool); } } public virtual new Version ClrVersion { get { return default(Version); } } public virtual new bool Cookies { get { return default(bool); } } public virtual new bool Crawler { get { return default(bool); } } public virtual new int DefaultSubmitButtonLimit { get { return default(int); } } public virtual new Version EcmaScriptVersion { get { return default(Version); } } public virtual new bool Frames { get { return default(bool); } } public virtual new int GatewayMajorVersion { get { return default(int); } } public virtual new double GatewayMinorVersion { get { return default(double); } } public virtual new string GatewayVersion { get { return default(string); } } public virtual new bool HasBackButton { get { return default(bool); } } public virtual new bool HidesRightAlignedMultiselectScrollbars { get { return default(bool); } } public virtual new string HtmlTextWriter { get { return default(string); } set { } } public virtual new string Id { get { return default(string); } } public virtual new string InputType { get { return default(string); } } public virtual new bool IsColor { get { return default(bool); } } public virtual new bool IsMobileDevice { get { return default(bool); } } public virtual new string this [string key] { get { return default(string); } } public virtual new bool JavaApplets { get { return default(bool); } } public virtual new Version JScriptVersion { get { return default(Version); } } public virtual new int MajorVersion { get { return default(int); } } public virtual new int MaximumHrefLength { get { return default(int); } } public virtual new int MaximumRenderedPageSize { get { return default(int); } } public virtual new int MaximumSoftkeyLabelLength { get { return default(int); } } public virtual new double MinorVersion { get { return default(double); } } public virtual new string MinorVersionString { get { return default(string); } } public virtual new string MobileDeviceManufacturer { get { return default(string); } } public virtual new string MobileDeviceModel { get { return default(string); } } public virtual new Version MSDomVersion { get { return default(Version); } } public virtual new int NumberOfSoftkeys { get { return default(int); } } public virtual new string Platform { get { return default(string); } } public virtual new string PreferredImageMime { get { return default(string); } } public virtual new string PreferredRenderingMime { get { return default(string); } } public virtual new string PreferredRenderingType { get { return default(string); } } public virtual new string PreferredRequestEncoding { get { return default(string); } } public virtual new string PreferredResponseEncoding { get { return default(string); } } public virtual new bool RendersBreakBeforeWmlSelectAndInput { get { return default(bool); } } public virtual new bool RendersBreaksAfterHtmlLists { get { return default(bool); } } public virtual new bool RendersBreaksAfterWmlAnchor { get { return default(bool); } } public virtual new bool RendersBreaksAfterWmlInput { get { return default(bool); } } public virtual new bool RendersWmlDoAcceptsInline { get { return default(bool); } } public virtual new bool RendersWmlSelectsAsMenuCards { get { return default(bool); } } public virtual new string RequiredMetaTagNameValue { get { return default(string); } } public virtual new bool RequiresAttributeColonSubstitution { get { return default(bool); } } public virtual new bool RequiresContentTypeMetaTag { get { return default(bool); } } public virtual new bool RequiresControlStateInSession { get { return default(bool); } } public virtual new bool RequiresDBCSCharacter { get { return default(bool); } } public virtual new bool RequiresHtmlAdaptiveErrorReporting { get { return default(bool); } } public virtual new bool RequiresLeadingPageBreak { get { return default(bool); } } public virtual new bool RequiresNoBreakInFormatting { get { return default(bool); } } public virtual new bool RequiresOutputOptimization { get { return default(bool); } } public virtual new bool RequiresPhoneNumbersAsPlainText { get { return default(bool); } } public virtual new bool RequiresSpecialViewStateEncoding { get { return default(bool); } } public virtual new bool RequiresUniqueFilePathSuffix { get { return default(bool); } } public virtual new bool RequiresUniqueHtmlCheckboxNames { get { return default(bool); } } public virtual new bool RequiresUniqueHtmlInputNames { get { return default(bool); } } public virtual new bool RequiresUrlEncodedPostfieldValues { get { return default(bool); } } public virtual new int ScreenBitDepth { get { return default(int); } } public virtual new int ScreenCharactersHeight { get { return default(int); } } public virtual new int ScreenCharactersWidth { get { return default(int); } } public virtual new int ScreenPixelsHeight { get { return default(int); } } public virtual new int ScreenPixelsWidth { get { return default(int); } } public virtual new bool SupportsAccesskeyAttribute { get { return default(bool); } } public virtual new bool SupportsBodyColor { get { return default(bool); } } public virtual new bool SupportsBold { get { return default(bool); } } public virtual new bool SupportsCacheControlMetaTag { get { return default(bool); } } public virtual new bool SupportsCallback { get { return default(bool); } } public virtual new bool SupportsCss { get { return default(bool); } } public virtual new bool SupportsDivAlign { get { return default(bool); } } public virtual new bool SupportsDivNoWrap { get { return default(bool); } } public virtual new bool SupportsEmptyStringInCookieValue { get { return default(bool); } } public virtual new bool SupportsFontColor { get { return default(bool); } } public virtual new bool SupportsFontName { get { return default(bool); } } public virtual new bool SupportsFontSize { get { return default(bool); } } public virtual new bool SupportsImageSubmit { get { return default(bool); } } public virtual new bool SupportsIModeSymbols { get { return default(bool); } } public virtual new bool SupportsInputIStyle { get { return default(bool); } } public virtual new bool SupportsInputMode { get { return default(bool); } } public virtual new bool SupportsItalic { get { return default(bool); } } public virtual new bool SupportsJPhoneMultiMediaAttributes { get { return default(bool); } } public virtual new bool SupportsJPhoneSymbols { get { return default(bool); } } public virtual new bool SupportsQueryStringInFormAction { get { return default(bool); } } public virtual new bool SupportsRedirectWithCookie { get { return default(bool); } } public virtual new bool SupportsSelectMultiple { get { return default(bool); } } public virtual new bool SupportsUncheck { get { return default(bool); } } public virtual new bool SupportsXmlHttp { get { return default(bool); } } public virtual new bool Tables { get { return default(bool); } } public virtual new Type TagWriter { get { return default(Type); } } public virtual new string Type { get { return default(string); } } public virtual new bool UseOptimizedCacheKey { get { return default(bool); } } public virtual new bool VBScript { get { return default(bool); } } public virtual new string Version { get { return default(string); } } public virtual new System.Version W3CDomVersion { get { return default(System.Version); } } public virtual new bool Win16 { get { return default(bool); } } public virtual new bool Win32 { get { return default(bool); } } #endregion } } #endif
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // 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.Diagnostics; using System.Reflection; using System.Threading; using System.Globalization; using System.IO; using NUnit.Framework.Constraints; using NUnit.Framework.Internal.Execution; using NUnit.Framework.Interfaces; #if !NETSTANDARD1_3 && !NETSTANDARD1_6 using System.Security.Principal; #endif #if ASYNC using System.Threading.Tasks; #endif namespace NUnit.Framework.Internal { /// <summary> /// Summary description for TestExecutionContextTests. /// </summary> [TestFixture][Property("Question", "Why?")] public class TestExecutionContextTests { private TestExecutionContext _fixtureContext; private TestExecutionContext _setupContext; private ResultState _fixtureResult; #if !NETSTANDARD1_3 && !NETSTANDARD1_6 string originalDirectory; IPrincipal originalPrincipal; #endif DateTime _fixtureCreateTime = DateTime.UtcNow; long _fixtureCreateTicks = Stopwatch.GetTimestamp(); [OneTimeSetUp] public void OneTimeSetUp() { _fixtureContext = TestExecutionContext.CurrentContext; _fixtureResult = _fixtureContext.CurrentResult.ResultState; } [OneTimeTearDown] public void OneTimeTearDown() { // TODO: We put some tests in one time teardown to verify that // the context is still valid. It would be better if these tests // were placed in a second-level test, invoked from this test class. TestExecutionContext ec = TestExecutionContext.CurrentContext; Assert.That(ec.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); Assert.That(ec.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); Assert.That(_fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); Assert.That(_fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } [SetUp] public void Initialize() { _setupContext = TestExecutionContext.CurrentContext; #if !NETSTANDARD1_3 && !NETSTANDARD1_6 originalCulture = CultureInfo.CurrentCulture; originalUICulture = CultureInfo.CurrentUICulture; originalDirectory = Environment.CurrentDirectory; originalPrincipal = Thread.CurrentPrincipal; #endif } [TearDown] public void Cleanup() { #if !NETSTANDARD1_3 && !NETSTANDARD1_6 Thread.CurrentThread.CurrentCulture = originalCulture; Thread.CurrentThread.CurrentUICulture = originalUICulture; #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_6 Environment.CurrentDirectory = originalDirectory; Thread.CurrentPrincipal = originalPrincipal; #endif Assert.That( TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo(_setupContext.CurrentTest.FullName), "Context at TearDown failed to match that saved from SetUp"); Assert.That( TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo(_setupContext.CurrentResult.Name), "Cannot access CurrentResult in TearDown"); } #region CurrentContext #if ASYNC [Test] public async Task CurrentContextFlowsWithAsyncExecution() { var context = TestExecutionContext.CurrentContext; await YieldAsync(); Assert.AreSame(context, TestExecutionContext.CurrentContext); } [Test] public async Task CurrentContextFlowsWithParallelAsyncExecution() { var expected = TestExecutionContext.CurrentContext; var parallelResult = await WhenAllAsync(YieldAndReturnContext(), YieldAndReturnContext()); Assert.AreSame(expected, TestExecutionContext.CurrentContext); Assert.AreSame(expected, parallelResult[0]); Assert.AreSame(expected, parallelResult[1]); } #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [Test] public void CurrentContextFlowsToUserCreatedThread() { TestExecutionContext threadContext = null; Thread thread = new Thread(() => { threadContext = TestExecutionContext.CurrentContext; }); thread.Start(); thread.Join(); Assert.That(threadContext, Is.Not.Null.And.SameAs(TestExecutionContext.CurrentContext)); } #endif #endregion #region CurrentTest [Test] public void FixtureSetUpCanAccessFixtureName() { Assert.That(_fixtureContext.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); } [Test] public void FixtureSetUpCanAccessFixtureFullName() { Assert.That(_fixtureContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); } [Test] public void FixtureSetUpHasNullMethodName() { Assert.That(_fixtureContext.CurrentTest.MethodName, Is.Null); } [Test] public void FixtureSetUpCanAccessFixtureId() { Assert.That(_fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] public void FixtureSetUpCanAccessFixtureProperties() { Assert.That(_fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } [Test] public void SetUpCanAccessTestName() { Assert.That(_setupContext.CurrentTest.Name, Is.EqualTo("SetUpCanAccessTestName")); } [Test] public void SetUpCanAccessTestFullName() { Assert.That(_setupContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.SetUpCanAccessTestFullName")); } [Test] public void SetUpCanAccessTestMethodName() { Assert.That(_setupContext.CurrentTest.MethodName, Is.EqualTo("SetUpCanAccessTestMethodName")); } [Test] public void SetUpCanAccessTestId() { Assert.That(_setupContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public void SetUpCanAccessTestProperties() { Assert.That(_setupContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [Test] public void TestCanAccessItsOwnName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("TestCanAccessItsOwnName")); } [Test] public void TestCanAccessItsOwnFullName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.TestCanAccessItsOwnFullName")); } [Test] public void TestCanAccessItsOwnMethodName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName, Is.EqualTo("TestCanAccessItsOwnMethodName")); } [Test] public void TestCanAccessItsOwnId() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public void TestCanAccessItsOwnProperties() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [TestCase(123, "abc")] public void TestCanAccessItsOwnArguments(int i, string s) { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"})); } #if ASYNC [Test] public async Task AsyncTestCanAccessItsOwnName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("AsyncTestCanAccessItsOwnName")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("AsyncTestCanAccessItsOwnName")); } [Test] public async Task AsyncTestCanAccessItsOwnFullName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.AsyncTestCanAccessItsOwnFullName")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.AsyncTestCanAccessItsOwnFullName")); } [Test] public async Task AsyncTestCanAccessItsOwnMethodName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName, Is.EqualTo("AsyncTestCanAccessItsOwnMethodName")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName, Is.EqualTo("AsyncTestCanAccessItsOwnMethodName")); } [Test] public async Task AsyncTestCanAccessItsOwnId() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public async Task AsyncTestCanAccessItsOwnProperties() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [TestCase(123, "abc")] public async Task AsyncTestCanAccessItsOwnArguments(int i, string s) { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"})); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"})); } #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [Test] public void TestHasWorkerWhenParallel() { var worker = TestExecutionContext.CurrentContext.TestWorker; var isRunningUnderTestWorker = TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher; Assert.That(worker != null || !isRunningUnderTestWorker); } #endif #endregion #region CurrentResult [Test] public void CanAccessResultName() { Assert.That(_fixtureContext.CurrentResult.Name, Is.EqualTo("TestExecutionContextTests")); Assert.That(_setupContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName")); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName")); } [Test] public void CanAccessResultFullName() { Assert.That(_fixtureContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); Assert.That(_setupContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName")); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName")); } [Test] public void CanAccessResultTest() { Assert.That(_fixtureContext.CurrentResult.Test, Is.SameAs(_fixtureContext.CurrentTest)); Assert.That(_setupContext.CurrentResult.Test, Is.SameAs(_setupContext.CurrentTest)); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test, Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest)); } [Test] public void CanAccessResultState() { // This is copied in setup because it can change if any test fails Assert.That(_fixtureResult, Is.EqualTo(ResultState.Success)); Assert.That(_setupContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); } #if ASYNC [Test] public async Task CanAccessResultName_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName_Async")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName_Async")); } [Test] public async Task CanAccessResultFullName_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName_Async")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName_Async")); } [Test] public async Task CanAccessResultTest_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test, Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test, Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest)); } [Test] public async Task CanAccessResultState_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); } #endif #endregion #region StartTime [Test] public void CanAccessStartTime() { Assert.That(_fixtureContext.StartTime, Is.GreaterThan(DateTime.MinValue).And.LessThanOrEqualTo(_fixtureCreateTime)); Assert.That(_setupContext.StartTime, Is.GreaterThanOrEqualTo(_fixtureContext.StartTime)); Assert.That(TestExecutionContext.CurrentContext.StartTime, Is.GreaterThanOrEqualTo(_setupContext.StartTime)); } #if ASYNC [Test] public async Task CanAccessStartTime_Async() { var startTime = TestExecutionContext.CurrentContext.StartTime; Assert.That(startTime, Is.GreaterThanOrEqualTo(_setupContext.StartTime)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.StartTime, Is.EqualTo(startTime)); } #endif #endregion #region StartTicks [Test] public void CanAccessStartTicks() { Assert.That(_fixtureContext.StartTicks, Is.LessThanOrEqualTo(_fixtureCreateTicks)); Assert.That(_setupContext.StartTicks, Is.GreaterThanOrEqualTo(_fixtureContext.StartTicks)); Assert.That(TestExecutionContext.CurrentContext.StartTicks, Is.GreaterThanOrEqualTo(_setupContext.StartTicks)); } #if ASYNC [Test] public async Task AsyncTestCanAccessStartTicks() { var startTicks = TestExecutionContext.CurrentContext.StartTicks; Assert.That(startTicks, Is.GreaterThanOrEqualTo(_setupContext.StartTicks)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.StartTicks, Is.EqualTo(startTicks)); } #endif #endregion #region OutWriter [Test] public void CanAccessOutWriter() { Assert.That(_fixtureContext.OutWriter, Is.Not.Null); Assert.That(_setupContext.OutWriter, Is.Not.Null); Assert.That(TestExecutionContext.CurrentContext.OutWriter, Is.SameAs(_setupContext.OutWriter)); } #if ASYNC [Test] public async Task AsyncTestCanAccessOutWriter() { var outWriter = TestExecutionContext.CurrentContext.OutWriter; Assert.That(outWriter, Is.SameAs(_setupContext.OutWriter)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.OutWriter, Is.SameAs(outWriter)); } #endif #endregion #region TestObject [Test] public void CanAccessTestObject() { Assert.That(_fixtureContext.TestObject, Is.Not.Null.And.TypeOf(GetType())); Assert.That(_setupContext.TestObject, Is.SameAs(_fixtureContext.TestObject)); Assert.That(TestExecutionContext.CurrentContext.TestObject, Is.SameAs(_setupContext.TestObject)); } #if ASYNC [Test] public async Task CanAccessTestObject_Async() { var testObject = TestExecutionContext.CurrentContext.TestObject; Assert.That(testObject, Is.SameAs(_setupContext.TestObject)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.TestObject, Is.SameAs(testObject)); } #endif #endregion #region StopOnError [Test] public void CanAccessStopOnError() { Assert.That(_setupContext.StopOnError, Is.EqualTo(_fixtureContext.StopOnError)); Assert.That(TestExecutionContext.CurrentContext.StopOnError, Is.EqualTo(_setupContext.StopOnError)); } #if ASYNC [Test] public async Task CanAccessStopOnError_Async() { var stop = TestExecutionContext.CurrentContext.StopOnError; Assert.That(stop, Is.EqualTo(_setupContext.StopOnError)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.StopOnError, Is.EqualTo(stop)); } #endif #endregion #region Listener [Test] public void CanAccessListener() { Assert.That(_fixtureContext.Listener, Is.Not.Null); Assert.That(_setupContext.Listener, Is.SameAs(_fixtureContext.Listener)); Assert.That(TestExecutionContext.CurrentContext.Listener, Is.SameAs(_setupContext.Listener)); } #if ASYNC [Test] public async Task CanAccessListener_Async() { var listener = TestExecutionContext.CurrentContext.Listener; Assert.That(listener, Is.SameAs(_setupContext.Listener)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.Listener, Is.SameAs(listener)); } #endif #endregion #region Dispatcher [Test] public void CanAccessDispatcher() { Assert.That(_fixtureContext.RandomGenerator, Is.Not.Null); Assert.That(_setupContext.Dispatcher, Is.SameAs(_fixtureContext.Dispatcher)); Assert.That(TestExecutionContext.CurrentContext.Dispatcher, Is.SameAs(_setupContext.Dispatcher)); } #if ASYNC [Test] public async Task CanAccessDispatcher_Async() { var dispatcher = TestExecutionContext.CurrentContext.Dispatcher; Assert.That(dispatcher, Is.SameAs(_setupContext.Dispatcher)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.Dispatcher, Is.SameAs(dispatcher)); } #endif #endregion #region ParallelScope [Test] public void CanAccessParallelScope() { var scope = _fixtureContext.ParallelScope; Assert.That(_setupContext.ParallelScope, Is.EqualTo(scope)); Assert.That(TestExecutionContext.CurrentContext.ParallelScope, Is.EqualTo(scope)); } #if ASYNC [Test] public async Task CanAccessParallelScope_Async() { var scope = TestExecutionContext.CurrentContext.ParallelScope; Assert.That(scope, Is.EqualTo(_setupContext.ParallelScope)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.ParallelScope, Is.EqualTo(scope)); } #endif #endregion #region TestWorker #if PARALLEL [Test] public void CanAccessTestWorker() { if (TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher) { Assert.That(_fixtureContext.TestWorker, Is.Not.Null); Assert.That(_setupContext.TestWorker, Is.SameAs(_fixtureContext.TestWorker)); Assert.That(TestExecutionContext.CurrentContext.TestWorker, Is.SameAs(_setupContext.TestWorker)); } } #if ASYNC [Test] public async Task CanAccessTestWorker_Async() { var worker = TestExecutionContext.CurrentContext.TestWorker; Assert.That(worker, Is.SameAs(_setupContext.TestWorker)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.TestWorker, Is.SameAs(worker)); } #endif #endif #endregion #region RandomGenerator [Test] public void CanAccessRandomGenerator() { Assert.That(_fixtureContext.RandomGenerator, Is.Not.Null); Assert.That(_setupContext.RandomGenerator, Is.Not.Null); Assert.That(TestExecutionContext.CurrentContext.RandomGenerator, Is.SameAs(_setupContext.RandomGenerator)); } #if ASYNC [Test] public async Task CanAccessRandomGenerator_Async() { var random = TestExecutionContext.CurrentContext.RandomGenerator; Assert.That(random, Is.SameAs(_setupContext.RandomGenerator)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.RandomGenerator, Is.SameAs(random)); } #endif #endregion #region AssertCount [Test] public void CanAccessAssertCount() { Assert.That(_fixtureContext.AssertCount, Is.EqualTo(0)); Assert.That(_setupContext.AssertCount, Is.EqualTo(1)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(2)); Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(4)); } #if ASYNC [Test] public async Task CanAccessAssertCount_Async() { Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(1)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(2)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(3)); } #endif #endregion #region MultipleAssertLevel [Test] public void CanAccessMultipleAssertLevel() { Assert.That(_fixtureContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.That(_setupContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.Multiple(() => { Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(1)); }); } #if ASYNC [Test] public async Task CanAccessMultipleAssertLevel_Async() { Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.Multiple(() => { Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(1)); }); } #endif #endregion #region TestCaseTimeout [Test] public void CanAccessTestCaseTimeout() { var timeout = _fixtureContext.TestCaseTimeout; Assert.That(_setupContext.TestCaseTimeout, Is.EqualTo(timeout)); Assert.That(TestExecutionContext.CurrentContext.TestCaseTimeout, Is.EqualTo(timeout)); } #if ASYNC [Test] public async Task CanAccessTestCaseTimeout_Async() { var timeout = TestExecutionContext.CurrentContext.TestCaseTimeout; Assert.That(timeout, Is.EqualTo(_setupContext.TestCaseTimeout)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.TestCaseTimeout, Is.EqualTo(timeout)); } #endif #endregion #region UpstreamActions [Test] public void CanAccessUpstreamActions() { var actions = _fixtureContext.UpstreamActions; Assert.That(_setupContext.UpstreamActions, Is.EqualTo(actions)); Assert.That(TestExecutionContext.CurrentContext.UpstreamActions, Is.EqualTo(actions)); } #if ASYNC [Test] public async Task CanAccessUpstreamAcxtions_Async() { var actions = TestExecutionContext.CurrentContext.UpstreamActions; Assert.That(actions, Is.SameAs(_setupContext.UpstreamActions)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.UpstreamActions, Is.SameAs(actions)); } #endif #endregion #region CurrentCulture and CurrentUICulture #if !NETSTANDARD1_3 && !NETSTANDARD1_6 CultureInfo originalCulture; CultureInfo originalUICulture; [Test] public void CanAccessCurrentCulture() { Assert.That(_fixtureContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); Assert.That(_setupContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void CanAccessCurrentUICulture() { Assert.That(_fixtureContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); Assert.That(_setupContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } #if ASYNC [Test] public async Task CanAccessCurrentCulture_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public async Task CanAccessCurrentUICulture_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } #endif [Test] public void SetAndRestoreCurrentCulture() { var context = new TestExecutionContext(_setupContext); try { CultureInfo otherCulture = new CultureInfo(originalCulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentCulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentCulture, "Culture was not set"); Assert.AreEqual(otherCulture, context.CurrentCulture, "Culture not in new context"); Assert.AreEqual(_setupContext.CurrentCulture, originalCulture, "Original context should not change"); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture was not restored"); Assert.AreEqual(_setupContext.CurrentCulture, originalCulture, "Culture not in final context"); } [Test] public void SetAndRestoreCurrentUICulture() { var context = new TestExecutionContext(_setupContext); try { CultureInfo otherCulture = new CultureInfo(originalUICulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentUICulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentUICulture, "UICulture was not set"); Assert.AreEqual(otherCulture, context.CurrentUICulture, "UICulture not in new context"); Assert.AreEqual(_setupContext.CurrentUICulture, originalUICulture, "Original context should not change"); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentUICulture, originalUICulture, "UICulture was not restored"); Assert.AreEqual(_setupContext.CurrentUICulture, originalUICulture, "UICulture not in final context"); } #endif #endregion #region CurrentPrincipal #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [Test] public void CanAccessCurrentPrincipal() { Type expectedType = Thread.CurrentPrincipal.GetType(); Assert.That(_fixtureContext.CurrentPrincipal, Is.TypeOf(expectedType), "Fixture"); Assert.That(_setupContext.CurrentPrincipal, Is.TypeOf(expectedType), "SetUp"); Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.TypeOf(expectedType), "Test"); } #if ASYNC [Test] public async Task CanAccessCurrentPrincipal_Async() { Type expectedType = Thread.CurrentPrincipal.GetType(); Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.TypeOf(expectedType), "Before yield"); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.TypeOf(expectedType), "After yield"); } #endif [Test] public void SetAndRestoreCurrentPrincipal() { var context = new TestExecutionContext(_setupContext); try { GenericIdentity identity = new GenericIdentity("foo"); context.CurrentPrincipal = new GenericPrincipal(identity, new string[0]); Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name, "Principal was not set"); Assert.AreEqual("foo", context.CurrentPrincipal.Identity.Name, "Principal not in new context"); Assert.AreEqual(_setupContext.CurrentPrincipal, originalPrincipal, "Original context should not change"); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(Thread.CurrentPrincipal, originalPrincipal, "Principal was not restored"); Assert.AreEqual(_setupContext.CurrentPrincipal, originalPrincipal, "Principal not in final context"); } #endif #endregion #region ValueFormatter [Test] public void SetAndRestoreValueFormatter() { var context = new TestExecutionContext(_setupContext); var originalFormatter = context.CurrentValueFormatter; try { ValueFormatter f = val => "dummy"; context.AddFormatter(next => f); Assert.That(context.CurrentValueFormatter, Is.EqualTo(f)); context.EstablishExecutionEnvironment(); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("dummy")); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.That(TestExecutionContext.CurrentContext.CurrentValueFormatter, Is.EqualTo(originalFormatter)); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("123")); } #endregion #region SingleThreaded [Test] public void SingleThreadedDefaultsToFalse() { Assert.False(new TestExecutionContext().IsSingleThreaded); } [Test] public void SingleThreadedIsInherited() { var parent = new TestExecutionContext(); parent.IsSingleThreaded = true; Assert.True(new TestExecutionContext(parent).IsSingleThreaded); } #endregion #region ExecutionStatus [Test] public void ExecutionStatusIsPushedToHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); bottomContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(topContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } [Test] public void ExecutionStatusIsPulledFromHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); topContext.ExecutionStatus = TestExecutionStatus.AbortRequested; Assert.That(bottomContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.AbortRequested)); } [Test] public void ExecutionStatusIsPromulgatedAcrossBranches() { var topContext = new TestExecutionContext(); var leftContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); var rightContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); leftContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(rightContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } #endregion #region Cross-domain Tests #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [Test, Platform(Exclude="Mono", Reason="Intermittent failures")] public void CanCreateObjectInAppDomain() { AppDomain domain = AppDomain.CreateDomain( "TestCanCreateAppDomain", AppDomain.CurrentDomain.Evidence, AssemblyHelper.GetDirectoryName(Assembly.GetExecutingAssembly()), null, false); var obj = domain.CreateInstanceAndUnwrap("nunit.framework.tests", "NUnit.Framework.Internal.TestExecutionContextTests+TestClass"); Assert.NotNull(obj); } [Serializable] private class TestClass { } #endif #endregion #region Helper Methods #if ASYNC private async Task YieldAsync() { #if NET_4_0 await TaskEx.Yield(); #else await Task.Yield(); #endif } private Task<T[]> WhenAllAsync<T>(params Task<T>[] tasks) { #if NET_4_0 return TaskEx.WhenAll(tasks); #else return Task.WhenAll(tasks); #endif } private async Task<TestExecutionContext> YieldAndReturnContext() { await YieldAsync(); return TestExecutionContext.CurrentContext; } #endif #endregion } #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [TestFixture, Platform(Exclude="Mono", Reason="Intermittent failures")] public class TextExecutionContextInAppDomain { private RunsInAppDomain _runsInAppDomain; [SetUp] public void SetUp() { var domain = AppDomain.CreateDomain("TestDomain", null, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath, false); _runsInAppDomain = domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "NUnit.Framework.Internal.RunsInAppDomain") as RunsInAppDomain; Assert.That(_runsInAppDomain, Is.Not.Null); } [Test] [Description("Issue 71 - NUnit swallows console output from AppDomains created within tests")] public void CanWriteToConsoleInAppDomain() { _runsInAppDomain.WriteToConsole(); } [Test] [Description("Issue 210 - TestContext.WriteLine in an AppDomain causes an error")] public void CanWriteToTestContextInAppDomain() { _runsInAppDomain.WriteToTestContext(); } } internal class RunsInAppDomain : MarshalByRefObject { public void WriteToConsole() { Console.WriteLine("RunsInAppDomain.WriteToConsole"); } public void WriteToTestContext() { TestContext.WriteLine("RunsInAppDomain.WriteToTestContext"); } } #endif }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookTableColumnsCollectionRequest. /// </summary> public partial class WorkbookTableColumnsCollectionRequest : BaseRequest, IWorkbookTableColumnsCollectionRequest { /// <summary> /// Constructs a new WorkbookTableColumnsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookTableColumnsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified WorkbookTableColumn to the collection via POST. /// </summary> /// <param name="workbookTableColumn">The WorkbookTableColumn to add.</param> /// <returns>The created WorkbookTableColumn.</returns> public System.Threading.Tasks.Task<WorkbookTableColumn> AddAsync(WorkbookTableColumn workbookTableColumn) { return this.AddAsync(workbookTableColumn, CancellationToken.None); } /// <summary> /// Adds the specified WorkbookTableColumn to the collection via POST. /// </summary> /// <param name="workbookTableColumn">The WorkbookTableColumn to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookTableColumn.</returns> public System.Threading.Tasks.Task<WorkbookTableColumn> AddAsync(WorkbookTableColumn workbookTableColumn, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<WorkbookTableColumn>(workbookTableColumn, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IWorkbookTableColumnsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IWorkbookTableColumnsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<WorkbookTableColumnsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest Expand(Expression<Func<WorkbookTableColumn, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest Select(Expression<Func<WorkbookTableColumn, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableColumnsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// 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.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Primitives; using Xunit; namespace System.ComponentModel.Composition.AttributedModel { class ConcreteCPD : ComposablePartDefinition { public override ComposablePart CreatePart() { throw new NotImplementedException(); } public override IEnumerable<ExportDefinition> ExportDefinitions { get { throw new NotImplementedException(); } } public override IEnumerable<ImportDefinition> ImportDefinitions { get { throw new NotImplementedException(); } } } public class CPDTest { } public class AttributedModelServicesTests { [Fact] public void CreatePartDefinition1_NullAsType_ShouldThrowArgumentNull() { var origin = ElementFactory.Create(); Assert.Throws<ArgumentNullException>("type", () => { AttributedModelServices.CreatePartDefinition((Type)null, origin); }); } [Fact] public void CreatePartDefinition2_NullAsType_ShouldThrowArgumentNull() { var origin = ElementFactory.Create(); Assert.Throws<ArgumentNullException>("type", () => { AttributedModelServices.CreatePartDefinition((Type)null, origin, false); }); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.ArgumentException: ComposablePartDefinition of type 'System.ComponentModel.Composition.AttributedModel.ConcreteCPD' cannot be used in this context. Only part definitions produced by the ReflectionModelServices.CreatePartDefinition are supported. public void CreatePart_From_InvalidPartDefiniton_ShouldThrowArgumentException() { Assert.Throws<ArgumentException>("partDefinition", () => { try { var partDefinition = new ConcreteCPD(); var instance = new CPDTest(); var part = AttributedModelServices.CreatePart(partDefinition, instance); } catch (Exception e) { Console.WriteLine(e); throw; } }); } [Fact] public void Exports_Throws_OnNullPart() { ComposablePartDefinition part = null; Type contractType = typeof(IContract1); Assert.Throws<ArgumentNullException>("part", () => { part.Exports(contractType); }); } [Fact] public void Exports_Throws_OnNullContractType() { ComposablePartDefinition part = typeof(PartExportingContract1).AsPart(); Type contractType = null; Assert.Throws<ArgumentNullException>("contractType", () => { part.Exports(contractType); }); } [Fact] public void Exports() { ComposablePartDefinition part1 = typeof(PartExportingContract1).AsPart(); ComposablePartDefinition part2 = typeof(PartExportingContract2).AsPart(); Assert.True(part1.Exports(typeof(IContract1))); Assert.True(part2.Exports(typeof(IContract2))); Assert.False(part2.Exports(typeof(IContract1))); Assert.False(part1.Exports(typeof(IContract2))); } [Fact] public void ExportsGeneric_Throws_OnNullPart() { ComposablePartDefinition part = null; Assert.Throws<ArgumentNullException>("part", () => { part.Exports<IContract1>(); }); } [Fact] public void ExportsGeneric() { ComposablePartDefinition part1 = typeof(PartExportingContract1).AsPart(); ComposablePartDefinition part2 = typeof(PartExportingContract2).AsPart(); Assert.True(part1.Exports<IContract1>()); Assert.True(part2.Exports<IContract2>()); Assert.False(part2.Exports<IContract1>()); Assert.False(part1.Exports<IContract2>()); } [Fact] public void Imports_Throws_OnNullPart() { ComposablePartDefinition part = null; Type contractType = typeof(IContract1); Assert.Throws<ArgumentNullException>("part", () => { part.Imports(contractType); }); } [Fact] public void Imports_Throws_OnNullContractName() { ComposablePartDefinition part = typeof(PartImportingContract1).AsPart(); Type contractType = null; Assert.Throws<ArgumentNullException>("contractType", () => { part.Imports(contractType); }); } [Fact] public void Imports() { ComposablePartDefinition part1 = typeof(PartImportingContract1).AsPart(); ComposablePartDefinition part2 = typeof(PartImportingContract2).AsPart(); Assert.True(part1.Imports(typeof(IContract1))); Assert.True(part2.Imports(typeof(IContract2))); Assert.False(part2.Imports(typeof(IContract1))); Assert.False(part1.Imports(typeof(IContract2))); } [Fact] public void Imports_CardinalityIgnored_WhenNotSpecified() { ComposablePartDefinition part1 = typeof(PartImportingContract1).AsPart(); ComposablePartDefinition part1Multiple = typeof(PartImportingContract1Multiple).AsPart(); ComposablePartDefinition part1Optional = typeof(PartImportingContract1Optionally).AsPart(); Assert.True(part1.Imports(typeof(IContract1))); Assert.True(part1Optional.Imports(typeof(IContract1))); Assert.True(part1Multiple.Imports(typeof(IContract1))); } [Fact] public void Imports_CardinalityNotIgnored_WhenSpecified() { ComposablePartDefinition part1 = typeof(PartImportingContract1).AsPart(); ComposablePartDefinition part1Multiple = typeof(PartImportingContract1Multiple).AsPart(); ComposablePartDefinition part1Optional = typeof(PartImportingContract1Optionally).AsPart(); Assert.True(part1.Imports(typeof(IContract1), ImportCardinality.ExactlyOne)); Assert.False(part1.Imports(typeof(IContract1), ImportCardinality.ZeroOrMore)); Assert.False(part1.Imports(typeof(IContract1), ImportCardinality.ZeroOrOne)); Assert.False(part1Multiple.Imports(typeof(IContract1), ImportCardinality.ExactlyOne)); Assert.True(part1Multiple.Imports(typeof(IContract1), ImportCardinality.ZeroOrMore)); Assert.False(part1Multiple.Imports(typeof(IContract1), ImportCardinality.ZeroOrOne)); Assert.False(part1Optional.Imports(typeof(IContract1), ImportCardinality.ExactlyOne)); Assert.False(part1Optional.Imports(typeof(IContract1), ImportCardinality.ZeroOrMore)); Assert.True(part1Optional.Imports(typeof(IContract1), ImportCardinality.ZeroOrOne)); } [Fact] public void ImportsGeneric_Throws_OnNullPart() { ComposablePartDefinition part = null; Assert.Throws<ArgumentNullException>("part", () => { part.Imports<IContract1>(); }); } [Fact] public void ImportsGeneric() { ComposablePartDefinition part1 = typeof(PartImportingContract1).AsPart(); ComposablePartDefinition part2 = typeof(PartImportingContract2).AsPart(); Assert.True(part1.Imports<IContract1>()); Assert.True(part2.Imports<IContract2>()); Assert.False(part2.Imports<IContract1>()); Assert.False(part1.Imports<IContract2>()); } [Fact] public void ImportsGeneric_CardinalityIgnored_WhenNotSpecified() { ComposablePartDefinition part1 = typeof(PartImportingContract1).AsPart(); ComposablePartDefinition part1Multiple = typeof(PartImportingContract1Multiple).AsPart(); ComposablePartDefinition part1Optional = typeof(PartImportingContract1Optionally).AsPart(); Assert.True(part1.Imports<IContract1>()); Assert.True(part1Optional.Imports<IContract1>()); Assert.True(part1Multiple.Imports<IContract1>()); } [Fact] public void ImportsGeneric_CardinalityNotIgnored_WhenSpecified() { ComposablePartDefinition part1 = typeof(PartImportingContract1).AsPart(); ComposablePartDefinition part1Multiple = typeof(PartImportingContract1Multiple).AsPart(); ComposablePartDefinition part1Optional = typeof(PartImportingContract1Optionally).AsPart(); Assert.True(part1.Imports<IContract1>(ImportCardinality.ExactlyOne)); Assert.False(part1.Imports<IContract1>(ImportCardinality.ZeroOrMore)); Assert.False(part1.Imports<IContract1>(ImportCardinality.ZeroOrOne)); Assert.False(part1Multiple.Imports<IContract1>(ImportCardinality.ExactlyOne)); Assert.True(part1Multiple.Imports<IContract1>(ImportCardinality.ZeroOrMore)); Assert.False(part1Multiple.Imports<IContract1>(ImportCardinality.ZeroOrOne)); Assert.False(part1Optional.Imports<IContract1>(ImportCardinality.ExactlyOne)); Assert.False(part1Optional.Imports<IContract1>(ImportCardinality.ZeroOrMore)); Assert.True(part1Optional.Imports<IContract1>(ImportCardinality.ZeroOrOne)); } public interface IContract1 { } public interface IContract2 { } [Export(typeof(IContract1))] public class PartExportingContract1 : IContract1 { } [Export(typeof(IContract2))] public class PartExportingContract2 : IContract2 { } public class PartImportingContract1 { [Import] public IContract1 import; } public class PartImportingContract2 { [Import] public IContract2 import; } public class PartImportingContract1Optionally { [Import(AllowDefault = true)] public IContract1 import; } public class PartImportingContract1Multiple { [ImportMany] public IEnumerable<IContract1> import; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TokenApi.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 file="ViewgenContext.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Mapping.ViewGeneration { using System.Collections.Generic; using System.Data.Common.Utils; using System.Data.Entity; using System.Data.Mapping.ViewGeneration.QueryRewriting; using System.Data.Mapping.ViewGeneration.Structures; using System.Data.Mapping.ViewGeneration.Utils; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; using System.Text; internal class ViewgenContext : InternalBase { #region Fields private ConfigViewGenerator m_config; private ViewTarget m_viewTarget; // Extent for which the view is being generated private EntitySetBase m_extent; // Different maps for members private MemberMaps m_memberMaps; private EdmItemCollection m_edmItemCollection; private StorageEntityContainerMapping m_entityContainerMapping; // The normalized cells that are created private List<LeftCellWrapper> m_cellWrappers; // Implicit constraints between members in queries based on schema. E.g., p.Addr IS NOT NULL <=> p IS OF Customer private FragmentQueryProcessor m_leftFragmentQP; // In addition to constraints for each right extent contains constraints due to associations private FragmentQueryProcessor m_rightFragmentQP; private CqlIdentifiers m_identifiers; // Maps (left) queries to their rewritings in terms of views private Dictionary<FragmentQuery, Tile<FragmentQuery>> m_rewritingCache; #endregion #region Constructors internal ViewgenContext(ViewTarget viewTarget, EntitySetBase extent, IEnumerable<Cell> extentCells, CqlIdentifiers identifiers, ConfigViewGenerator config, MemberDomainMap queryDomainMap, MemberDomainMap updateDomainMap, StorageEntityContainerMapping entityContainerMapping) { foreach (Cell cell in extentCells) { Debug.Assert(extent.Equals(cell.GetLeftQuery(viewTarget).Extent)); Debug.Assert(cell.CQuery.NumProjectedSlots == cell.SQuery.NumProjectedSlots); } m_extent = extent; m_viewTarget = viewTarget; m_config = config; m_edmItemCollection = entityContainerMapping.StorageMappingItemCollection.EdmItemCollection; m_entityContainerMapping = entityContainerMapping; m_identifiers = identifiers; // create a copy of updateDomainMap so generation of query views later on is not affected // it is modified in QueryRewriter.AdjustMemberDomainsForUpdateViews updateDomainMap = updateDomainMap.MakeCopy(); // Create a signature generator that handles all the // multiconstant work and generating the signatures MemberDomainMap domainMap = viewTarget == ViewTarget.QueryView ? queryDomainMap : updateDomainMap; m_memberMaps = new MemberMaps(viewTarget, MemberProjectionIndex.Create(extent, m_edmItemCollection), queryDomainMap, updateDomainMap); // Create left fragment KB: includes constraints for the extent to be constructed FragmentQueryKB leftKB = new FragmentQueryKB(); leftKB.CreateVariableConstraints(extent, domainMap, m_edmItemCollection); m_leftFragmentQP = new FragmentQueryProcessor(leftKB); m_rewritingCache = new Dictionary<FragmentQuery, Tile<FragmentQuery>>( FragmentQuery.GetEqualityComparer(m_leftFragmentQP)); // Now using the signatures, create new cells such that // "extent's" query (C or S) is described in terms of multiconstants if (!CreateLeftCellWrappers(extentCells, viewTarget)) { return; } // Create right fragment KB: includes constraints for all extents and association roles of right queries FragmentQueryKB rightKB = new FragmentQueryKB(); MemberDomainMap rightDomainMap = viewTarget == ViewTarget.QueryView ? updateDomainMap : queryDomainMap; foreach (LeftCellWrapper leftCellWrapper in m_cellWrappers) { EntitySetBase rightExtent = leftCellWrapper.RightExtent; rightKB.CreateVariableConstraints(rightExtent, rightDomainMap, m_edmItemCollection); rightKB.CreateAssociationConstraints(rightExtent, rightDomainMap, m_edmItemCollection); } if (m_viewTarget == ViewTarget.UpdateView) { CreateConstraintsForForeignKeyAssociationsAffectingThisWarapper(rightKB, rightDomainMap); } m_rightFragmentQP = new FragmentQueryProcessor(rightKB); // Check for concurrency control tokens if (m_viewTarget == ViewTarget.QueryView) { CheckConcurrencyControlTokens(); } // For backward compatibility - // order wrappers by increasing domain size, decreasing number of attributes m_cellWrappers.Sort(LeftCellWrapper.Comparer); } /// <summary> /// Find the Foreign Key Associations that relate EntitySets used in these left cell wrappers and /// add any equivalence facts between sets implied by 1:1 associations. /// We can collect other implication facts but we don't have a scenario that needs them( yet ). /// </summary> /// <param name="rightKB"></param> /// <param name="rightDomainMap"></param> private void CreateConstraintsForForeignKeyAssociationsAffectingThisWarapper(FragmentQueryKB rightKB, MemberDomainMap rightDomainMap) { //First find the entity types of the sets in these cell wrappers. var entityTypes = m_cellWrappers.Select(it => it.RightExtent).OfType<EntitySet>().Select(it => it.ElementType); //Get all the foreign key association sets in these entity sets var allForeignKeyAssociationSets = this.m_entityContainerMapping.EdmEntityContainer.BaseEntitySets.OfType<AssociationSet>().Where(it => it.ElementType.IsForeignKey); //Find all the foreign key associations that have corresponding sets var oneToOneForeignKeyAssociationsForThisWrapper = allForeignKeyAssociationSets.Select(it => it.ElementType); //Find all the 1:1 associations from the above list oneToOneForeignKeyAssociationsForThisWrapper = oneToOneForeignKeyAssociationsForThisWrapper.Where(it => (it.AssociationEndMembers.All(endMember => endMember.RelationshipMultiplicity == RelationshipMultiplicity.One))); //Filter the 1:1 foreign key associations to the ones relating the sets used in these cell wrappers. oneToOneForeignKeyAssociationsForThisWrapper = oneToOneForeignKeyAssociationsForThisWrapper.Where(it => (it.AssociationEndMembers.All(endMember => entityTypes.Contains(endMember.GetEntityType())))); //filter foreign key association sets to the sets that are 1:1 and affecting this wrapper. var oneToOneForeignKeyAssociationSetsForThisWrapper = allForeignKeyAssociationSets.Where(it => oneToOneForeignKeyAssociationsForThisWrapper.Contains(it.ElementType)); //Collect the facts for the foreign key association sets that are 1:1 and affecting this wrapper foreach (var assocSet in oneToOneForeignKeyAssociationSetsForThisWrapper) { rightKB.CreateEquivalenceConstraintForOneToOneForeignKeyAssociation(assocSet, rightDomainMap, m_edmItemCollection); } } #endregion #region Properties internal ViewTarget ViewTarget { get { return m_viewTarget; } } internal MemberMaps MemberMaps { get { return m_memberMaps; } } // effects: Returns the extent for which the cells have been normalized internal EntitySetBase Extent { get { return m_extent; } } internal ConfigViewGenerator Config { get { return m_config; } } internal CqlIdentifiers CqlIdentifiers { get { return m_identifiers; } } internal EdmItemCollection EdmItemCollection { get { return m_edmItemCollection; } } internal FragmentQueryProcessor LeftFragmentQP { get { return m_leftFragmentQP; } } internal FragmentQueryProcessor RightFragmentQP { get { return m_rightFragmentQP; } } // effects: Returns all wrappers that were originally relevant for // this extent internal List<LeftCellWrapper> AllWrappersForExtent { get { return m_cellWrappers; } } internal StorageEntityContainerMapping EntityContainerMapping { get { return m_entityContainerMapping; } } #endregion #region InternalMethods // effects: Returns the cached rewriting of (left) queries in terms of views, if any internal bool TryGetCachedRewriting(FragmentQuery query, out Tile<FragmentQuery> rewriting) { return m_rewritingCache.TryGetValue(query, out rewriting); } // effects: Records the cached rewriting of (left) queries in terms of views internal void SetCachedRewriting(FragmentQuery query, Tile<FragmentQuery> rewriting) { m_rewritingCache[query] = rewriting; } #endregion #region Private Methods /// <summary> /// Checks: /// 1) Concurrency token is not defined in this Extent's ElementTypes' derived types /// 2) Members with concurrency token should not have conditions specified /// </summary> private void CheckConcurrencyControlTokens() { Debug.Assert(m_viewTarget == ViewTarget.QueryView); // Get the token fields for this extent EntityTypeBase extentType = m_extent.ElementType; Set<EdmMember> tokenMembers = MetadataHelper.GetConcurrencyMembersForTypeHierarchy(extentType, m_edmItemCollection); Set<MemberPath> tokenPaths = new Set<MemberPath>(MemberPath.EqualityComparer); foreach (EdmMember tokenMember in tokenMembers) { if (!tokenMember.DeclaringType.IsAssignableFrom(extentType)) { string message = System.Data.Entity.Strings.ViewGen_Concurrency_Derived_Class(tokenMember.Name, tokenMember.DeclaringType.Name, m_extent); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ConcurrencyDerivedClass, message, m_cellWrappers, String.Empty); ExceptionHelpers.ThrowMappingException(record, m_config); } tokenPaths.Add(new MemberPath(m_extent, tokenMember)); } if (tokenMembers.Count > 0) { foreach (LeftCellWrapper wrapper in m_cellWrappers) { Set<MemberPath> conditionMembers = new Set<MemberPath>( wrapper.OnlyInputCell.CQuery.WhereClause.MemberRestrictions.Select(oneOf => oneOf.RestrictedMemberSlot.MemberPath), MemberPath.EqualityComparer); conditionMembers.Intersect(tokenPaths); if (conditionMembers.Count > 0) { // There is a condition on concurrency tokens. Throw an exception. StringBuilder builder = new StringBuilder(); builder.AppendLine(Strings.ViewGen_Concurrency_Invalid_Condition(MemberPath.PropertiesToUserString(conditionMembers, false), m_extent.Name)); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ConcurrencyTokenHasCondition, builder.ToString(), new LeftCellWrapper[] { wrapper }, String.Empty); ExceptionHelpers.ThrowMappingException(record, m_config); } } } } // effects: Given the cells for the extent (extentCells) along with // the signatures (multiconstants + needed attributes) for this extent, generates // the left cell wrappers for it extent (viewTarget indicates whether // the view is for querying or update purposes // Modifies m_cellWrappers to contain this list private bool CreateLeftCellWrappers(IEnumerable<Cell> extentCells, ViewTarget viewTarget) { List<Cell> extentCellsList = new List<Cell>(extentCells); List<Cell> alignedCells = AlignFields(extentCellsList, m_memberMaps.ProjectedSlotMap, viewTarget); Debug.Assert(alignedCells.Count == extentCellsList.Count, "Cell counts disagree"); // Go through all the cells and create cell wrappers that can be used for generating the view m_cellWrappers = new List<LeftCellWrapper>(); for (int i = 0; i < alignedCells.Count; i++) { Cell alignedCell = alignedCells[i]; CellQuery left = alignedCell.GetLeftQuery(viewTarget); CellQuery right = alignedCell.GetRightQuery(viewTarget); // Obtain the non-null projected slots into attributes Set<MemberPath> attributes = left.GetNonNullSlots(); BoolExpression fromVariable = BoolExpression.CreateLiteral(new CellIdBoolean(m_identifiers, extentCellsList[i].CellNumber), m_memberMaps.LeftDomainMap); FragmentQuery leftFragmentQuery = FragmentQuery.Create(fromVariable, left); FragmentQuery rightFragmentQuery = FragmentQuery.Create(fromVariable, right); if (viewTarget == ViewTarget.UpdateView) { leftFragmentQuery = m_leftFragmentQP.CreateDerivedViewBySelectingConstantAttributes(leftFragmentQuery) ?? leftFragmentQuery; } LeftCellWrapper leftWrapper = new LeftCellWrapper(m_viewTarget, attributes, leftFragmentQuery, left, right, m_memberMaps, extentCellsList[i]); m_cellWrappers.Add(leftWrapper); } return true; } // effects: Align the fields of each cell in mapping using projectedSlotMap that has a mapping // for each member of this extent to the slot number of that member in the projected slots // example: // input: Proj[A,B,"5"] = Proj[F,"7",G] // Proj[C,B] = Proj[H,I] // output: m_projectedSlotMap: A -> 0, B -> 1, C -> 2 // Proj[A,B,null] = Proj[F,"7",null] // Proj[null,B,C] = Proj[null,I,H] private static List<Cell> AlignFields(IEnumerable<Cell> cells, MemberProjectionIndex projectedSlotMap, ViewTarget viewTarget) { List<Cell> outputCells = new List<Cell>(); // Determine the aligned field for each cell // The new cells have ProjectedSlotMap.Count number of fields foreach (Cell cell in cells) { // If isQueryView is true, we need to consider the C side of // the cells; otherwise, we look at the S side. Note that we // CANNOT use cell.LeftQuery since that is determined by // cell's isQueryView // The query for which we are constructing the extent CellQuery mainQuery = cell.GetLeftQuery(viewTarget); CellQuery otherQuery = cell.GetRightQuery(viewTarget); CellQuery newMainQuery; CellQuery newOtherQuery; // Create both queries where the projected slot map is used // to determine the order of the fields of the mainquery (of // course, the otherQuery's fields are aligned automatically) mainQuery.CreateFieldAlignedCellQueries(otherQuery, projectedSlotMap, out newMainQuery, out newOtherQuery); Cell outputCell = viewTarget == ViewTarget.QueryView ? Cell.CreateCS(newMainQuery, newOtherQuery, cell.CellLabel, cell.CellNumber) : Cell.CreateCS(newOtherQuery, newMainQuery, cell.CellLabel, cell.CellNumber); outputCells.Add(outputCell); } return outputCells; } #endregion #region String Methods internal override void ToCompactString(StringBuilder builder) { LeftCellWrapper.WrappersToStringBuilder(builder, m_cellWrappers, "Left Celll Wrappers"); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; namespace Greatbone { /// <summary> /// An add-only data collection that can act as both a list, a dictionary and/or a two-layered tree. /// </summary> public class Map<K, V> : IEnumerable<Map<K, V>.Entry> { int[] buckets; protected Entry[] entries; int count; // current group head int head = -1; public Map(int capacity = 16) { // find a least power of 2 that is greater than or equal to capacity int size = 8; while (size < capacity) { size <<= 1; } ReInit(size); } void ReInit(int size) // size must be power of 2 { if (entries == null || size > entries.Length) // allocalte new arrays as needed { buckets = new int[size]; entries = new Entry[size]; } for (int i = 0; i < buckets.Length; i++) // initialize all buckets to -1 { buckets[i] = -1; } count = 0; } public int Count => count; public Entry EntryAt(int idx) => entries[idx]; public V At(int idx) => entries[idx].value; public V[] GroupOf(K key) { int idx = IndexOf(key); if (idx > -1) { int tail = entries[idx].tail; int ret = tail - idx; // number of returned elements V[] arr = new V[ret]; for (int i = 0; i < ret; i++) { arr[i] = entries[idx + 1 + i].value; } return arr; } return null; } public int IndexOf(K key) { int code = key.GetHashCode() & 0x7fffffff; int buck = code % buckets.Length; // target bucket int idx = buckets[buck]; while (idx != -1) { Entry e = entries[idx]; if (e.Match(code, key)) { return idx; } idx = entries[idx].next; // adjust for next index } return -1; } public void Clear() { if (entries != null) { ReInit(entries.Length); } } public void Add(K key, V value) { Add(key, value, false); } public void Add<M>(M v) where M : V, IKeyable<K> { Add(v.Key, v, false); } void Add(K key, V value, bool rehash) { // ensure double-than-needed capacity if (!rehash && count >= entries.Length / 2) { Entry[] old = entries; int oldc = count; ReInit(entries.Length * 2); // re-add old elements for (int i = 0; i < oldc; i++) { Add(old[i].key, old[i].value, true); } } int code = key.GetHashCode() & 0x7fffffff; int buck = code % buckets.Length; // target bucket int idx = buckets[buck]; while (idx != -1) { Entry e = entries[idx]; if (e.Match(code, key)) { e.value = value; return; // replace the old value } idx = entries[idx].next; // adjust for next index } // add a new entry idx = count; entries[idx] = new Entry(code, buckets[buck], key, value); buckets[buck] = idx; count++; // decide group if (value is IGroupKeyable<K> gkeyable) { // compare to current head if (head == -1 || !gkeyable.GroupAs(entries[head].key)) { head = idx; } entries[head].tail = idx; } } public bool Contains(K key) { if (TryGet(key, out _)) { return true; } return false; } public bool TryGet(K key, out V value) { int code = key.GetHashCode() & 0x7fffffff; int buck = code % buckets.Length; // target bucket int idx = buckets[buck]; while (idx != -1) { Entry e = entries[idx]; if (e.Match(code, key)) { value = e.value; return true; } idx = entries[idx].next; // adjust for next index } value = default; return false; } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } public IEnumerator<Entry> GetEnumerator() { return new Enumerator(this); } // // advanced search operations that can be overridden with concurrency constructs public V this[K key] { get { if (key == null) return default; if (TryGet(key, out var val)) { return val; } return default; } set => Add(key, value); } public V[] All(Predicate<V> cond = null) { ValueList<V> list = new ValueList<V>(16); for (int i = 0; i < count; i++) { V v = entries[i].value; if (cond == null || cond(v)) { list.Add(v); } } return list.ToArray(); } public V Find(Predicate<V> cond = null) { for (int i = 0; i < count; i++) { V v = entries[i].value; if (cond == null || cond(v)) { return v; } } return default; } public void ForEach(Func<K, V, bool> cond, Action<K, V> hand) { for (int i = 0; i < count; i++) { K key = entries[i].key; V value = entries[i].value; if (cond == null || cond(key, value)) { hand(entries[i].key, entries[i].value); } } } public struct Entry { readonly int code; // lower 31 bits of hash code internal readonly K key; // entry key internal V value; // entry value internal readonly int next; // index of next entry, -1 if last internal int tail; // the index of group tail, when this is the head entry internal Entry(int code, int next, K key, V value) { this.code = code; this.next = next; this.key = key; this.value = value; this.tail = -1; } internal bool Match(int code, K key) { return this.code == code && this.key.Equals(key); } public override string ToString() { return value.ToString(); } public K Key => key; public V Value => value; public bool IsHead => tail > -1; } public struct Enumerator : IEnumerator<Entry> { readonly Map<K, V> map; int current; internal Enumerator(Map<K, V> map) { this.map = map; current = -1; } public bool MoveNext() { return ++current < map.Count; } public void Reset() { current = -1; } public Entry Current => map.entries[current]; object IEnumerator.Current => map.entries[current]; public void Dispose() { } } static void Test() { Map<string, string> m = new Map<string, string> { {"010101", "mike"}, {"010102", "jobs"}, {"010103", "tim"}, {"010104", "john"}, {"010301", "abigae"}, {"010302", "stephen"}, {"010303", "cox"}, }; var r = m.GroupOf("010101"); } } }
// 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 gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>Index</c> resource.</summary> public sealed partial class IndexName : gax::IResourceName, sys::IEquatable<IndexName> { /// <summary>The possible contents of <see cref="IndexName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/indexes/{index}</c>. /// </summary> ProjectLocationIndex = 1, } private static gax::PathTemplate s_projectLocationIndex = new gax::PathTemplate("projects/{project}/locations/{location}/indexes/{index}"); /// <summary>Creates a <see cref="IndexName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="IndexName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static IndexName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new IndexName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="IndexName"/> with the pattern /// <c>projects/{project}/locations/{location}/indexes/{index}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="IndexName"/> constructed from the provided ids.</returns> public static IndexName FromProjectLocationIndex(string projectId, string locationId, string indexId) => new IndexName(ResourceNameType.ProjectLocationIndex, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexId, nameof(indexId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="IndexName"/> with pattern /// <c>projects/{project}/locations/{location}/indexes/{index}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="IndexName"/> with pattern /// <c>projects/{project}/locations/{location}/indexes/{index}</c>. /// </returns> public static string Format(string projectId, string locationId, string indexId) => FormatProjectLocationIndex(projectId, locationId, indexId); /// <summary> /// Formats the IDs into the string representation of this <see cref="IndexName"/> with pattern /// <c>projects/{project}/locations/{location}/indexes/{index}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="IndexName"/> with pattern /// <c>projects/{project}/locations/{location}/indexes/{index}</c>. /// </returns> public static string FormatProjectLocationIndex(string projectId, string locationId, string indexId) => s_projectLocationIndex.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(indexId, nameof(indexId))); /// <summary>Parses the given resource name string into a new <see cref="IndexName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item> /// </list> /// </remarks> /// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="IndexName"/> if successful.</returns> public static IndexName Parse(string indexName) => Parse(indexName, false); /// <summary> /// Parses the given resource name string into a new <see cref="IndexName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="IndexName"/> if successful.</returns> public static IndexName Parse(string indexName, bool allowUnparsed) => TryParse(indexName, allowUnparsed, out IndexName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="IndexName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item> /// </list> /// </remarks> /// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="IndexName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string indexName, out IndexName result) => TryParse(indexName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="IndexName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="IndexName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string indexName, bool allowUnparsed, out IndexName result) { gax::GaxPreconditions.CheckNotNull(indexName, nameof(indexName)); gax::TemplatedResourceName resourceName; if (s_projectLocationIndex.TryParseName(indexName, out resourceName)) { result = FromProjectLocationIndex(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(indexName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private IndexName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string indexId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; IndexId = indexId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="IndexName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/indexes/{index}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param> public IndexName(string projectId, string locationId, string indexId) : this(ResourceNameType.ProjectLocationIndex, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexId, nameof(indexId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Index</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string IndexId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationIndex: return s_projectLocationIndex.Expand(ProjectId, LocationId, IndexId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as IndexName); /// <inheritdoc/> public bool Equals(IndexName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(IndexName a, IndexName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(IndexName a, IndexName b) => !(a == b); } public partial class Index { /// <summary> /// <see cref="gcav::IndexName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::IndexName IndexName { get => string.IsNullOrEmpty(Name) ? null : gcav::IndexName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Runtime.InteropServices; using mshtml; using OpenLiveWriter.Interop.Com; using OpenLiveWriter.Interop.SHDocVw; using OLECMDEXECOPT = OpenLiveWriter.Interop.SHDocVw.OLECMDEXECOPT; using OLECMDF = OpenLiveWriter.Interop.SHDocVw.OLECMDF; using OLECMDID = OpenLiveWriter.Interop.SHDocVw.OLECMDID; namespace OpenLiveWriter.BrowserControl { /// <summary> /// Abstract base class for BrowserCommand implementations /// </summary> public abstract class ExplorerBrowserCommand : IBrowserCommand { /// <summary> /// Initialize a BrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public ExplorerBrowserCommand(AxWebBrowser browser) { Browser = browser; } /// <summary> /// Determine whether the current command is enabled. /// </summary> public abstract bool Enabled { get; } /// <summary> /// Execute the command /// </summary> public abstract void Execute(); /// <summary> /// Browser control used by subclasses to implement commands (initialized /// in constructor) /// </summary> protected internal AxWebBrowser Browser; } /// <summary> /// Base class implementation for BrowserCommands that must be invoked directly /// via method calls (i.e. they are not available via QueryStatusWB or ExecWB). /// This base class implements QueryStatus and leaves Execute to be implemented /// by subclasses. /// </summary> public abstract class DirectInvokeBrowserCommand : ExplorerBrowserCommand { /// <summary> /// Initialize a DirectInvokeBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public DirectInvokeBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Set the current enabled status of the command (this must be done via an /// external call because this command is not capable of calling QueryStatusWB /// to determine its own status) /// </summary> /// <param name="enabled">true if enabled, false if disabled</param> public void SetEnabled(bool enabled) { m_enabled = enabled; } /// <summary> /// Determine whether the current command is enabled. /// </summary> public override bool Enabled { get { return m_enabled; } } /// <summary> /// Private member used to track current enabled status (default to enabled) /// </summary> private bool m_enabled = true; } /// <summary> /// New Window browser button /// </summary> public class NewWindowBrowserCommand : DirectInvokeBrowserCommand { /// <summary> /// Initialize a NewWindowBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public NewWindowBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { // determine location to navigate to (either current URL or about:blank) string location = Browser.LocationURL; if (location.Length == 0) location = BrowserLocations.AboutBlank; // open a new window and navigate to the specified location object m = Type.Missing; object flags = BrowserNavConstants.navOpenInNewWindow; Browser.Navigate(location, ref flags, ref m, ref m, ref m); } } /// <summary> /// Command for browser Back button /// </summary> public class GoBackBrowserCommand : DirectInvokeBrowserCommand { /// <summary> /// Initialize a GoBackBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public GoBackBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { // go back (ignore excpetion thrown if the history list doesn't have // a page to go back to) try { Browser.GoBack(); } catch { Debug.Assert(false, "Invalid call to GoBack"); } } } /// <summary> /// Command for browser Forward button /// </summary> public class GoForwardBrowserCommand : DirectInvokeBrowserCommand { /// <summary> /// Initialize a GoForwardBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public GoForwardBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { // go forward (ignore excpetion thrown if the history list doesn't have // a page to go forward to) try { Browser.GoForward(); } catch { Debug.Assert(false, "Invalid call to GoForward"); } } } /// <summary> /// Command for browser Stop button /// </summary> public class StopBrowserCommand : DirectInvokeBrowserCommand { /// <summary> /// Initialize a StopBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public StopBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { Browser.Stop(); } } /// <summary> /// Command for browser Home button /// </summary> public class GoHomeBrowserCommand : DirectInvokeBrowserCommand { /// <summary> /// Initialize a GoHomeBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public GoHomeBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { Browser.GoHome(); } } /// <summary> /// Command for browser Search button. Goes to the default search page. /// </summary> public class GoSearchBrowserCommand : DirectInvokeBrowserCommand { /// <summary> /// Initialize a GoSearchBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public GoSearchBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { Browser.GoSearch(); } } /// <summary> /// Abstract base class for commands that are implemented by calling IShellUIHelper /// Provides a static helper for getting an interface to IShellUIHelper. Defers /// implementation of Execute to subclasses. /// </summary> public abstract class ShellUIHelperBrowserCommand : DirectInvokeBrowserCommand { /// <summary> /// Initialize a ShellUIHelperBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public ShellUIHelperBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Helper function that encapsulates getting an interface to an /// IShellUIHelper. Currently just creates and returns one, however /// we could change the implementation to cache a single IShellUIHelper /// globally (or per-thread). /// </summary> /// <returns>interface to IShellUIHelper</returns> protected static IShellUIHelper ShellUIHelper { get { return new ShellUIHelperClass(); } } } /// <summary> /// Command for Add Favorites... /// </summary> public class AddFavoriteBrowserCommand : ShellUIHelperBrowserCommand { /// <summary> /// Initialize an AddFavoriteBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public AddFavoriteBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { // determine the current URL and Title string url = Browser.LocationURL; object title = Browser.LocationName; // add to favorites ShellUIHelper.AddFavorite(url, ref title); } } /// <summary> /// Command for Organize Favorites... /// </summary> public class OrganizeFavoritesBrowserCommand : ShellUIHelperBrowserCommand { /// <summary> /// Initialize an OrganizeFavoritesBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public OrganizeFavoritesBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { // constant for calling Organize Favorites dialog const string ORGANIZE_FAVORITES = "OrganizeFavorites"; // call organize favorites dialog object objNull = null; ShellUIHelper.ShowBrowserUI(ORGANIZE_FAVORITES, ref objNull); } } /// <summary> /// Command for Languages dialog /// </summary> public class LanguagesBrowserCommand : ShellUIHelperBrowserCommand { /// <summary> /// Initialize an LanguagesBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> public LanguagesBrowserCommand(AxWebBrowser browser) : base(browser) { } /// <summary> /// Execute the command /// </summary> public override void Execute() { // constant for calling Languages dialog const string LANGUAGE_DIALOG = "LanguageDialog"; // call organize favorites dialog object objNull = null; ShellUIHelper.ShowBrowserUI(LANGUAGE_DIALOG, ref objNull); } } /// <summary> /// Implementation of BrowserCommand for commands that can be accessed /// using IWebBrowser2.ExecWB. /// </summary> public class StandardBrowserCommand : ExplorerBrowserCommand { /// <summary> /// Initialize a NativeBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> /// <param name="cmdID">unique ID of command</param> public StandardBrowserCommand(AxWebBrowser browser, OLECMDID cmdID) : base(browser) { m_cmdID = cmdID; } /// <summary> /// Determine whether the current command is enabled. /// </summary> public override bool Enabled { get { return IsEnabled(m_cmdID); } } /// <summary> /// Execute the command /// </summary> public override void Execute() { object input = null; object output = null; Browser.ExecWB( m_cmdID, OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref input, ref output); } /// <summary> /// Helper function used to determine if a given command-id is enabled /// </summary> /// <param name="cmdID">command id</param> /// <returns>true if enabled, otherwise false</returns> protected bool IsEnabled(OLECMDID cmdID) { // query the underlying command OLECMDF cmdf = Browser.QueryStatusWB(cmdID); // return the appropriate value if ((cmdf & OLECMDF.OLECMDF_ENABLED) > 0) return true; else return false; } /// <summary> /// ID of native browser command /// </summary> private OLECMDID m_cmdID; } /// <summary> /// Implementation of BrowserCommand for command that can be accessed through the /// IE private command group (find, view source, internet options). Note that /// this interface is verified to work through IE 6.0 but is not officially /// documented and guaranteed to work in future versions. /// </summary> public class PrivateBrowserCommand : ExplorerBrowserCommand { // constants defining known private browser commands. Constants are used // rather than an enum to keep the command-set 'open' for additional (as yet // undiscovered) private commands. public const int Find = 1; public const int ViewSource = 2; public const int InternetOptions = 3; // constants used for validation of private commandID (these should be // updated when new private commands are added) private const int PrivateCommandMin = 1; private const int PrivateCommandMax = 3; /// <summary> /// Initialize a PrivateBrowserCommand /// </summary> /// <param name="browser">reference to underlying browser control</param> /// <param name="cmdID">unique ID of command</param> public PrivateBrowserCommand(AxWebBrowser browser, uint cmdID) : base(browser) { // make sure the cmdID is valid Debug.Assert(cmdID >= PrivateCommandMin && cmdID <= PrivateCommandMax, "Invalid private command ID"); // save the command ID m_cmdID = cmdID; } /// <summary> /// Determine whether the current command is enabled /// </summary> public override bool Enabled { get { // get the command target IOleCommandTargetWithExecParams target = GetCommandTarget(); // if there is a target, query it for its status if (target != null) { if (target is IHTMLDocument2) { // command to be queried OLECMD oleCmd = new OLECMD(); oleCmd.cmdID = m_cmdID; // query for the command's status target.QueryStatus( CGID_IWebBrowserPrivate, 1, ref oleCmd, IntPtr.Zero); // check to see if the command is enabled if ((oleCmd.cmdf & OpenLiveWriter.Interop.Com.OLECMDF.ENABLED) > 0) return true; else return false; } else // not an HTML document return false; } // no valid command target else return false; } } /// <summary> /// Execute the command with an input and output parameter /// </summary> public override void Execute() { // get the command target IOleCommandTargetWithExecParams target = GetCommandTarget(); // if there is a target, execute the command on it if (target != null) { object input = null; object output = null; try { target.Exec( CGID_IWebBrowserPrivate, m_cmdID, OpenLiveWriter.Interop.Com.OLECMDEXECOPT.DODEFAULT, ref input, ref output); } catch (COMException e) { // The InternetOptions command throws a spurious exception // every time it is invoked -- ignore it. if (m_cmdID != InternetOptions) throw e; } } // should never try to execute a command if there is no target! // (caller should have detected this via QueryStatus) else { Debug.Assert(false, "Attempted to execute a command when there is no valid target"); } } /// <summary> /// Helper function to get the appropriate command target for the command /// </summary> /// <returns>IOleCommandTarget if a valid one can be found for the command's /// context, return null if no command target can be located</returns> private IOleCommandTargetWithExecParams GetCommandTarget() { // get the document and try to get its command target object document = Browser.Document; if (document != null) { // return as IOleCommandTarget (returns null if document // is not an HTML document or doesn't support IOleCommandTarget) return document as IOleCommandTargetWithExecParams; } else { Debug.Assert(false, "No current document for the browser! (not sure if this " + "condition is actually invalid, asserting here to proactively " + "detect when this occurs)."); // no current document, no valid command target return null; } } /// <summary> /// ID of private command /// </summary> private uint m_cmdID; /// <summary> /// Command Group ID for private WebBrowser commands /// </summary> private static Guid CGID_IWebBrowserPrivate = new Guid(0xED016940, 0xBD5B, 0x11cf, 0xBA, 0x4E, 0x00, 0xC0, 0x4F, 0xD7, 0x08, 0x16); } /// <summary> /// Structure containing commonly used browser locations /// </summary> internal struct BrowserLocations { public static readonly string AboutBlank = "about:blank"; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Concurrency; using System.Reactive.Subjects; using System.Text; using System.Windows; using Microsoft.Tools.WindowsInstallerXml.Bootstrapper; using NuGet; using ReactiveUI; using ReactiveUI.Routing; using ReactiveUI.Xaml; using Shimmer.Client; using Shimmer.Client.WiXUi; using Shimmer.Core; using Shimmer.WiXUi.Views; using TinyIoC; using Path = System.IO.Path; using FileNotFoundException = System.IO.FileNotFoundException; namespace Shimmer.WiXUi.ViewModels { public class WixUiBootstrapper : ReactiveObject, IWixUiBootstrapper { public IRoutingState Router { get; protected set; } public IWiXEvents WiXEvents { get; protected set; } public static TinyIoCContainer Kernel { get; protected set; } readonly Lazy<ReleaseEntry> _BundledRelease; public ReleaseEntry BundledRelease { get { return _BundledRelease.Value; } } readonly Lazy<IPackage> bundledPackageMetadata; readonly IFileSystemFactory fileSystem; readonly string currentAssemblyDir; public WixUiBootstrapper( IWiXEvents wixEvents, TinyIoCContainer testKernel = null, IRoutingState router = null, IFileSystemFactory fileSystem = null, string currentAssemblyDir = null, string targetRootDirectory = null) { Kernel = testKernel ?? createDefaultKernel(); this.fileSystem = fileSystem ?? AnonFileSystem.Default; this.currentAssemblyDir = currentAssemblyDir ?? Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); RxApp.ConfigureServiceLocator( (type, contract) => { this.Log().Debug("Resolving type '{0}' with contract '{1}'", type, contract); return String.IsNullOrEmpty(contract) ? Kernel.Resolve(type) : Kernel.Resolve(type, contract); }, (type, contract) => Kernel.ResolveAll(type, true), (c, t, s) => { this.Log().Debug("Registering type '{0}' for interface '{1}' and contract '{2}'", c, t, s); if (String.IsNullOrEmpty(s)) { Kernel.Register(t, c, Guid.NewGuid().ToString()); } else { Kernel.Register(t, c, s); } }); RxRouting.ViewModelToViewFunc = findViewClassNameForViewModelName; Kernel.Register<IWixUiBootstrapper>(this); Kernel.Register<IScreen>(this); Kernel.Register(wixEvents); Router = router ?? new RoutingState(); WiXEvents = wixEvents; _BundledRelease = new Lazy<ReleaseEntry>(readBundledReleasesFile); registerExtensionDlls(Kernel); UserError.RegisterHandler(ex => { this.Log().ErrorException("Something unexpected happened", ex.InnerException); if (wixEvents.DisplayMode != Display.Full) { this.Log().Error(ex.ErrorMessage); wixEvents.ShouldQuit(); } var errorVm = RxApp.GetService<IErrorViewModel>(); errorVm.Error = ex; errorVm.Shutdown.Subscribe(_ => wixEvents.ShouldQuit()); errorVm.OpenLogsFolder.Subscribe(_ => openLogsFolder()); RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(errorVm)); return Observable.Return(RecoveryOptionResult.CancelOperation); }); bundledPackageMetadata = new Lazy<IPackage>(openBundledPackage); wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => { this.Log().Info("DetectPackageCompleteObs: got id: '{0}', state: '{1}', status: '{2}'", eventArgs.PackageId, eventArgs.State, eventArgs.Status); var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } // we now have multiple applications in the chain // only run this code after the last entry in the chain if (eventArgs.PackageId != "UserApplicationId") return; if (wixEvents.Action == LaunchAction.Uninstall) { if (wixEvents.DisplayMode != Display.Full) { this.Log().Info("Shimmer is doing a silent uninstall! Sneaky!"); wixEvents.Engine.Plan(LaunchAction.Uninstall); return; } this.Log().Info("Shimmer is doing an uninstall! Sadface!"); var uninstallVm = RxApp.GetService<IUninstallingViewModel>(); Router.Navigate.Execute(uninstallVm); wixEvents.Engine.Plan(LaunchAction.Uninstall); return; } // TODO: If the app is already installed, run it and bail // If Display is silent, we should just exit here. if (wixEvents.Action == LaunchAction.Install) { if (wixEvents.DisplayMode != Display.Full) { this.Log().Info("Shimmer is doing a silent install! Sneaky!"); wixEvents.Engine.Plan(LaunchAction.Install); return; } this.Log().Info("We are doing an UI install! Huzzah!"); var welcomeVm = RxApp.GetService<IWelcomeViewModel>(); welcomeVm.PackageMetadata = bundledPackageMetadata.Value; welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install)); // NB: WiX runs a "Main thread" that all of these events // come back on, and a "UI thread" where it actually runs // the WPF window. Gotta proxy to the UI thread. RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(welcomeVm)); } }); var executablesToStart = Enumerable.Empty<string>(); wixEvents.PlanCompleteObs.Subscribe(eventArgs => { this.Log().Info("PlanCompleteObs: got status: '{0}'", eventArgs.Status); var installManager = new InstallManager(BundledRelease, targetRootDirectory); var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } if (wixEvents.Action == LaunchAction.Uninstall) { var task = installManager.ExecuteUninstall(BundledRelease.Version); task.Subscribe( _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd), ex => UserError.Throw(new UserError("Failed to uninstall", ex.Message, innerException: ex))); // the installer can close before the uninstall is done // which means the UpdateManager is not disposed correctly // which means an error is thrown in the destructor // // let's wait for it to finish // // oh, and .Wait() is unnecesary here // because the subscriber handles an exception var result = task.FirstOrDefault(); return; } IObserver<int> progress = null; if (wixEvents.DisplayMode == Display.Full) { var installingVm = RxApp.GetService<IInstallingViewModel>(); progress = installingVm.ProgressValue; installingVm.PackageMetadata = bundledPackageMetadata.Value; RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(installingVm)); } installManager.ExecuteInstall(this.currentAssemblyDir, bundledPackageMetadata.Value, progress).Subscribe( toStart => { executablesToStart = toStart ?? executablesToStart; wixEvents.Engine.Apply(wixEvents.MainWindowHwnd); }, ex => UserError.Throw("Failed to install application", ex)); }); wixEvents.ApplyCompleteObs.Subscribe(eventArgs => { this.Log().Info("ApplyCompleteObs: got restart: '{0}', result: '{1}', status: '{2}'", eventArgs.Restart, eventArgs.Result, eventArgs.Status); var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } if (wixEvents.DisplayMode == Display.Full && wixEvents.Action == LaunchAction.Install) { var processFactory = Kernel.Resolve<IProcessFactory>(); foreach (var path in executablesToStart) { processFactory.Start(path); } } wixEvents.ShouldQuit(); }); wixEvents.ErrorObs.Subscribe( eventArgs => { this.Log().Info("ErrorObs: got id: '{0}', result: '{1}', code: '{2}'", eventArgs.PackageId, eventArgs.Result, eventArgs.ErrorCode); UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage); }); wixEvents.Engine.Detect(); } static void openLogsFolder() { var processFactory = Kernel.Resolve<IProcessFactory>(); processFactory.Start(FileLogger.LogDirectory); } UserError convertHResultToError(int status) { // NB: WiX passes this as an int which makes it impossible for us to // grok properly var hr = BitConverter.ToUInt32(BitConverter.GetBytes(status), 0); if ((hr & 0x80000000) == 0) { return null; } return new UserError(String.Format("An installer error has occurred: 0x{0:x}", hr)); } IPackage openBundledPackage() { var fi = fileSystem.GetFileInfo(Path.Combine(currentAssemblyDir, BundledRelease.Filename)); if (!fi.Exists) { this.Log().Error("The expected file '{0}' could not be found...", BundledRelease.Filename); var directoryInfo = fileSystem.GetDirectoryInfo(currentAssemblyDir); foreach (var f in directoryInfo.GetFiles("*.nupkg")) { this.Log().Info("Directory contains file: {0}", f.Name); } UserError.Throw("This installer is incorrectly configured, please contact the author", new FileNotFoundException(fi.FullName)); return null; } return new ZipPackage(fi.FullName); } ReleaseEntry readBundledReleasesFile() { var release = fileSystem.GetFileInfo(Path.Combine(currentAssemblyDir, "RELEASES")); if (!release.Exists) { UserError.Throw("This installer is incorrectly configured, please contact the author", new FileNotFoundException(release.FullName)); return null; } ReleaseEntry ret; try { var fileText = fileSystem .GetFile(release.FullName) .ReadAllText(release.FullName, Encoding.UTF8); ret = ReleaseEntry .ParseReleaseFile(fileText) .Where(x => !x.IsDelta) .OrderByDescending(x => x.Version) .First(); } catch (Exception ex) { this.Log().ErrorException("Couldn't read bundled RELEASES file", ex); UserError.Throw("This installer is incorrectly configured, please contact the author", ex); return null; } // now set the logger to the found package name RxApp.LoggerFactory = _ => new FileLogger(ret.PackageName) { Level = ReactiveUI.LogLevel.Info }; ReactiveUIMicro.RxApp.ConfigureFileLogging(ret.PackageName); // HACK: we can do better than this later return ret; } void registerExtensionDlls(TinyIoCContainer kernel) { var di = fileSystem.GetDirectoryInfo(Path.GetDirectoryName(currentAssemblyDir)); var thisAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location; var extensions = di.GetFiles("*.dll") .Where(x => x.FullName != thisAssembly) .SelectMany(x => { try { return new[] { System.Reflection.Assembly.LoadFile(x.FullName) }; } catch (Exception ex) { this.Log().WarnException("Couldn't load " + x.Name, ex); return Enumerable.Empty<System.Reflection.Assembly>(); } }) .SelectMany(x => x.GetModules()).SelectMany(x => x.GetTypes()) .Where(x => typeof(IWiXCustomUi).IsAssignableFrom(x) && !x.IsAbstract) .SelectMany(x => { try { return new[] {(IWiXCustomUi) Activator.CreateInstance(x)}; } catch (Exception ex) { this.Log().WarnException("Couldn't create instance: " + x.FullName, ex); return Enumerable.Empty<IWiXCustomUi>(); } }); foreach (var extension in extensions) { extension.RegisterTypes(kernel); } registerDefaultTypes(kernel); } static void registerDefaultTypes(TinyIoCContainer kernel) { var toRegister = new[] { new { Interface = typeof(IProcessFactory), Impl = typeof(DefaultProcessFactory) }, new { Interface = typeof(IErrorViewModel), Impl = typeof(ErrorViewModel) }, new { Interface = typeof(IWelcomeViewModel), Impl = typeof(WelcomeViewModel) }, new { Interface = typeof(IInstallingViewModel), Impl = typeof(InstallingViewModel) }, new { Interface = typeof(IUninstallingViewModel), Impl = typeof(UninstallingViewModel) }, new { Interface = typeof(IViewFor<ErrorViewModel>), Impl = typeof(ErrorView) }, new { Interface = typeof(IViewFor<WelcomeViewModel>), Impl = typeof(WelcomeView) }, new { Interface = typeof(IViewFor<InstallingViewModel>), Impl = typeof(InstallingView) }, new { Interface = typeof(IViewFor<UninstallingViewModel>), Impl = typeof(UninstallingView) }, }; foreach (var pair in toRegister.Where(pair => !kernel.CanResolve(pair.Interface))) { kernel.Register(pair.Interface, pair.Impl); } } static string findViewClassNameForViewModelName(string viewModelName) { if (viewModelName.Contains("ErrorViewModel")) return typeof (IViewFor<IErrorViewModel>).AssemblyQualifiedName; if (viewModelName.Contains("WelcomeViewModel")) return typeof (IViewFor<IWelcomeViewModel>).AssemblyQualifiedName; if (viewModelName.Contains("InstallingViewModel")) return typeof (IViewFor<IInstallingViewModel>).AssemblyQualifiedName; if (viewModelName.Contains("UninstallingViewModel")) return typeof (IViewFor<IUninstallingViewModel>).AssemblyQualifiedName; throw new Exception("Unknown View"); } TinyIoCContainer createDefaultKernel() { var ret = new TinyIoCContainer(); return ret; } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** using System; using System.IO; using System.Drawing; using System.Collections; using System.Diagnostics; using System.Windows.Forms; using System.ComponentModel; using NUnit.Core; using NUnit.Core.Filters; using NUnit.Util; namespace NUnit.UiKit { public delegate void SelectedTestChangedHandler( ITest test ); public delegate void CheckedTestChangedHandler( ITest[] tests ); /// <summary> /// TestSuiteTreeView is a tree view control /// specialized for displaying the tests /// in an assembly. Clients should always /// use TestNode rather than TreeNode when /// dealing with this class to be sure of /// calling the proper methods. /// </summary> public class TestSuiteTreeView : TreeView { #region DisplayStyle Enumeraton /// <summary> /// Indicates how a tree should be displayed /// </summary> public enum DisplayStyle { Auto, // Select based on space available Expand, // Expand fully Collapse, // Collpase fully HideTests // Expand all but the fixtures, leaving // leaf nodes hidden } #endregion #region Instance Variables /// <summary> /// Hashtable provides direct access to TestNodes /// </summary> private Hashtable treeMap = new Hashtable(); /// <summary> /// The TestNode on which a right click was done /// </summary> private TestSuiteTreeNode contextNode; /// <summary> /// Whether the browser supports running tests, /// or just loading and examining them /// </summary> private bool runCommandSupported = true; /// <summary> /// Whether or not we track progress of tests visibly in the tree /// </summary> private bool displayProgress = true; /// <summary> /// Whether to clear test results when tests change /// </summary> private bool clearResultsOnChange; /// <summary> /// The properties dialog if displayed /// </summary> private TestPropertiesDialog propertiesDialog; /// <summary> /// Source of events that the tree responds to and /// target for the run command. /// </summary> private ITestLoader loader; public System.Windows.Forms.ImageList treeImages; private System.ComponentModel.IContainer components; /// <summary> /// True if the UI should allow a run command to be selected /// </summary> private bool runCommandEnabled = false; private ITest[] runningTests; private TestFilter categoryFilter = TestFilter.Empty; private bool suppressEvents = false; #endregion #region Construction and Initialization public TestSuiteTreeView() { InitializeComponent(); this.ContextMenu = new System.Windows.Forms.ContextMenu(); this.ContextMenu.Popup += new System.EventHandler( ContextMenu_Popup ); // See if there are any overriding images in the directory; Uri myUri = new Uri( System.Reflection.Assembly.GetExecutingAssembly().CodeBase ); string imageDir = Path.GetDirectoryName( myUri.LocalPath ); string successFile = Path.Combine( imageDir, "Success.jpg" ); if ( File.Exists( successFile ) ) treeImages.Images[TestSuiteTreeNode.SuccessIndex] = Image.FromFile( successFile ); string failureFile = Path.Combine( imageDir, "Failure.jpg" ); if ( File.Exists( failureFile ) ) treeImages.Images[TestSuiteTreeNode.FailureIndex] = Image.FromFile( failureFile ); string ignoredFile = Path.Combine( imageDir, "Ignored.jpg" ); if ( File.Exists( ignoredFile ) ) treeImages.Images[TestSuiteTreeNode.IgnoredIndex] = Image.FromFile( ignoredFile ); if ( !this.DesignMode ) this.clearResultsOnChange = Services.UserSettings.GetSetting( "Options.TestLoader.ClearResultsOnReload", false ); } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(TestSuiteTreeView)); this.treeImages = new System.Windows.Forms.ImageList(this.components); // // treeImages // this.treeImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit; this.treeImages.ImageSize = new System.Drawing.Size(16, 16); this.treeImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("treeImages.ImageStream"))); this.treeImages.TransparentColor = System.Drawing.Color.White; // // TestSuiteTreeView // this.ImageIndex = 0; this.ImageList = this.treeImages; this.SelectedImageIndex = 0; this.DoubleClick += new System.EventHandler(this.TestSuiteTreeView_DoubleClick); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.TestSuiteTreeView_DragEnter); this.DragDrop += new System.Windows.Forms.DragEventHandler(this.TestSuiteTreeView_DragDrop); } public void Initialize( ITestLoader loader, ITestEvents events ) { this.loader = loader; events.TestLoaded += new TestEventHandler( OnTestLoaded ); events.TestReloaded += new TestEventHandler( OnTestChanged ); events.TestUnloaded += new TestEventHandler( OnTestUnloaded ); events.RunStarting += new TestEventHandler( OnRunStarting ); events.RunFinished += new TestEventHandler( OnRunFinished ); events.TestFinished += new TestEventHandler( OnTestResult ); events.SuiteFinished+= new TestEventHandler( OnTestResult ); } #endregion #region Properties and Events /// <summary> /// Property determining whether the run command /// is supported from the tree context menu and /// by double-clicking test cases. /// </summary> [Category( "Behavior" ), DefaultValue( true )] [Description("Indicates whether the tree context menu should include a run command")] public bool RunCommandSupported { get { return runCommandSupported; } set { runCommandSupported = value; } } /// <summary> /// Property determining whether tree should redraw nodes /// as tests are complete in order to show progress. /// </summary> [Category( "Behavior" ), DefaultValue( true )] [Description("Indicates whether results should be displayed in the tree as each test completes")] public bool DisplayTestProgress { get { return displayProgress; } set { displayProgress = value; } } [Category( "Appearance" ), DefaultValue( false )] [Description("Indicates whether checkboxes are displayed beside test nodes")] public new bool CheckBoxes { get { return base.CheckBoxes; } set { if ( base.CheckBoxes != value ) { TreeNode savedTopNode = this.TopNode; base.CheckBoxes = value; // Only need this when we turn off checkboxes if ( savedTopNode != null && !value ) { try { suppressEvents = true; this.Accept( new RestoreVisualStateVisitor() ); } finally { savedTopNode.EnsureVisible(); suppressEvents = false; } } } } } /// <summary> /// The currently selected test. /// </summary> [Browsable( false )] public ITest SelectedTest { get { TestSuiteTreeNode node = (TestSuiteTreeNode)SelectedNode; return node == null ? null : node.Test; } } [Browsable( false )] public ITest[] CheckedTests { get { CheckedTestFinder finder = new CheckedTestFinder( this ); return finder.GetCheckedTests( CheckedTestFinder.SelectionFlags.All ); } } [Browsable( false )] public ITest[] SelectedTests { get { CheckedTestFinder finder = new CheckedTestFinder( this ); ITest[] result = finder.GetCheckedTests( CheckedTestFinder.SelectionFlags.Top | CheckedTestFinder.SelectionFlags.Explicit ); if ( result.Length == 0 ) result = new ITest[] { this.SelectedTest }; return result; } } [Browsable( false )] public ITest[] FailedTests { get { FailedTestsFilterVisitor visitor = new FailedTestsFilterVisitor(); Accept(visitor); return visitor.Tests; } } /// <summary> /// The currently selected test result or null /// </summary> [Browsable( false )] public TestResult SelectedTestResult { get { TestSuiteTreeNode node = (TestSuiteTreeNode)SelectedNode; return node == null ? null : node.Result; } } [Browsable(false)] public TestFilter CategoryFilter { get { return categoryFilter; } set { categoryFilter = value; TestFilterVisitor visitor = new TestFilterVisitor( categoryFilter ); this.Accept( visitor ); } } public event SelectedTestChangedHandler SelectedTestChanged; public event CheckedTestChangedHandler CheckedTestChanged; public TestSuiteTreeNode this[string uniqueName] { get { return treeMap[uniqueName] as TestSuiteTreeNode; } } /// <summary> /// Test node corresponding to a test /// </summary> private TestSuiteTreeNode this[ITest test] { get { return FindNode( test ); } } /// <summary> /// Test node corresponding to a TestResultInfo /// </summary> private TestSuiteTreeNode this[TestResult result] { get { return FindNode( result.Test ); } } #endregion #region Handlers for events related to loading and running tests private void OnTestLoaded( object sender, TestEventArgs e ) { CheckPropertiesDialog(); TestNode test = e.Test as TestNode; if ( test != null ) Load( test ); runCommandEnabled = true; } private void OnTestChanged( object sender, TestEventArgs e ) { TestNode test = e.Test as TestNode; if ( test != null ) { Invoke( new LoadHandler( Reload ), new object[]{ test } ); if ( clearResultsOnChange ) ClearResults(); } } private void OnTestUnloaded( object sender, TestEventArgs e) { ClosePropertiesDialog(); Clear(); contextNode = null; runCommandEnabled = false; } private void OnRunStarting( object sender, TestEventArgs e ) { CheckPropertiesDialog(); ClearResults(); runCommandEnabled = false; } private void OnRunFinished( object sender, TestEventArgs e ) { // if ( e.Result != null ) // this[e.Result].Expand(); if ( runningTests != null ) foreach( ITest test in runningTests ) this[test].Expand(); if ( propertiesDialog != null ) propertiesDialog.Invoke( new PropertiesDisplayHandler( propertiesDialog.DisplayProperties ) ); runningTests = null; runCommandEnabled = true; } private void OnTestResult( object sender, TestEventArgs e ) { SetTestResult(e.Result); } #endregion #region Context Menu /// <summary> /// Handles right mouse button down by /// /// remembering the proper context item /// and implements multiple select with the left button. /// </summary> /// <param name="e">MouseEventArgs structure with information about the mouse position and button state</param> protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Right ) { CheckPropertiesDialog(); TreeNode theNode = GetNodeAt( e.X, e.Y ); contextNode = theNode as TestSuiteTreeNode; } // else if (e.Button == MouseButtons.Left ) // { // if ( Control.ModifierKeys == Keys.Control ) // { // TestSuiteTreeNode theNode = GetNodeAt( e.X, e.Y ) as TestSuiteTreeNode; // if ( theNode != null ) // theNode.Selected = true; // } // else // { // ClearSelected(); // } // } base.OnMouseDown( e ); } /// <summary> /// Build treeview context menu dynamically on popup /// </summary> private void ContextMenu_Popup(object sender, System.EventArgs e) { this.ContextMenu.MenuItems.Clear(); TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode; if ( targetNode == null ) return; if ( RunCommandSupported ) { // TODO: handle in Starting event if ( loader.Running ) runCommandEnabled = false; MenuItem runMenuItem = new MenuItem( "&Run", new EventHandler( runMenuItem_Click ) ); runMenuItem.DefaultItem = runMenuItem.Enabled = runCommandEnabled & targetNode.Included; this.ContextMenu.MenuItems.Add( runMenuItem ); MenuItem runAllMenuItem = new MenuItem( "Run &All", new EventHandler( runAllMenuItem_Click ) ); runAllMenuItem.Enabled = runCommandEnabled; this.ContextMenu.MenuItems.Add( runAllMenuItem ); MenuItem runFailedMenuItem = new MenuItem( "Run &Failed", new EventHandler( runFailedMenuItem_Click ) ); runFailedMenuItem.Enabled = runCommandEnabled && loader.TestResult != null && loader.TestResult.IsFailure; this.ContextMenu.MenuItems.Add( runFailedMenuItem ); this.ContextMenu.MenuItems.Add( "-" ); } MenuItem showCheckBoxesMenuItem = new MenuItem( "Show CheckBoxes", new EventHandler( showCheckBoxesMenuItem_Click ) ); showCheckBoxesMenuItem.Checked = this.CheckBoxes; this.ContextMenu.MenuItems.Add( showCheckBoxesMenuItem ); this.ContextMenu.MenuItems.Add( "-" ); if ( targetNode.Nodes.Count > 0 ) { if ( targetNode.IsExpanded ) { MenuItem collapseMenuItem = new MenuItem( "&Collapse", new EventHandler( collapseMenuItem_Click ) ); collapseMenuItem.DefaultItem = !runCommandEnabled; this.ContextMenu.MenuItems.Add( collapseMenuItem ); } else { MenuItem expandMenuItem = new MenuItem( "&Expand", new EventHandler( expandMenuItem_Click ) ); expandMenuItem.DefaultItem = !runCommandEnabled; this.ContextMenu.MenuItems.Add( expandMenuItem ); } } this.ContextMenu.MenuItems.Add( "Expand All", new EventHandler( expandAllMenuItem_Click ) ); this.ContextMenu.MenuItems.Add( "Collapse All", new EventHandler( collapseAllMenuItem_Click ) ); this.ContextMenu.MenuItems.Add( "-" ); MenuItem propertiesMenuItem = new MenuItem( "&Properties", new EventHandler( propertiesMenuItem_Click ) ); this.ContextMenu.MenuItems.Add( propertiesMenuItem ); } private void showCheckBoxesMenuItem_Click( object sender, System.EventArgs e) { this.CheckBoxes = !this.CheckBoxes; } /// <summary> /// When Expand context menu item is clicked, expand the node /// </summary> private void expandMenuItem_Click(object sender, System.EventArgs e) { TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode; if ( targetNode != null ) targetNode.Expand(); } /// <summary> /// When Collapse context menu item is clicked, collapse the node /// </summary> private void collapseMenuItem_Click(object sender, System.EventArgs e) { TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode; if ( targetNode != null ) targetNode.Collapse(); } private void expandAllMenuItem_Click(object sender, System.EventArgs e) { this.BeginUpdate(); this.ExpandAll(); this.EndUpdate(); } private void collapseAllMenuItem_Click(object sender, System.EventArgs e) { this.BeginUpdate(); this.CollapseAll(); this.EndUpdate(); // Compensate for a bug in the underlying control if ( this.Nodes.Count > 0 ) this.SelectedNode = this.Nodes[0]; } /// <summary> /// When Run context menu item is clicked, run the test that /// was selected when the right click was done. /// </summary> private void runMenuItem_Click(object sender, System.EventArgs e) { //TODO: some sort of lock on these booleans? if ( runCommandEnabled ) { runCommandEnabled = false; if ( contextNode != null ) RunTests( new ITest[] { contextNode.Test }, false ); else RunSelectedTests(); } } private void runAllMenuItem_Click(object sender, System.EventArgs e) { if ( runCommandEnabled ) { runCommandEnabled = false; RunAllTests(); } } private void runFailedMenuItem_Click(object sender, System.EventArgs e) { if ( runCommandEnabled ) { runCommandEnabled = false; RunFailedTests(); } } private void propertiesMenuItem_Click( object sender, System.EventArgs e) { TestSuiteTreeNode targetNode = contextNode != null ? contextNode : (TestSuiteTreeNode)SelectedNode; if ( targetNode != null ) ShowPropertiesDialog( targetNode ); } #endregion #region Drag and drop /// <summary> /// Helper method to determine if an IDataObject is valid /// for dropping on the tree view. It must be a the drop /// of a single file with a valid assembly file type. /// </summary> /// <param name="data">IDataObject to be tested</param> /// <returns>True if dropping is allowed</returns> private bool IsValidFileDrop( IDataObject data ) { if ( !data.GetDataPresent( DataFormats.FileDrop ) ) return false; string [] fileNames = data.GetData( DataFormats.FileDrop ) as string []; if ( fileNames == null || fileNames.Length == 0 ) return false; // We can't open more than one project at a time // so handle length of 1 separately. if ( fileNames.Length == 1 ) { string fileName = fileNames[0]; bool isProject = Services.UserSettings.GetSetting( "Options.TestLoader.VisualStudioSupport", false ) ? NUnitProject.CanLoadAsProject( fileName ) : NUnitProject.IsProjectFile( fileName ); return isProject || PathUtils.IsAssemblyFileType( fileName ); } // Multiple assemblies are allowed - we // assume they are all in the same directory // since they are being dragged together. foreach( string fileName in fileNames ) { if ( !PathUtils.IsAssemblyFileType( fileName ) ) return false; } return true; } private void TestSuiteTreeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { if ( IsValidFileDrop( e.Data ) ) { string[] fileNames = (string[])e.Data.GetData( DataFormats.FileDrop ); if ( fileNames.Length == 1 ) loader.LoadProject( fileNames[0] ); else loader.LoadProject( fileNames ); if (loader.IsProjectLoaded && loader.TestProject.IsLoadable) loader.LoadTest(); } } private void TestSuiteTreeView_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) { if ( IsValidFileDrop( e.Data ) ) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.None; } #endregion #region UI Event Handlers private void TestSuiteTreeView_DoubleClick(object sender, System.EventArgs e) { TestSuiteTreeNode node = SelectedNode as TestSuiteTreeNode; if ( runCommandSupported && runCommandEnabled && node.Nodes.Count == 0 && node.Included ) { runCommandEnabled = false; // TODO: Since this is a terminal node, don't use a category filter RunTests( new ITest[] { SelectedTest }, true ); } } protected override void OnAfterSelect(System.Windows.Forms.TreeViewEventArgs e) { if ( !suppressEvents ) { if ( SelectedTestChanged != null ) SelectedTestChanged( SelectedTest ); base.OnAfterSelect( e ); } } protected override void OnAfterCheck(TreeViewEventArgs e) { if ( !suppressEvents ) { if (CheckedTestChanged != null) CheckedTestChanged(CheckedTests); base.OnAfterCheck (e); ((TestSuiteTreeNode)e.Node).WasChecked = e.Node.Checked; } } #endregion #region Public methods to manipulate the tree /// <summary> /// Clear all the results in the tree. /// </summary> public void ClearResults() { foreach ( TestSuiteTreeNode rootNode in Nodes ) rootNode.ClearResults(); } /// <summary> /// Load the tree with a test hierarchy /// </summary> /// <param name="test">Test to be loaded</param> public void Load( TestNode test ) { using( new CP.Windows.Forms.WaitCursor() ) { Clear(); BeginUpdate(); try { AddTreeNodes( Nodes, test, false ); SetInitialExpansion(); } finally { EndUpdate(); contextNode = null; } } } /// <summary> /// Load the tree from a test result /// </summary> /// <param name="result"></param> public void Load( TestResult result ) { using ( new CP.Windows.Forms.WaitCursor( ) ) { Clear(); BeginUpdate(); try { AddTreeNodes( Nodes, result, false ); SetInitialExpansion(); } finally { EndUpdate(); } } } /// <summary> /// Reload the tree with a changed test hierarchy /// while maintaining as much gui state as possible. /// </summary> /// <param name="test">Test suite to be loaded</param> public void Reload( TestNode test ) { UpdateNode( (TestSuiteTreeNode) Nodes[0], test ); } /// <summary> /// Clear all the info in the tree. /// </summary> public void Clear() { treeMap.Clear(); Nodes.Clear(); } protected override void OnAfterCollapse(TreeViewEventArgs e) { if ( !suppressEvents ) { base.OnAfterCollapse (e); ((TestSuiteTreeNode)e.Node).WasExpanded = false; } } protected override void OnAfterExpand(TreeViewEventArgs e) { if ( !suppressEvents ) { base.OnAfterExpand (e); ((TestSuiteTreeNode)e.Node).WasExpanded = true; } } public void Accept(TestSuiteTreeNodeVisitor visitor) { foreach(TestSuiteTreeNode node in Nodes) { node.Accept(visitor); } } public void ClearCheckedNodes() { Accept(new ClearCheckedNodesVisitor()); } public void CheckFailedNodes() { Accept(new CheckFailedNodesVisitor()); } /// <summary> /// Add the result of a test to the tree /// </summary> /// <param name="result">The result of the test</param> public void SetTestResult(TestResult result) { TestSuiteTreeNode node = this[result]; if ( node == null ) throw new ArgumentException( "Test not found in tree: " + result.Test.TestName.UniqueName ); if ( result.Test.TestName.FullName != node.Test.TestName.FullName ) throw( new ArgumentException("Attempting to set Result with a value that refers to a different test") ); node.Result = result; if ( DisplayTestProgress && node.IsVisible ) { Invalidate( node.Bounds ); Update(); } } public void HideTests() { this.BeginUpdate(); foreach( TestSuiteTreeNode node in Nodes ) HideTestsUnderNode( node ); this.EndUpdate(); } public void ShowPropertiesDialog( ITest test ) { ShowPropertiesDialog( this[ test ] ); } private void ShowPropertiesDialog( TestSuiteTreeNode node ) { if ( propertiesDialog == null ) { Form owner = this.FindForm(); propertiesDialog = new TestPropertiesDialog( node ); propertiesDialog.Owner = owner; propertiesDialog.StartPosition = FormStartPosition.Manual; propertiesDialog.Left = owner.Left + ( owner.Width - propertiesDialog.Width ) / 2; propertiesDialog.Top = owner.Top + ( owner.Height - propertiesDialog.Height ) / 2; propertiesDialog.Show(); propertiesDialog.Closed += new EventHandler( OnPropertiesDialogClosed ); } else { propertiesDialog.DisplayProperties( node ); } } private void ClosePropertiesDialog() { if ( propertiesDialog != null ) propertiesDialog.Close(); } private void CheckPropertiesDialog() { if ( propertiesDialog != null && !propertiesDialog.Pinned ) propertiesDialog.Close(); } private void OnPropertiesDialogClosed( object sender, System.EventArgs e ) { propertiesDialog = null; } #endregion #region Running Tests public void RunAllTests() { runCommandEnabled = false; RunTests( new ITest[] { ((TestSuiteTreeNode)Nodes[0]).Test }, true ); } public void RunSelectedTests() { runCommandEnabled = false; RunTests( SelectedTests, false ); } public void RunFailedTests() { runCommandEnabled = false; RunTests( FailedTests, true ); } private void RunTests( ITest[] tests, bool ignoreCategories ) { runningTests = tests; if ( ignoreCategories ) loader.RunTests( MakeNameFilter( tests ) ); else loader.RunTests( MakeFilter( tests ) ); } private TestFilter MakeFilter( ITest[] tests ) { TestFilter nameFilter = MakeNameFilter( tests ); if ( nameFilter == TestFilter.Empty ) return CategoryFilter; if ( tests.Length == 1 ) { TestSuiteTreeNode rootNode = (TestSuiteTreeNode)Nodes[0]; if ( tests[0] == rootNode.Test ) return CategoryFilter; } if ( CategoryFilter.IsEmpty ) return nameFilter; return new AndFilter( nameFilter, CategoryFilter ); } private TestFilter MakeNameFilter( ITest[] tests ) { if ( tests == null || tests.Length == 0 ) return TestFilter.Empty; NameFilter nameFilter = new NameFilter(); foreach( ITest test in tests ) nameFilter.Add( test.TestName ); return nameFilter; } #endregion #region Helper Methods /// <summary> /// Add nodes to the tree constructed from a test /// </summary> /// <param name="nodes">The TreeNodeCollection to which the new node should be added</param> /// <param name="rootTest">The test for which a node is to be built</param> /// <param name="highlight">If true, highlight the text for this node in the tree</param> /// <returns>A newly constructed TestNode, possibly with descendant nodes</returns> private TestSuiteTreeNode AddTreeNodes( IList nodes, TestNode rootTest, bool highlight ) { TestSuiteTreeNode node = new TestSuiteTreeNode( rootTest ); // if ( highlight ) node.ForeColor = Color.Blue; AddToMap( node ); nodes.Add( node ); if ( rootTest.IsSuite ) { foreach( TestNode test in rootTest.Tests ) AddTreeNodes( node.Nodes, test, highlight ); } return node; } private TestSuiteTreeNode AddTreeNodes( IList nodes, TestResult rootResult, bool highlight ) { TestSuiteTreeNode node = new TestSuiteTreeNode( rootResult ); AddToMap( node ); nodes.Add( node ); TestSuiteResult suiteResult = rootResult as TestSuiteResult; if ( suiteResult != null ) { foreach( TestResult result in suiteResult.Results ) AddTreeNodes( node.Nodes, result, highlight ); } node.UpdateImageIndex(); return node; } private void AddToMap( TestSuiteTreeNode node ) { string key = node.Test.TestName.UniqueName; if ( treeMap.ContainsKey( key ) ) Trace.WriteLine( "Duplicate entry: " + key ); // UserMessage.Display( string.Format( // "The test {0} is duplicated\r\rResults will not be displayed correctly in the tree.", node.Test.FullName ), "Duplicate Test" ); else { //Trace.WriteLine( "Added to map: " + node.Test.UniqueName ); treeMap.Add( key, node ); } } private void RemoveFromMap( TestSuiteTreeNode node ) { foreach( TestSuiteTreeNode child in node.Nodes ) RemoveFromMap( child ); treeMap.Remove( node.Test.TestName.UniqueName ); } /// <summary> /// Remove a node from the tree itself and the hashtable /// </summary> /// <param name="node">Node to remove</param> private void RemoveNode( TestSuiteTreeNode node ) { if ( contextNode == node ) contextNode = null; RemoveFromMap( node ); node.Remove(); } /// <summary> /// Helper routine that compares a node with a test /// </summary> /// <param name="node">Node to compare</param> /// <param name="test">Test to compare</param> /// <returns>True if the test has the same name</returns> private bool Match( TestSuiteTreeNode node, TestNode test ) { return node.Test.TestName.FullName == test.TestName.FullName; } /// <summary> /// A node has been matched with a test, so update it /// and then process child nodes and tests recursively. /// If a child was added or removed, then this node /// will expand itself. /// </summary> /// <param name="node">Node to be updated</param> /// <param name="test">Test to plug into node</param> /// <returns>True if a child node was added or deleted</returns> private bool UpdateNode( TestSuiteTreeNode node, TestNode test ) { if ( node.Test.TestName.FullName != test.TestName.FullName ) throw( new ArgumentException( string.Format( "Attempting to update {0} with {1}", node.Test.TestName.FullName, test.TestName.FullName ) ) ); treeMap.Remove( node.Test.TestName.UniqueName ); node.Test = test; treeMap.Add( test.TestName.UniqueName, node ); if ( !test.IsSuite ) return false; bool showChildren = UpdateNodes( node.Nodes, test.Tests ); if ( showChildren ) node.Expand(); return showChildren; } /// <summary> /// Match a set of nodes against a set of tests. /// Remove nodes that are no longer represented /// in the tests. Update any nodes that match. /// Add new nodes for new tests. /// </summary> /// <param name="nodes">List of nodes to be matched</param> /// <param name="tests">List of tests to be matched</param> /// <returns>True if the parent should expand to show that something was added or deleted</returns> private bool UpdateNodes( IList nodes, IList tests ) { // As of NUnit 2.3.6006, the newly reloaded tests // are guaranteed to be in the same order as the // originally loaded tests. Hence, we can merge // the two lists. However, we can only use an // equality comparison, since we don't know what // determines the order. Hence the two passes. bool showChanges = false; // Pass1: delete nodes as needed foreach( TestSuiteTreeNode node in nodes ) if ( NodeWasDeleted( node, tests ) ) { RemoveNode( node ); showChanges = true; } // Pass2: All nodes in the node list are also // in the tests, so we can merge in changes // and add any new nodes. int index = 0; foreach( TestNode test in tests ) { TestSuiteTreeNode node = index < nodes.Count ? (TestSuiteTreeNode)nodes[index] : null; if ( node != null && node.Test.TestName.FullName == test.TestName.FullName ) UpdateNode( node, test ); else { TestSuiteTreeNode newNode = new TestSuiteTreeNode( test ); // if ( highlight ) node.ForeColor = Color.Blue; AddToMap( newNode ); nodes.Insert( index, newNode ); if ( test.IsSuite ) { foreach( TestNode childTest in test.Tests ) AddTreeNodes( newNode.Nodes, childTest, false ); } showChanges = true; } index++; } return showChanges; } /// <summary> /// Helper returns true if the node test is not in /// the list of tests provided. /// </summary> /// <param name="node">Node to examine</param> /// <param name="tests">List of tests to match with node</param> private bool NodeWasDeleted( TestSuiteTreeNode node, IList tests ) { foreach ( TestNode test in tests ) if( Match( node, test ) ) return false; return true; } /// <summary> /// Delegate for use in invoking the tree loader /// from the watcher thread. /// </summary> private delegate void LoadHandler( TestNode test ); private delegate void PropertiesDisplayHandler(); /// <summary> /// Helper collapses all fixtures under a node /// </summary> /// <param name="node">Node under which to collapse fixtures</param> private void HideTestsUnderNode( TestSuiteTreeNode node ) { bool expand = false; foreach( TestSuiteTreeNode child in node.Nodes ) if ( child.Test.IsSuite ) { expand = true; HideTestsUnderNode( child ); } if ( expand ) node.Expand(); else node.Collapse(); } /// <summary> /// Helper used to figure out the display style /// to use when the setting is Auto /// </summary> /// <returns>DisplayStyle to be used</returns> private DisplayStyle GetDisplayStyle() { DisplayStyle initialDisplay = (TestSuiteTreeView.DisplayStyle) Services.UserSettings.GetSetting( "Gui.TestTree.InitialTreeDisplay", DisplayStyle.Auto ); if ( initialDisplay != DisplayStyle.Auto ) return initialDisplay; if ( VisibleCount >= this.GetNodeCount( true ) ) return DisplayStyle.Expand; return DisplayStyle.HideTests; } public void SetInitialExpansion() { CollapseAll(); switch ( GetDisplayStyle() ) { case DisplayStyle.Expand: ExpandAll(); break; case DisplayStyle.HideTests: HideTests(); break; case DisplayStyle.Collapse: default: break; } SelectedNode = Nodes[0]; SelectedNode.EnsureVisible(); } private TestSuiteTreeNode FindNode( ITest test ) { return treeMap[test.TestName.UniqueName] as TestSuiteTreeNode; } #endregion } #region Helper Classes internal class ClearCheckedNodesVisitor : TestSuiteTreeNodeVisitor { public override void Visit(TestSuiteTreeNode node) { node.Checked = false; } } internal class CheckFailedNodesVisitor : TestSuiteTreeNodeVisitor { public override void Visit(TestSuiteTreeNode node) { if (!node.Test.IsSuite && node.Result != null && node.Result.IsFailure) { node.Checked = true; node.EnsureVisible(); } else node.Checked = false; } } internal class FailedTestsFilterVisitor : TestSuiteTreeNodeVisitor { NUnit.Core.Filters.NameFilter filter = new NameFilter(); ArrayList tests = new ArrayList(); public TestFilter Filter { get { return filter; } } public ITest[] Tests { get { return (ITest[])tests.ToArray(typeof(ITest)); } } public override void Visit(TestSuiteTreeNode node) { if (!node.Test.IsSuite && node.Result != null && node.Result.IsFailure) { tests.Add(node.Test); filter.Add(node.Test.TestName); } } } internal class RestoreVisualStateVisitor : TestSuiteTreeNodeVisitor { public override void Visit(TestSuiteTreeNode node) { if ( node.WasExpanded && !node.IsExpanded ) node.Expand(); node.Checked = node.WasChecked; } } public class TestFilterVisitor : TestSuiteTreeNodeVisitor { private ITestFilter filter; public TestFilterVisitor( ITestFilter filter ) { this.filter = filter; } public override void Visit( TestSuiteTreeNode node ) { node.Included = filter.Pass( node.Test ); } } internal class CheckedTestFinder { [Flags] public enum SelectionFlags { Top= 1, Sub = 2, Explicit = 4, All = Top + Sub } private ArrayList checkedTests = new ArrayList(); private struct CheckedTestInfo { public ITest Test; public bool TopLevel; public CheckedTestInfo( ITest test, bool topLevel ) { this.Test = test; this.TopLevel = topLevel; } } public ITest[] GetCheckedTests( SelectionFlags flags ) { int count = 0; foreach( CheckedTestInfo info in checkedTests ) if ( isSelected( info, flags ) ) count++; ITest[] result = new ITest[count]; int index = 0; foreach( CheckedTestInfo info in checkedTests ) if ( isSelected( info, flags ) ) result[index++] = info.Test; return result; } private bool isSelected( CheckedTestInfo info, SelectionFlags flags ) { if ( info.TopLevel && (flags & SelectionFlags.Top) != 0 ) return true; else if ( !info.TopLevel && (flags & SelectionFlags.Sub) != 0 ) return true; else if ( info.Test.RunState == RunState.Explicit && (flags & SelectionFlags.Explicit) != 0 ) return true; else return false; } public CheckedTestFinder( TestSuiteTreeView treeView ) { FindCheckedNodes( treeView.Nodes, true ); } private void FindCheckedNodes( TestSuiteTreeNode node, bool topLevel ) { if ( node.Checked ) { checkedTests.Add( new CheckedTestInfo( node.Test, topLevel ) ); topLevel = false; } FindCheckedNodes( node.Nodes, topLevel ); } private void FindCheckedNodes( TreeNodeCollection nodes, bool topLevel ) { foreach( TestSuiteTreeNode node in nodes ) FindCheckedNodes( node, topLevel ); } } #endregion }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.IO; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; namespace fyiReporting.RDL { ///<summary> /// StyleInfo (borders, fonts, background, padding, ...) ///</summary> public class StyleInfo: ICloneable { // note: all sizes are expressed as points // _BorderColor /// <summary> /// Color of the left border /// </summary> public Color BColorLeft; // (Color) Color of the left border /// <summary> /// Color of the right border /// </summary> public Color BColorRight; // (Color) Color of the right border /// <summary> /// Color of the top border /// </summary> public Color BColorTop; // (Color) Color of the top border /// <summary> /// Color of the bottom border /// </summary> public Color BColorBottom; // (Color) Color of the bottom border // _BorderStyle /// <summary> /// Style of the left border /// </summary> public BorderStyleEnum BStyleLeft; // (Enum BorderStyle) Style of the left border /// <summary> /// Style of the left border /// </summary> public BorderStyleEnum BStyleRight; // (Enum BorderStyle) Style of the left border /// <summary> /// Style of the top border /// </summary> public BorderStyleEnum BStyleTop; // (Enum BorderStyle) Style of the top border /// <summary> /// Style of the bottom border /// </summary> public BorderStyleEnum BStyleBottom; // (Enum BorderStyle) Style of the bottom border // _BorderWdith /// <summary> /// Width of the left border. Max: 20 pt Min: 0.25 pt /// </summary> public float BWidthLeft; //(Size) Width of the left border. Max: 20 pt Min: 0.25 pt /// <summary> /// Width of the right border. Max: 20 pt Min: 0.25 pt /// </summary> public float BWidthRight; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt /// <summary> /// Width of the right border. Max: 20 pt Min: 0.25 pt /// </summary> public float BWidthTop; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt /// <summary> /// Width of the bottom border. Max: 20 pt Min: 0.25 pt /// </summary> public float BWidthBottom; //(Size) Width of the bottom border. Max: 20 pt Min: 0.25 pt /// <summary> /// Color of the background /// </summary> public Color BackgroundColor; //(Color) Color of the background public string BackgroundColorText; //(Textual Color) Color of the background /// <summary> /// The type of background gradient /// </summary> public BackgroundGradientTypeEnum BackgroundGradientType; // The type of background gradient /// <summary> /// End color for the background gradient. /// </summary> /// <summary> /// The type of background pattern /// </summary> public patternTypeEnum PatternType; public Color BackgroundGradientEndColor; //(Color) End color for the background gradient. /// <summary> /// A background image for the report item. /// </summary> public PageImage BackgroundImage; // A background image for the report item. /// <summary> /// Font style Default: Normal /// </summary> public FontStyleEnum FontStyle; // (Enum FontStyle) Font style Default: Normal /// <summary> /// Name of the font family Default: Arial /// </summary> private string _FontFamily; //(string)Name of the font family Default: Arial -- allow comma separated value? /// <summary> /// Point size of the font /// </summary> public float FontSize; //(Size) Point size of the font /// <summary> /// Thickness of the font /// </summary> public FontWeightEnum FontWeight; //(Enum FontWeight) Thickness of the font /// <summary> /// Cell format in Excel07 Default: General /// </summary> public string _Format; //WRP 28102008 Cell format string /// <summary> /// Special text formatting Default: none /// </summary> public TextDecorationEnum TextDecoration; // (Enum TextDecoration) Special text formatting Default: none /// <summary> /// Horizontal alignment of the text Default: General /// </summary> public TextAlignEnum TextAlign; // (Enum TextAlign) Horizontal alignment of the text Default: General /// <summary> /// Vertical alignment of the text Default: Top /// </summary> public VerticalAlignEnum VerticalAlign; // (Enum VerticalAlign) Vertical alignment of the text Default: Top /// <summary> /// The foreground color Default: Black /// </summary> public Color Color; // (Color) The foreground color Default: Black public string ColorText; // (Color-text) /// <summary> /// Padding between the left edge of the report item. /// </summary> public float PaddingLeft; // (Size)Padding between the left edge of the report item. /// <summary> /// Padding between the right edge of the report item. /// </summary> public float PaddingRight; // (Size) Padding between the right edge of the report item. /// <summary> /// Padding between the top edge of the report item. /// </summary> public float PaddingTop; // (Size) Padding between the top edge of the report item. /// <summary> /// Padding between the bottom edge of the report item. /// </summary> public float PaddingBottom; // (Size) Padding between the bottom edge of the report item. /// <summary> /// Height of a line of text. /// </summary> public float LineHeight; // (Size) Height of a line of text /// <summary> /// Indicates whether text is written left-to-right (default) /// </summary> public DirectionEnum Direction; // (Enum Direction) Indicates whether text is written left-to-right (default) /// <summary> /// Indicates the writing mode; e.g. left right top bottom or top bottom left right. /// </summary> public WritingModeEnum WritingMode; // (Enum WritingMode) Indicates whether text is written /// <summary> /// The primary language of the text. /// </summary> public string Language; // (Language) The primary language of the text. /// <summary> /// Unused. /// </summary> public UnicodeBiDirectionalEnum UnicodeBiDirectional; // (Enum UnicodeBiDirection) /// <summary> /// Calendar to use. /// </summary> public CalendarEnum Calendar; // (Enum Calendar) /// <summary> /// The digit format to use. /// </summary> public string NumeralLanguage; // (Language) The digit format to use as described by its /// <summary> /// The variant of the digit format to use. /// </summary> public int NumeralVariant; //(Integer) The variant of the digit format to use. /// <summary> /// Constructor using all defaults for the style. /// </summary> public StyleInfo() { BColorLeft = BColorRight = BColorTop = BColorBottom = System.Drawing.Color.Black; // (Color) Color of the bottom border BStyleLeft = BStyleRight = BStyleTop = BStyleBottom = BorderStyleEnum.None; // _BorderWdith BWidthLeft = BWidthRight = BWidthTop = BWidthBottom = 1; BackgroundColor = System.Drawing.Color.Empty; BackgroundColorText = string.Empty; BackgroundGradientType = BackgroundGradientTypeEnum.None; BackgroundGradientEndColor = System.Drawing.Color.Empty; BackgroundImage = null; FontStyle = FontStyleEnum.Normal; _FontFamily = "Arial"; //WRP 291008 numFmtId should be 0 (Zero) for General format - will be interpreted as a string //It has default values in Excel07 as per ECMA-376 standard (SEction 3.8.30) for Office Open XML Excel07 _Format = "General"; FontSize = 10; FontWeight = FontWeightEnum.Normal; PatternType = patternTypeEnum.None; TextDecoration = TextDecorationEnum.None; TextAlign = TextAlignEnum.General; VerticalAlign = VerticalAlignEnum.Top; Color = System.Drawing.Color.Black; ColorText = "Black"; PaddingLeft = PaddingRight = PaddingTop = PaddingBottom = 0; LineHeight = 0; Direction = DirectionEnum.LTR; WritingMode = WritingModeEnum.lr_tb; Language = "en-US"; UnicodeBiDirectional = UnicodeBiDirectionalEnum.Normal; Calendar = CalendarEnum.Gregorian; NumeralLanguage = Language; NumeralVariant=1; } /// <summary> /// Name of the font family Default: Arial /// </summary> public string FontFamily { get { int i = _FontFamily.IndexOf(","); return i > 0? _FontFamily.Substring(0, i): _FontFamily; } set { _FontFamily = value; } } /// <summary> /// Name of the font family Default: Arial. Support list of families separated by ','. /// </summary> public string FontFamilyFull { get {return _FontFamily;} } /// <summary> /// Gets the FontFamily instance using the FontFamily string. This supports lists of fonts. /// </summary> /// <returns></returns> public FontFamily GetFontFamily() { return GetFontFamily(_FontFamily); } /// <summary> /// Gets the FontFamily instance using the passed face name. This supports lists of fonts. /// </summary> /// <returns></returns> static public FontFamily GetFontFamily(string fface) { string[] choices = fface.Split(','); FontFamily ff=null; foreach (string val in choices) { try { string font=null; // TODO: should be better way than to hard code; could put in config file?? switch (val.Trim().ToLower()) { case "serif": font = "Times New Roman"; break; case "sans-serif": font = "Arial"; break; case "cursive": font = "Comic Sans MS"; break; case "fantasy": font = "Impact"; break; case "monospace": case "courier": font = "Courier New"; break; default: font = val; break; } ff = new FontFamily(font); if (ff != null) break; } catch {} // if font doesn't exist we will go to the next } if (ff == null) ff = new FontFamily("Arial"); return ff; } /// <summary> /// True if font is bold. /// </summary> /// <returns></returns> public bool IsFontBold() { switch(FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: return true; default: return false; } } public static string ToUpperFirstLetter(string source) { if (string.IsNullOrEmpty(source)) { return string.Empty; } // convert to char array of the string char[] letters = source.ToCharArray(); // upper case the first char letters[0] = char.ToUpper(letters[0]); // return the array made of the new char array return new string(letters); } /// <summary> /// Gets the enumerated font weight. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> static public FontWeightEnum GetFontWeight(string v, FontWeightEnum def) { FontWeightEnum fw; try { fw = (FontWeightEnum)System.Enum.Parse(typeof(FontWeightEnum), ToUpperFirstLetter(v)); } catch { fw = def; } return fw; } /// <summary> /// Returns the font style (normal or italic). /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static FontStyleEnum GetFontStyle(string v, FontStyleEnum def) { FontStyleEnum f; try { f = (FontStyleEnum)Enum.Parse(typeof(FontStyleEnum), v); } catch { f = def; } return f; } /// <summary> /// Gets the background gradient type. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> static public BackgroundGradientTypeEnum GetBackgroundGradientType(string v, BackgroundGradientTypeEnum def) { BackgroundGradientTypeEnum gt; try { gt = (BackgroundGradientTypeEnum)Enum.Parse(typeof(BackgroundGradientTypeEnum), v); } catch { gt = def; } return gt; } /// <summary> /// Gets the text decoration. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static TextDecorationEnum GetTextDecoration(string v, TextDecorationEnum def) { TextDecorationEnum td; try { td = (TextDecorationEnum)Enum.Parse(typeof(TextDecorationEnum), v); } catch { td = def; } return td; } /// <summary> /// Gets the text alignment. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static TextAlignEnum GetTextAlign(string v, TextAlignEnum def) { TextAlignEnum ta; try { ta = (TextAlignEnum)Enum.Parse(typeof(TextAlignEnum), System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(v)); } catch { ta = def; } return ta; } /// <summary> /// Gets the vertical alignment. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static VerticalAlignEnum GetVerticalAlign(string v, VerticalAlignEnum def) { VerticalAlignEnum va; try { va = (VerticalAlignEnum)Enum.Parse(typeof(VerticalAlignEnum), v); } catch { va = def; } return va; } /// <summary> /// Gets the direction of the text. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static DirectionEnum GetDirection(string v, DirectionEnum def) { DirectionEnum d; try { d = (DirectionEnum)Enum.Parse(typeof(DirectionEnum), v); } catch { d = def; } return d; } /// <summary> /// Gets the writing mode; e.g. left right top bottom or top bottom left right. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static WritingModeEnum GetWritingMode(string v, WritingModeEnum def) { WritingModeEnum w; try { if (v == "rl-tb" || v == "tb-rl") { // How the hell did it ever get saved as rl-tb? v = "tb_rl"; } else if (v == "lr-tb") { v = "lr_tb"; } else if (v == "tb-lr") { v = "tb_lr"; } w = (WritingModeEnum)Enum.Parse(typeof(WritingModeEnum), v); } catch { w = def; } return w; } /// <summary> /// Gets the unicode BiDirectional. /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static UnicodeBiDirectionalEnum GetUnicodeBiDirectional(string v, UnicodeBiDirectionalEnum def) { UnicodeBiDirectionalEnum u; try { u = (UnicodeBiDirectionalEnum)Enum.Parse(typeof(UnicodeBiDirectionalEnum), v); } catch { u = def; } return u; } /// <summary> /// Gets the calendar (e.g. Gregorian, GregorianArabic, and so on) /// </summary> /// <param name="v"></param> /// <param name="def"></param> /// <returns></returns> public static CalendarEnum GetCalendar(string v, CalendarEnum def) { CalendarEnum c; try { c = (CalendarEnum)Enum.Parse(typeof(CalendarEnum), v); } catch { c = def; } return c; } // WRP 301008 return Excel07 format code as defined in section 3.8.30 of the ECMA-376 standard for Office Open XML Excel07 file formats public static int GetFormatCode (string val) { switch (val) { case "General": return 0; case "0": return 1; case "0.00": return 2; case "#,##0": return 3; case "#,##0.00": return 4; case "0%": return 9; case "p": case "P": case "0.00%": return 10; case "0.00E+00": return 11; case "# ?/?": return 12; case " # ??/??": return 13; case "mm-dd-yy": return 14; case "d-mmm-yy": return 15; case "d-mmm": return 16; case "mmm-yy": return 17; case "h:mm AM/PM": return 18; case "h:mm:ss AM/PM": return 19; case "h:mm": return 20; case "h:mm:ss": return 21; case "m/d/yy h:mm": return 22; case "#,##0 ;(#,##0)": return 37; case "#,##0 ;[Red](#,##0)": return 38; case "#,##0.00;(#,##0.00)": return 39; case "#,##0.00;[Red](#,##0.00)": return 40; case "mm:ss": return 45; case "[h]:mm:ss": return 46; case "mmss.0": return 47; case "##0.0E+0": return 48; case "@": return 49; default: return 999; } } public static patternTypeEnum GetPatternType(System.Drawing.Drawing2D.HatchStyle hs) { switch (hs) { case HatchStyle.BackwardDiagonal: return patternTypeEnum.BackwardDiagonal; case HatchStyle.Cross: return patternTypeEnum.Cross; case HatchStyle.DarkDownwardDiagonal: return patternTypeEnum.DarkDownwardDiagonal; case HatchStyle.DarkHorizontal: return patternTypeEnum.DarkHorizontal; case HatchStyle.Vertical: return patternTypeEnum.Vertical; case HatchStyle.LargeConfetti: return patternTypeEnum.LargeConfetti; case HatchStyle.OutlinedDiamond: return patternTypeEnum.OutlinedDiamond; case HatchStyle.SmallConfetti: return patternTypeEnum.SmallConfetti; case HatchStyle.HorizontalBrick: return patternTypeEnum.HorizontalBrick; case HatchStyle.LargeCheckerBoard: return patternTypeEnum.CheckerBoard; case HatchStyle.SolidDiamond: return patternTypeEnum.SolidDiamond; case HatchStyle.DiagonalBrick: return patternTypeEnum.DiagonalBrick; default: return patternTypeEnum.None; } } #region ICloneable Members public object Clone() { return this.MemberwiseClone(); } #endregion } /// <summary> /// The types of patterns supported. /// </summary> public enum patternTypeEnum { None, LargeConfetti, Cross, DarkDownwardDiagonal, OutlinedDiamond, DarkHorizontal, SmallConfetti, HorizontalBrick, CheckerBoard, Vertical, SolidDiamond, DiagonalBrick, BackwardDiagonal } /// <summary> /// The types of background gradients supported. /// </summary> public enum BackgroundGradientTypeEnum { /// <summary> /// No gradient /// </summary> None, /// <summary> /// Left Right gradient /// </summary> LeftRight, /// <summary> /// Top Bottom gradient /// </summary> TopBottom, /// <summary> /// Center gradient /// </summary> Center, /// <summary> /// Diagonal Left gradient /// </summary> DiagonalLeft, /// <summary> /// Diagonal Right gradient /// </summary> DiagonalRight, /// <summary> /// Horizontal Center gradient /// </summary> HorizontalCenter, /// <summary> /// Vertical Center /// </summary> VerticalCenter } /// <summary> /// Font styles supported /// </summary> public enum FontStyleEnum { /// <summary> /// Normal font /// </summary> Normal, /// <summary> /// Italic font /// </summary> Italic } /// <summary> /// Potential font weights /// </summary> public enum FontWeightEnum { /// <summary> /// Lighter font /// </summary> Lighter, /// <summary> /// Normal font /// </summary> Normal, /// <summary> /// Bold font /// </summary> Bold, /// <summary> /// Bolder font /// </summary> Bolder, /// <summary> /// W100 font /// </summary> W100, /// <summary> /// W200 font /// </summary> W200, /// <summary> /// W300 font /// </summary> W300, /// <summary> /// W400 font /// </summary> W400, /// <summary> /// W500 font /// </summary> W500, /// <summary> /// W600 font /// </summary> W600, /// <summary> /// W700 font /// </summary> W700, /// <summary> /// W800 font /// </summary> W800, /// <summary> /// W900 font /// </summary> W900 } public enum TextDecorationEnum { Underline, Overline, LineThrough, None } public enum TextAlignEnum { Left, Center, Right, General, Justified } public enum VerticalAlignEnum { Top, Middle, Bottom } public enum DirectionEnum { LTR, // left to right RTL // right to left } public enum WritingModeEnum { lr_tb, // left right - top bottom tb_rl, // top bottom - right left tb_lr // top bottom - left right } public enum UnicodeBiDirectionalEnum { Normal, Embed, BiDi_Override } public enum CalendarEnum { Gregorian, GregorianArabic, GregorianMiddleEastFrench, GregorianTransliteratedEnglish, GregorianTransliteratedFrench, GregorianUSEnglish, Hebrew, Hijri, Japanese, Korea, Taiwan, ThaiBuddhist } }
#region File Description //----------------------------------------------------------------------------- // EffectHelpers.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion using System; namespace SharpDX.Toolkit.Graphics { /// <summary> /// Track which effect parameters need to be recomputed during the next OnApply. /// </summary> [Flags] internal enum EffectDirtyFlags { WorldViewProj = 1, World = 2, EyePosition = 4, MaterialColor = 8, Fog = 16, FogEnable = 32, AlphaTest = 64, ShaderIndex = 128, All = -1 } /// <summary> /// Helper code shared between the various built-in effects. /// </summary> internal static class EffectHelpers { /// <summary> /// Sets up the standard key/fill/back lighting rig. /// </summary> internal static Vector3 EnableDefaultLighting(DirectionalLight light0, DirectionalLight light1, DirectionalLight light2) { // Key light. light0.Direction = new Vector3(-0.5265408f, -0.5735765f, -0.6275069f); light0.DiffuseColor = new Vector3(1, 0.9607844f, 0.8078432f); light0.SpecularColor = new Vector3(1, 0.9607844f, 0.8078432f); light0.Enabled = true; // Fill light. light1.Direction = new Vector3(0.7198464f, 0.3420201f, 0.6040227f); light1.DiffuseColor = new Vector3(0.9647059f, 0.7607844f, 0.4078432f); light1.SpecularColor = Vector3.Zero; light1.Enabled = true; // Back light. light2.Direction = new Vector3(0.4545195f, -0.7660444f, 0.4545195f); light2.DiffuseColor = new Vector3(0.3231373f, 0.3607844f, 0.3937255f); light2.SpecularColor = new Vector3(0.3231373f, 0.3607844f, 0.3937255f); light2.Enabled = true; // Ambient light. return new Vector3(0.05333332f, 0.09882354f, 0.1819608f); } /// <summary> /// Lazily recomputes the world+view+projection matrix and /// fog vector based on the current effect parameter settings. /// </summary> internal static EffectDirtyFlags SetWorldViewProjAndFog(EffectDirtyFlags dirtyFlags, ref Matrix world, ref Matrix view, ref Matrix projection, ref Matrix worldView, bool fogEnabled, float fogStart, float fogEnd, EffectParameter worldViewProjParam, EffectParameter fogVectorParam) { // Recompute the world+view+projection matrix? if ((dirtyFlags & EffectDirtyFlags.WorldViewProj) != 0) { Matrix worldViewProj; Matrix.Multiply(ref world, ref view, out worldView); Matrix.Multiply(ref worldView, ref projection, out worldViewProj); worldViewProjParam.SetValue(worldViewProj); dirtyFlags &= ~EffectDirtyFlags.WorldViewProj; } if (fogEnabled) { // Recompute the fog vector? if ((dirtyFlags & (EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable)) != 0) { SetFogVector(ref worldView, fogStart, fogEnd, fogVectorParam); dirtyFlags &= ~(EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable); } } else { // When fog is disabled, make sure the fog vector is reset to zero. if ((dirtyFlags & EffectDirtyFlags.FogEnable) != 0) { fogVectorParam.SetValue(Vector4.Zero); dirtyFlags &= ~EffectDirtyFlags.FogEnable; } } return dirtyFlags; } /// <summary> /// Sets a vector which can be dotted with the object space vertex position to compute fog amount. /// </summary> static void SetFogVector(ref Matrix worldView, float fogStart, float fogEnd, EffectParameter fogVectorParam) { if (fogStart == fogEnd) { // Degenerate case: force everything to 100% fogged if start and end are the same. fogVectorParam.SetValue(new Vector4(0, 0, 0, 1)); } else { // We want to transform vertex positions into view space, take the resulting // Z value, then scale and offset according to the fog start/end distances. // Because we only care about the Z component, the shader can do all this // with a single dot product, using only the Z row of the world+view matrix. float scale = 1f / (fogStart - fogEnd); var fogVector = new Vector4(worldView.M13 * scale, worldView.M23 * scale, worldView.M33 * scale, (worldView.M43 + fogStart) * scale); fogVectorParam.SetValue(fogVector); } } /// <summary> /// Lazily recomputes the world inverse transpose matrix and /// eye position based on the current effect parameter settings. /// </summary> internal static EffectDirtyFlags SetLightingMatrices(EffectDirtyFlags dirtyFlags, ref Matrix world, ref Matrix view, EffectParameter worldParam, EffectParameter worldInverseTransposeParam, EffectParameter eyePositionParam) { // Set the world and world inverse transpose matrices. if ((dirtyFlags & EffectDirtyFlags.World) != 0) { Matrix worldTranspose; Matrix worldInverseTranspose; Matrix.Invert(ref world, out worldTranspose); Matrix.Transpose(ref worldTranspose, out worldInverseTranspose); worldParam.SetValue(world); worldInverseTransposeParam.SetValue(worldInverseTranspose); dirtyFlags &= ~EffectDirtyFlags.World; } // Set the eye position. if ((dirtyFlags & EffectDirtyFlags.EyePosition) != 0) { Matrix viewInverse; Matrix.Invert(ref view, out viewInverse); eyePositionParam.SetValue(viewInverse.TranslationVector); dirtyFlags &= ~EffectDirtyFlags.EyePosition; } return dirtyFlags; } /// <summary> /// Sets the diffuse/emissive/alpha material color parameters. /// </summary> internal static void SetMaterialColor(bool lightingEnabled, float alpha, ref Vector4 diffuseColor, ref Vector3 emissiveColor, ref Vector3 ambientLightColor, EffectParameter diffuseColorParam, EffectParameter emissiveColorParam) { // Desired lighting model: // // ((AmbientLightColor + sum(diffuse directional light)) * DiffuseColor) + EmissiveColor // // When lighting is disabled, ambient and directional lights are ignored, leaving: // // DiffuseColor + EmissiveColor // // For the lighting disabled case, we can save one shader instruction by precomputing // diffuse+emissive on the CPU, after which the shader can use DiffuseColor directly, // ignoring its emissive parameter. // // When lighting is enabled, we can merge the ambient and emissive settings. If we // set our emissive parameter to emissive+(ambient*diffuse), the shader no longer // needs to bother adding the ambient contribution, simplifying its computation to: // // (sum(diffuse directional light) * DiffuseColor) + EmissiveColor // // For further optimization goodness, we merge material alpha with the diffuse // color parameter, and premultiply all color values by this alpha. if (lightingEnabled) { var diffuse = new Vector4(diffuseColor.X * alpha, diffuseColor.Y * alpha, diffuseColor.Z * alpha, alpha); var emissive = new Vector3( (emissiveColor.X + ambientLightColor.X * diffuseColor.X) * alpha, (emissiveColor.Y + ambientLightColor.Y * diffuseColor.Y) * alpha, (emissiveColor.Z + ambientLightColor.Z * diffuseColor.Z) * alpha ); diffuseColorParam.SetValue(diffuse); emissiveColorParam.SetValue(emissive); } else { var diffuse = new Vector4((diffuseColor.X + emissiveColor.X) * alpha, (diffuseColor.Y + emissiveColor.Y) * alpha, (diffuseColor.Z + emissiveColor.Z) * alpha, alpha); diffuseColorParam.SetValue(diffuse); } } } }
/* * Magix - A Web Application Framework for Humans * Copyright 2010 - 2014 - thomas@magixilluminate.com * Magix is licensed as MITx11, see enclosed License.txt File for Details. */ using System; using System.IO; using System.Net; using Magix.Core; namespace Magix.execute { /* * remoting hyperlisp support */ public class RemotingCore : ActiveController { /* * remote hyperlisp support */ [ActiveEvent(Name = "magix.core.application-startup")] public static void magix_core_application_startup(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.app-startup-dox].value"); return; } RemapTunneledEvents(); RemapOpenEvents(); } /* * remaps stored open active events */ private static void RemapOpenEvents() { Node tmp = new Node(); tmp["prototype"]["type"].Value = "magix.execute.open"; RaiseActiveEvent( "magix.data.load", tmp); if (tmp.Contains("objects")) { foreach (Node idx in tmp["objects"]) { ActiveEvents.Instance.MakeRemotable(idx["value"]["event"].Get<string>()); } } } /* * remaps stored tunneled active events */ private static void RemapTunneledEvents() { Node tmp = new Node(); tmp["prototype"]["type"].Value = "magix.execute.tunnel"; RaiseActiveEvent( "magix.data.load", tmp); if (tmp.Contains("objects")) { foreach (Node idx in tmp["objects"]) { string activeEvent = idx["value"]["event"].Get<string>(); ActiveEvents.Instance.OverrideRemotely(activeEvent, idx["value"]["url"].Get<string>()); if (!ActiveEvents.Instance.IsOverride(activeEvent)) { // to make sure the local system actually has an active event with that name ActiveEvents.Instance.CreateEventMapping( activeEvent, "magix.execute._mumbo-jumbo"); } } } } /* * tunnel hyperlisp keyword */ [ActiveEvent(Name = "magix.execute.tunnel")] public static void magix_execute_tunnel(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.tunnel-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.tunnel-sample]"); return; } if (!ip.ContainsValue("name")) throw new ArgumentException( @"[tunnel] needs [name], being active event name, to know which event to override to go externally"); Node dp = Dp(e.Params); string activeEvent = Expressions.GetExpressionValue<string>(ip["name"].Get<string>(), dp, ip, false); string url = ip.Contains("url") ? Expressions.GetExpressionValue<string>(ip["url"].Get<string>(), dp, ip, false) : null; if (string.IsNullOrEmpty(url)) { if (!ip.Contains("persist") || ip["persist"].Get<bool>()) DataBaseRemoval.Remove(activeEvent, "magix.execute.tunnel", e.Params); ActiveEvents.Instance.RemoveRemoteOverride(activeEvent); string originalName = ""; string origActiveEvent = ActiveEvents.Instance.GetEventMappingValue(activeEvent, ref originalName); if (origActiveEvent == "magix.execute._mumbo-jumbo") { ActiveEvents.Instance.RemoveMapping(activeEvent); } } else { if (!ip.Contains("persist") || ip["persist"].Get<bool>()) { DataBaseRemoval.Remove(activeEvent, "magix.execute.tunnel", e.Params); Node saveNode = new Node("magix.data.save"); saveNode["id"].Value = Guid.NewGuid(); saveNode["value"]["event"].Value = activeEvent; saveNode["value"]["type"].Value = "magix.execute.tunnel"; saveNode["value"]["url"].Value = url; BypassExecuteActiveEvent(saveNode, e.Params); } ActiveEvents.Instance.OverrideRemotely(activeEvent, url); if (!ActiveEvents.Instance.IsOverride(activeEvent)) { // to make sure the local system actually has an active event with that name ActiveEvents.Instance.CreateEventMapping( activeEvent, "magix.execute._mumbo-jumbo"); } } } /* * open hyperlisp keyword */ [ActiveEvent(Name = "magix.execute.open")] public static void magix_execute_open(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.open-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.open-sample]"); return; } if (!ip.ContainsValue("name")) throw new ArgumentException("[open] needs a [name] parameter"); Node dp = Dp(e.Params); string activeEvent = Expressions.GetExpressionValue<string>(ip["name"].Get<string>(), dp, ip, false); if (!ip.Contains("persist") || ip["persist"].Get<bool>()) { DataBaseRemoval.Remove(activeEvent, "magix.execute.open", e.Params); Node saveNode = new Node("magix.data.save"); saveNode["id"].Value = Guid.NewGuid(); saveNode["value"]["event"].Value = activeEvent; saveNode["value"]["type"].Value = "magix.execute.open"; BypassExecuteActiveEvent(saveNode, e.Params); } ActiveEvents.Instance.MakeRemotable(activeEvent); } /* * close hyperlisp support */ [ActiveEvent(Name = "magix.execute.close")] public static void magix_execute_close(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.close-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.close-sample]"); return; } if (!ip.ContainsValue("name")) throw new ArgumentException("[close] needs a [name]"); Node dp = Dp(e.Params); string activeEvent = Expressions.GetExpressionValue<string>(ip["name"].Get<string>(), dp, ip, false); if (!ip.Contains("persist") || ip["persist"].Get<bool>()) DataBaseRemoval.Remove(activeEvent, "magix.execute.open", e.Params); ActiveEvents.Instance.RemoveRemotable(activeEvent); } /* * remotely invokes an event */ [ActiveEvent(Name = "magix.execute.remote")] public static void magix_execute_remote(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.remote-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.remote-sample]"); return; } Node dp = Dp(e.Params); if (!ip.ContainsValue("name")) throw new ArgumentException("[remote] needs a [name]"); string activeEvent = Expressions.GetExpressionValue<string>(ip["name"].Get<string>(), dp, ip, false); if (!ip.Contains("url") || string.IsNullOrEmpty(ip["url"].Get<string>())) throw new ArgumentException("[remote] needs a [url]"); string url = Expressions.GetExpressionValue<string>(ip["url"].Get<string>(), dp, ip, false); RemotelyInvokeActiveEvent(ip, activeEvent, url); } /* * helper for above */ private static void RemotelyInvokeActiveEvent(Node ip, string activeEvent, string url) { HttpWebRequest req = WebRequest.Create(url) as System.Net.HttpWebRequest; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; using (StreamWriter writer = new StreamWriter(req.GetRequestStream())) { writer.Write("event=" + System.Web.HttpUtility.UrlEncode(activeEvent)); if (ip.Contains("params")) { Node tmp = new Node(ip.Name, ip.Value); tmp.AddRange(ip["params"]); writer.Write("&params=" + System.Web.HttpUtility.UrlEncode(tmp.ToJSONString())); } } using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(resp.GetResponseStream())) { if ((int)resp.StatusCode >= 200 && (int)resp.StatusCode < 300) { string val = reader.ReadToEnd(); if (!val.StartsWith("return:")) throw new Exception( "something went wrong when connecting to '" + url + "'.&nbsp;&nbsp;server responded with: " + val); if (val.Length > 7) { Node tmp = Node.FromJSONString(val.Substring(7)); ip["params"].Clear(); ip["params"].AddRange(tmp); } } else throw new ArgumentException("couldn't find event '" + activeEvent + "' on " + url); } } } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { public class InertButton : Button { private enum RepeatClickStatus { Disabled, Started, Repeating, Stopped } private class RepeatClickEventArgs : EventArgs { private static RepeatClickEventArgs _empty; static RepeatClickEventArgs() { _empty = new RepeatClickEventArgs(); } public new static RepeatClickEventArgs Empty { get { return _empty; } } } private IContainer components = new Container(); private int m_borderWidth = 1; private bool m_mouseOver = false; private bool m_mouseCapture = false; private bool m_isPopup = false; private Image m_imageEnabled = null; private Image m_imageDisabled = null; private int m_imageIndexEnabled = -1; private int m_imageIndexDisabled = -1; private bool m_monochrom = true; private ToolTip m_toolTip = null; private string m_toolTipText = ""; private Color m_borderColor = Color.Empty; public InertButton() { InternalConstruct(null, null); } public InertButton(Image imageEnabled) { InternalConstruct(imageEnabled, null); } public InertButton(Image imageEnabled, Image imageDisabled) { InternalConstruct(imageEnabled, imageDisabled); } private void InternalConstruct(Image imageEnabled, Image imageDisabled) { // Remember parameters ImageEnabled = imageEnabled; ImageDisabled = imageDisabled; // Prevent drawing flicker by blitting from memory in WM_PAINT SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // Prevent base class from trying to generate double click events and // so testing clicks against the double click time and rectangle. Getting // rid of this allows the user to press then release button very quickly. //SetStyle(ControlStyles.StandardDoubleClick, false); // Should not be allowed to select this control SetStyle(ControlStyles.Selectable, false); m_timer = new Timer(); m_timer.Enabled = false; m_timer.Tick += new EventHandler(Timer_Tick); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } public Color BorderColor { get { return m_borderColor; } set { if (m_borderColor != value) { m_borderColor = value; Invalidate(); } } } private bool ShouldSerializeBorderColor() { return (m_borderColor != Color.Empty); } public int BorderWidth { get { return m_borderWidth; } set { if (value < 1) value = 1; if (m_borderWidth != value) { m_borderWidth = value; Invalidate(); } } } public Image ImageEnabled { get { if (m_imageEnabled != null) return m_imageEnabled; try { if (ImageList == null || ImageIndexEnabled == -1) return null; else return ImageList.Images[m_imageIndexEnabled]; } catch { return null; } } set { if (m_imageEnabled != value) { m_imageEnabled = value; Invalidate(); } } } private bool ShouldSerializeImageEnabled() { return (m_imageEnabled != null); } public Image ImageDisabled { get { if (m_imageDisabled != null) return m_imageDisabled; try { if (ImageList == null || ImageIndexDisabled == -1) return null; else return ImageList.Images[m_imageIndexDisabled]; } catch { return null; } } set { if (m_imageDisabled != value) { m_imageDisabled = value; Invalidate(); } } } public int ImageIndexEnabled { get { return m_imageIndexEnabled; } set { if (m_imageIndexEnabled != value) { m_imageIndexEnabled = value; Invalidate(); } } } public int ImageIndexDisabled { get { return m_imageIndexDisabled; } set { if (m_imageIndexDisabled != value) { m_imageIndexDisabled = value; Invalidate(); } } } public bool IsPopup { get { return m_isPopup; } set { if (m_isPopup != value) { m_isPopup = value; Invalidate(); } } } public bool Monochrome { get { return m_monochrom; } set { if (value != m_monochrom) { m_monochrom = value; Invalidate(); } } } public bool RepeatClick { get { return (ClickStatus != RepeatClickStatus.Disabled); } set { ClickStatus = RepeatClickStatus.Stopped; } } private RepeatClickStatus m_clickStatus = RepeatClickStatus.Disabled; private RepeatClickStatus ClickStatus { get { return m_clickStatus; } set { if (m_clickStatus == value) return; m_clickStatus = value; if (ClickStatus == RepeatClickStatus.Started) { Timer.Interval = RepeatClickDelay; Timer.Enabled = true; } else if (ClickStatus == RepeatClickStatus.Repeating) Timer.Interval = RepeatClickInterval; else Timer.Enabled = false; } } private int m_repeatClickDelay = 500; public int RepeatClickDelay { get { return m_repeatClickDelay; } set { m_repeatClickDelay = value; } } private int m_repeatClickInterval = 100; public int RepeatClickInterval { get { return m_repeatClickInterval; } set { m_repeatClickInterval = value; } } private Timer m_timer; private Timer Timer { get { return m_timer; } } public string ToolTipText { get { return m_toolTipText; } set { if (m_toolTipText != value) { if (m_toolTip == null) m_toolTip = new ToolTip(this.components); m_toolTipText = value; m_toolTip.SetToolTip(this, value); } } } private void Timer_Tick(object sender, EventArgs e) { if (m_mouseCapture && m_mouseOver) OnClick(RepeatClickEventArgs.Empty); if (ClickStatus == RepeatClickStatus.Started) ClickStatus = RepeatClickStatus.Repeating; } /// <exclude/> protected override void OnMouseDown(MouseEventArgs mevent) { base.OnMouseDown(mevent); if (mevent.Button != MouseButtons.Left) return; if (m_mouseCapture == false || m_mouseOver == false) { m_mouseCapture = true; m_mouseOver = true; //Redraw to show button state Invalidate(); } if (RepeatClick) { OnClick(RepeatClickEventArgs.Empty); ClickStatus = RepeatClickStatus.Started; } } /// <exclude/> protected override void OnClick(EventArgs e) { if (RepeatClick && !(e is RepeatClickEventArgs)) return; base.OnClick (e); } /// <exclude/> protected override void OnMouseUp(MouseEventArgs mevent) { base.OnMouseUp(mevent); if (mevent.Button != MouseButtons.Left) return; if (m_mouseOver == true || m_mouseCapture == true) { m_mouseOver = false; m_mouseCapture = false; // Redraw to show button state Invalidate(); } if (RepeatClick) ClickStatus = RepeatClickStatus.Stopped; } /// <exclude/> protected override void OnMouseMove(MouseEventArgs mevent) { base.OnMouseMove(mevent); // Is mouse point inside our client rectangle bool over = this.ClientRectangle.Contains(new Point(mevent.X, mevent.Y)); // If entering the button area or leaving the button area... if (over != m_mouseOver) { // Update state m_mouseOver = over; // Redraw to show button state Invalidate(); } } /// <exclude/> protected override void OnMouseEnter(EventArgs e) { // Update state to reflect mouse over the button area if (!m_mouseOver) { m_mouseOver = true; // Redraw to show button state Invalidate(); } base.OnMouseEnter(e); } /// <exclude/> protected override void OnMouseLeave(EventArgs e) { // Update state to reflect mouse not over the button area if (m_mouseOver) { m_mouseOver = false; // Redraw to show button state Invalidate(); } base.OnMouseLeave(e); } /// <exclude/> protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); DrawBackground(pevent.Graphics); DrawImage(pevent.Graphics); DrawText(pevent.Graphics); DrawBorder(pevent.Graphics); } private void DrawBackground(Graphics g) { using (SolidBrush brush = new SolidBrush(BackColor)) { g.FillRectangle(brush, ClientRectangle); } } private void DrawImage(Graphics g) { Image image = this.Enabled ? ImageEnabled : ((ImageDisabled != null) ? ImageDisabled : ImageEnabled); ImageAttributes imageAttr = null; if (null == image) return; if (m_monochrom) { imageAttr = new ImageAttributes(); // transform the monochrom image // white -> BackColor // black -> ForeColor ColorMap[] colorMap = new ColorMap[2]; colorMap[0] = new ColorMap(); colorMap[0].OldColor = Color.White; colorMap[0].NewColor = this.BackColor; colorMap[1] = new ColorMap(); colorMap[1].OldColor = Color.Black; colorMap[1].NewColor = this.ForeColor; imageAttr.SetRemapTable(colorMap); } var scaledWidth = (int)(image.Width * (double)DeviceDpi / 96); var scaledHeight = (int)(image.Height * (double)DeviceDpi / 96); Rectangle rect = new Rectangle(0, 0, scaledWidth, scaledHeight); if ((!Enabled) && (null == ImageDisabled)) { using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size)) { if (imageAttr != null) { using (Graphics gMono = Graphics.FromImage(bitmapMono)) { gMono.DrawImage(image, new Point[3] {new Point(0, 0), new Point(scaledWidth - 1, 0), new Point(0, scaledHeight - 1) }, rect, GraphicsUnit.Pixel, imageAttr); } } ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor); } } else { // Three points provided are upper-left, upper-right and // lower-left of the destination parallelogram. Point[] pts = new Point[3]; pts[0].X = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0; pts[0].Y = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0; pts[1].X = pts[0].X + ClientRectangle.Width; pts[1].Y = pts[0].Y; pts[2].X = pts[0].X; pts[2].Y = pts[1].Y + ClientRectangle.Height; if (imageAttr == null) g.DrawImage(image, pts, rect, GraphicsUnit.Pixel); else g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr); } } private void DrawText(Graphics g) { if (Text == string.Empty) return; Rectangle rect = ClientRectangle; rect.X += BorderWidth; rect.Y += BorderWidth; rect.Width -= 2 * BorderWidth; rect.Height -= 2 * BorderWidth; StringFormat stringFormat = new StringFormat(); if (TextAlign == ContentAlignment.TopLeft) { stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Near; } else if (TextAlign == ContentAlignment.TopCenter) { stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Near; } else if (TextAlign == ContentAlignment.TopRight) { stringFormat.Alignment = StringAlignment.Far; stringFormat.LineAlignment = StringAlignment.Near; } else if (TextAlign == ContentAlignment.MiddleLeft) { stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Center; } else if (TextAlign == ContentAlignment.MiddleCenter) { stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center; } else if (TextAlign == ContentAlignment.MiddleRight) { stringFormat.Alignment = StringAlignment.Far; stringFormat.LineAlignment = StringAlignment.Center; } else if (TextAlign == ContentAlignment.BottomLeft) { stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Far; } else if (TextAlign == ContentAlignment.BottomCenter) { stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Far; } else if (TextAlign == ContentAlignment.BottomRight) { stringFormat.Alignment = StringAlignment.Far; stringFormat.LineAlignment = StringAlignment.Far; } using (Brush brush = new SolidBrush(ForeColor)) { g.DrawString(Text, Font, brush, rect, stringFormat); } } private void DrawBorder(Graphics g) { ButtonBorderStyle bs; // Decide on the type of border to draw around image if (!this.Enabled) bs = IsPopup ? ButtonBorderStyle.Outset : ButtonBorderStyle.Solid; else if (m_mouseOver && m_mouseCapture) bs = ButtonBorderStyle.Inset; else if (IsPopup || m_mouseOver) bs = ButtonBorderStyle.Outset; else bs = ButtonBorderStyle.Solid; Color colorLeftTop; Color colorRightBottom; if (bs == ButtonBorderStyle.Solid) { colorLeftTop = this.BackColor; colorRightBottom = this.BackColor; } else if (bs == ButtonBorderStyle.Outset) { colorLeftTop = m_borderColor.IsEmpty ? this.BackColor : m_borderColor; colorRightBottom = this.BackColor; } else { colorLeftTop = this.BackColor; colorRightBottom = m_borderColor.IsEmpty ? this.BackColor : m_borderColor; } ControlPaint.DrawBorder(g, this.ClientRectangle, colorLeftTop, m_borderWidth, bs, colorLeftTop, m_borderWidth, bs, colorRightBottom, m_borderWidth, bs, colorRightBottom, m_borderWidth, bs); } /// <exclude/> protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); if (Enabled == false) { m_mouseOver = false; m_mouseCapture = false; if (RepeatClick && ClickStatus != RepeatClickStatus.Stopped) ClickStatus = RepeatClickStatus.Stopped; } Invalidate(); } } }
// 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.Runtime.Serialization { [System.AttributeUsageAttribute((System.AttributeTargets)(12), Inherited=false, AllowMultiple=false)] public sealed partial class CollectionDataContractAttribute : System.Attribute { public CollectionDataContractAttribute() { } public bool IsItemNameSetExplicitly { get { throw null; } } public bool IsKeyNameSetExplicitly { get { throw null; } } public bool IsNameSetExplicitly { get { throw null; } } public bool IsNamespaceSetExplicitly { get { throw null; } } public bool IsReference { get { throw null; } set { } } public bool IsReferenceSetExplicitly { get { throw null; } } public bool IsValueNameSetExplicitly { get { throw null; } } public string ItemName { get { throw null; } set { } } public string KeyName { get { throw null; } set { } } public string Name { get { throw null; } set { } } public string Namespace { get { throw null; } set { } } public string ValueName { get { throw null; } set { } } } [System.AttributeUsageAttribute((System.AttributeTargets)(3), Inherited=false, AllowMultiple=true)] public sealed partial class ContractNamespaceAttribute : System.Attribute { public ContractNamespaceAttribute(string contractNamespace) { } public string ClrNamespace { get { throw null; } set { } } public string ContractNamespace { get { throw null; } } } [System.AttributeUsageAttribute((System.AttributeTargets)(28), Inherited=false, AllowMultiple=false)] public sealed partial class DataContractAttribute : System.Attribute { public DataContractAttribute() { } public bool IsNameSetExplicitly { get { throw null; } } public bool IsNamespaceSetExplicitly { get { throw null; } } public bool IsReference { get { throw null; } set { } } public bool IsReferenceSetExplicitly { get { throw null; } } public string Name { get { throw null; } set { } } public string Namespace { get { throw null; } set { } } } public abstract partial class DataContractResolver { protected DataContractResolver() { } public abstract System.Type ResolveName(string typeName, string typeNamespace, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver); public abstract bool TryResolveType(System.Type type, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace); } public sealed partial class DataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer { public DataContractSerializer(System.Type type) { } public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { } //CODEDOM public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, System.Runtime.Serialization.IDataContractSurrogate dataContractSurrogate) { } //CODEDOM public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, System.Runtime.Serialization.IDataContractSurrogate dataContractSurrogate, System.Runtime.Serialization.DataContractResolver dataContractResolver) { } public DataContractSerializer(System.Type type, System.Runtime.Serialization.DataContractSerializerSettings settings) { } public DataContractSerializer(System.Type type, string rootName, string rootNamespace) { } public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { } //CODEDOM public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, System.Runtime.Serialization.IDataContractSurrogate dataContractSurrogate) { } //CODEDOM public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, System.Runtime.Serialization.IDataContractSurrogate dataContractSurrogate, System.Runtime.Serialization.DataContractResolver dataContractResolver) { } public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace) { } public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { } //CODEDOM public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, System.Runtime.Serialization.IDataContractSurrogate dataContractSurrogate) { } //CODEDOM public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, System.Runtime.Serialization.IDataContractSurrogate dataContractSurrogate, System.Runtime.Serialization.DataContractResolver dataContractResolver) { } public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } } //CODEDOM public System.Runtime.Serialization.IDataContractSurrogate DataContractSurrogate { get { throw null; } } public bool IgnoreExtensionDataObject { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyCollection<System.Type> KnownTypes { get { throw null; } } public int MaxItemsInObjectGraph { get { throw null; } } public bool PreserveObjectReferences { get { throw null; } } public bool SerializeReadOnlyTypes { get { throw null; } } public override bool IsStartObject(System.Xml.XmlDictionaryReader reader) { throw null; } public override bool IsStartObject(System.Xml.XmlReader reader) { throw null; } public override object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; } public object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName, System.Runtime.Serialization.DataContractResolver dataContractResolver) { throw null; } public override object ReadObject(System.Xml.XmlReader reader) { throw null; } public override object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; } public override void WriteEndObject(System.Xml.XmlDictionaryWriter writer) { } public override void WriteEndObject(System.Xml.XmlWriter writer) { } public void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph, System.Runtime.Serialization.DataContractResolver dataContractResolver) { } public override void WriteObject(System.Xml.XmlWriter writer, object graph) { } public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph) { } public override void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { } public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph) { } public override void WriteStartObject(System.Xml.XmlWriter writer, object graph) { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static partial class DataContractSerializerExtensions { public static System.Runtime.Serialization.ISerializationSurrogateProvider GetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer) { throw null; } public static void SetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer, System.Runtime.Serialization.ISerializationSurrogateProvider provider) { } } public partial class DataContractSerializerSettings { public DataContractSerializerSettings() { } public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } set { } } //CODEDOM public System.Runtime.Serialization.IDataContractSurrogate DataContractSurrogate { get { throw null; } set { } } public bool IgnoreExtensionDataObject { get { throw null; } set { } } public System.Collections.Generic.IEnumerable<System.Type> KnownTypes { get { throw null; } set { } } public int MaxItemsInObjectGraph { get { throw null; } set { } } public bool PreserveObjectReferences { get { throw null; } set { } } public System.Xml.XmlDictionaryString RootName { get { throw null; } set { } } public System.Xml.XmlDictionaryString RootNamespace { get { throw null; } set { } } public bool SerializeReadOnlyTypes { get { throw null; } set { } } } [System.AttributeUsageAttribute((System.AttributeTargets)(384), Inherited=false, AllowMultiple=false)] public sealed partial class DataMemberAttribute : System.Attribute { public DataMemberAttribute() { } public bool EmitDefaultValue { get { throw null; } set { } } public bool IsNameSetExplicitly { get { throw null; } } public bool IsRequired { get { throw null; } set { } } public string Name { get { throw null; } set { } } public int Order { get { throw null; } set { } } } public partial class DateTimeFormat { public DateTimeFormat(string formatString) { } public DateTimeFormat(string formatString, System.IFormatProvider formatProvider) { } public System.Globalization.DateTimeStyles DateTimeStyles { get { throw null; } set { } } public System.IFormatProvider FormatProvider { get { throw null; } } public string FormatString { get { throw null; } } } public enum EmitTypeInformation { Always = 1, AsNeeded = 0, Never = 2, } [System.AttributeUsageAttribute((System.AttributeTargets)(256), Inherited=false, AllowMultiple=false)] public sealed partial class EnumMemberAttribute : System.Attribute { public EnumMemberAttribute() { } public bool IsValueSetExplicitly { get { throw null; } } public string Value { get { throw null; } set { } } } public partial class ExportOptions { public ExportOptions() { } //CODEDOM public System.Runtime.Serialization.IDataContractSurrogate DataContractSurrogate { get { throw null; } set { } } public System.Collections.ObjectModel.Collection<System.Type> KnownTypes { get { throw null; } } } public sealed partial class ExtensionDataObject { internal ExtensionDataObject() { } } [System.CLSCompliantAttribute(false)] public abstract partial class Formatter : System.Runtime.Serialization.IFormatter { protected System.Runtime.Serialization.ObjectIDGenerator m_idGenerator; protected System.Collections.Queue m_objectQueue; protected Formatter() { } public abstract System.Runtime.Serialization.SerializationBinder Binder { get; set; } public abstract System.Runtime.Serialization.StreamingContext Context { get; set; } public abstract System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; } public abstract object Deserialize(System.IO.Stream serializationStream); protected virtual object GetNext(out long objID) { objID = default(long); throw null; } protected virtual long Schedule(object obj) { throw null; } public abstract void Serialize(System.IO.Stream serializationStream, object graph); protected abstract void WriteArray(object obj, string name, System.Type memberType); protected abstract void WriteBoolean(bool val, string name); protected abstract void WriteByte(byte val, string name); protected abstract void WriteChar(char val, string name); protected abstract void WriteDateTime(System.DateTime val, string name); protected abstract void WriteDecimal(decimal val, string name); protected abstract void WriteDouble(double val, string name); protected abstract void WriteInt16(short val, string name); protected abstract void WriteInt32(int val, string name); protected abstract void WriteInt64(long val, string name); protected virtual void WriteMember(string memberName, object data) { } protected abstract void WriteObjectRef(object obj, string name, System.Type memberType); [System.CLSCompliantAttribute(false)] protected abstract void WriteSByte(sbyte val, string name); protected abstract void WriteSingle(float val, string name); protected abstract void WriteTimeSpan(System.TimeSpan val, string name); [System.CLSCompliantAttribute(false)] protected abstract void WriteUInt16(ushort val, string name); [System.CLSCompliantAttribute(false)] protected abstract void WriteUInt32(uint val, string name); [System.CLSCompliantAttribute(false)] protected abstract void WriteUInt64(ulong val, string name); protected abstract void WriteValueType(object obj, string name, System.Type memberType); } public partial class FormatterConverter : System.Runtime.Serialization.IFormatterConverter { public FormatterConverter() { } public object Convert(object value, System.Type type) { throw null; } public object Convert(object value, System.TypeCode typeCode) { throw null; } public bool ToBoolean(object value) { throw null; } public byte ToByte(object value) { throw null; } public char ToChar(object value) { throw null; } public System.DateTime ToDateTime(object value) { throw null; } public decimal ToDecimal(object value) { throw null; } public double ToDouble(object value) { throw null; } public short ToInt16(object value) { throw null; } public int ToInt32(object value) { throw null; } public long ToInt64(object value) { throw null; } [System.CLSCompliantAttribute(false)] public sbyte ToSByte(object value) { throw null; } public float ToSingle(object value) { throw null; } public string ToString(object value) { throw null; } [System.CLSCompliantAttribute(false)] public ushort ToUInt16(object value) { throw null; } [System.CLSCompliantAttribute(false)] public uint ToUInt32(object value) { throw null; } [System.CLSCompliantAttribute(false)] public ulong ToUInt64(object value) { throw null; } } public static partial class FormatterServices { public static void CheckTypeSecurity(System.Type t, System.Runtime.Serialization.Formatters.TypeFilterLevel securityLevel) { } public static object[] GetObjectData(object obj, System.Reflection.MemberInfo[] members) { throw null; } public static object GetSafeUninitializedObject(System.Type type) { throw null; } public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type) { throw null; } public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type, System.Runtime.Serialization.StreamingContext context) { throw null; } public static System.Runtime.Serialization.ISerializationSurrogate GetSurrogateForCyclicalReference(System.Runtime.Serialization.ISerializationSurrogate innerSurrogate) { throw null; } public static System.Type GetTypeFromAssembly(System.Reflection.Assembly assem, string name) { throw null; } public static object GetUninitializedObject(System.Type type) { throw null; } public static object PopulateObjectMembers(object obj, System.Reflection.MemberInfo[] members, object[] data) { throw null; } } public partial interface IDeserializationCallback { void OnDeserialization(object sender); } public partial interface IExtensibleDataObject { System.Runtime.Serialization.ExtensionDataObject ExtensionData { get; set; } } public partial interface IFormatter { System.Runtime.Serialization.SerializationBinder Binder { get; set; } System.Runtime.Serialization.StreamingContext Context { get; set; } System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; } object Deserialize(System.IO.Stream serializationStream); void Serialize(System.IO.Stream serializationStream, object graph); } [System.CLSCompliantAttribute(false)] public partial interface IFormatterConverter { object Convert(object value, System.Type type); object Convert(object value, System.TypeCode typeCode); bool ToBoolean(object value); byte ToByte(object value); char ToChar(object value); System.DateTime ToDateTime(object value); decimal ToDecimal(object value); double ToDouble(object value); short ToInt16(object value); int ToInt32(object value); long ToInt64(object value); sbyte ToSByte(object value); float ToSingle(object value); string ToString(object value); ushort ToUInt16(object value); uint ToUInt32(object value); ulong ToUInt64(object value); } [System.AttributeUsageAttribute((System.AttributeTargets)(384), Inherited=false, AllowMultiple=false)] public sealed partial class IgnoreDataMemberAttribute : System.Attribute { public IgnoreDataMemberAttribute() { } } public partial class InvalidDataContractException : System.Exception { public InvalidDataContractException() { } protected InvalidDataContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public InvalidDataContractException(string message) { } public InvalidDataContractException(string message, System.Exception innerException) { } } public partial interface IObjectReference { object GetRealObject(System.Runtime.Serialization.StreamingContext context); } public partial interface ISafeSerializationData { void CompleteDeserialization(object deserialized); } public partial interface ISerializable { void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context); } public partial interface ISerializationSurrogate { void GetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context); object SetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISurrogateSelector selector); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public partial interface ISerializationSurrogateProvider { object GetDeserializedObject(object obj, System.Type targetType); object GetObjectToSerialize(object obj, System.Type targetType); System.Type GetSurrogateType(System.Type type); } public partial interface ISurrogateSelector { void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector); System.Runtime.Serialization.ISurrogateSelector GetNextSelector(); System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector); } [System.AttributeUsageAttribute((System.AttributeTargets)(12), Inherited=true, AllowMultiple=true)] public sealed partial class KnownTypeAttribute : System.Attribute { public KnownTypeAttribute(string methodName) { } public KnownTypeAttribute(System.Type type) { } public string MethodName { get { throw null; } } public System.Type Type { get { throw null; } } } public partial class ObjectIDGenerator { public ObjectIDGenerator() { } public virtual long GetId(object obj, out bool firstTime) { firstTime = default(bool); throw null; } public virtual long HasId(object obj, out bool firstTime) { firstTime = default(bool); throw null; } } public partial class ObjectManager { public ObjectManager(System.Runtime.Serialization.ISurrogateSelector selector, System.Runtime.Serialization.StreamingContext context) { } public virtual void DoFixups() { } public virtual object GetObject(long objectID) { throw null; } public virtual void RaiseDeserializationEvent() { } public void RaiseOnDeserializingEvent(object obj) { } public virtual void RecordArrayElementFixup(long arrayToBeFixed, int index, long objectRequired) { } public virtual void RecordArrayElementFixup(long arrayToBeFixed, int[] indices, long objectRequired) { } public virtual void RecordDelayedFixup(long objectToBeFixed, string memberName, long objectRequired) { } public virtual void RecordFixup(long objectToBeFixed, System.Reflection.MemberInfo member, long objectRequired) { } public virtual void RegisterObject(object obj, long objectID) { } public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info) { } public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member) { } public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member, int[] arrayIndex) { } } [System.AttributeUsageAttribute((System.AttributeTargets)(64), Inherited=false)] public sealed partial class OnDeserializedAttribute : System.Attribute { public OnDeserializedAttribute() { } } [System.AttributeUsageAttribute((System.AttributeTargets)(64), Inherited=false)] public sealed partial class OnDeserializingAttribute : System.Attribute { public OnDeserializingAttribute() { } } [System.AttributeUsageAttribute((System.AttributeTargets)(64), Inherited=false)] public sealed partial class OnSerializedAttribute : System.Attribute { public OnSerializedAttribute() { } } [System.AttributeUsageAttribute((System.AttributeTargets)(64), Inherited=false)] public sealed partial class OnSerializingAttribute : System.Attribute { public OnSerializingAttribute() { } } [System.AttributeUsageAttribute((System.AttributeTargets)(256), Inherited=false)] public sealed partial class OptionalFieldAttribute : System.Attribute { public OptionalFieldAttribute() { } public int VersionAdded { get { throw null; } set { } } } public sealed partial class SafeSerializationEventArgs : System.EventArgs { internal SafeSerializationEventArgs() { } public System.Runtime.Serialization.StreamingContext StreamingContext { get { throw null; } } public void AddSerializedState(System.Runtime.Serialization.ISafeSerializationData serializedState) { } } public abstract partial class SerializationBinder { protected SerializationBinder() { } public virtual void BindToName(System.Type serializedType, out string assemblyName, out string typeName) { assemblyName = default(string); typeName = default(string); } public abstract System.Type BindToType(string assemblyName, string typeName); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SerializationEntry { public string Name { get { throw null; } } public System.Type ObjectType { get { throw null; } } public object Value { get { throw null; } } } public partial class SerializationException : System.SystemException { public SerializationException() { } protected SerializationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SerializationException(string message) { } public SerializationException(string message, System.Exception innerException) { } } public sealed partial class SerializationInfo { [System.CLSCompliantAttribute(false)] public SerializationInfo(System.Type type, System.Runtime.Serialization.IFormatterConverter converter) { } [System.CLSCompliantAttribute(false)] public SerializationInfo(System.Type type, System.Runtime.Serialization.IFormatterConverter converter, bool requireSameTokenInPartialTrust) { } public string AssemblyName { get { throw null; } set { } } public string FullTypeName { get { throw null; } set { } } public bool IsAssemblyNameSetExplicit { get { throw null; } } public bool IsFullTypeNameSetExplicit { get { throw null; } } public int MemberCount { get { throw null; } } public System.Type ObjectType { get { throw null; } } public void AddValue(string name, bool value) { } public void AddValue(string name, byte value) { } public void AddValue(string name, char value) { } public void AddValue(string name, System.DateTime value) { } public void AddValue(string name, decimal value) { } public void AddValue(string name, double value) { } public void AddValue(string name, short value) { } public void AddValue(string name, int value) { } public void AddValue(string name, long value) { } public void AddValue(string name, object value) { } public void AddValue(string name, object value, System.Type type) { } [System.CLSCompliantAttribute(false)] public void AddValue(string name, sbyte value) { } public void AddValue(string name, float value) { } [System.CLSCompliantAttribute(false)] public void AddValue(string name, ushort value) { } [System.CLSCompliantAttribute(false)] public void AddValue(string name, uint value) { } [System.CLSCompliantAttribute(false)] public void AddValue(string name, ulong value) { } public bool GetBoolean(string name) { throw null; } public byte GetByte(string name) { throw null; } public char GetChar(string name) { throw null; } public System.DateTime GetDateTime(string name) { throw null; } public decimal GetDecimal(string name) { throw null; } public double GetDouble(string name) { throw null; } public System.Runtime.Serialization.SerializationInfoEnumerator GetEnumerator() { throw null; } public short GetInt16(string name) { throw null; } public int GetInt32(string name) { throw null; } public long GetInt64(string name) { throw null; } [System.CLSCompliantAttribute(false)] public sbyte GetSByte(string name) { throw null; } public float GetSingle(string name) { throw null; } public string GetString(string name) { throw null; } [System.CLSCompliantAttribute(false)] public ushort GetUInt16(string name) { throw null; } [System.CLSCompliantAttribute(false)] public uint GetUInt32(string name) { throw null; } [System.CLSCompliantAttribute(false)] public ulong GetUInt64(string name) { throw null; } public object GetValue(string name, System.Type type) { throw null; } public void SetType(System.Type type) { } } public sealed partial class SerializationInfoEnumerator : System.Collections.IEnumerator { internal SerializationInfoEnumerator() { } public System.Runtime.Serialization.SerializationEntry Current { get { throw null; } } public string Name { get { throw null; } } public System.Type ObjectType { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public object Value { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public sealed partial class SerializationObjectManager { public SerializationObjectManager(System.Runtime.Serialization.StreamingContext context) { } public void RaiseOnSerializedEvent() { } public void RegisterObject(object obj) { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct StreamingContext { public StreamingContext(System.Runtime.Serialization.StreamingContextStates state) { throw null;} public StreamingContext(System.Runtime.Serialization.StreamingContextStates state, object additional) { throw null;} public object Context { get { throw null; } } public System.Runtime.Serialization.StreamingContextStates State { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } [System.FlagsAttribute] public enum StreamingContextStates { All = 255, Clone = 64, CrossAppDomain = 128, CrossMachine = 2, CrossProcess = 1, File = 4, Other = 32, Persistence = 8, Remoting = 16, } public partial class SurrogateSelector : System.Runtime.Serialization.ISurrogateSelector { public SurrogateSelector() { } public virtual void AddSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISerializationSurrogate surrogate) { } public virtual void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector) { } public virtual System.Runtime.Serialization.ISurrogateSelector GetNextSelector() { throw null; } public virtual System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector) { selector = default(System.Runtime.Serialization.ISurrogateSelector); throw null; } public virtual void RemoveSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context) { } } public abstract partial class XmlObjectSerializer { protected XmlObjectSerializer() { } public abstract bool IsStartObject(System.Xml.XmlDictionaryReader reader); public virtual bool IsStartObject(System.Xml.XmlReader reader) { throw null; } public virtual object ReadObject(System.IO.Stream stream) { throw null; } public virtual object ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; } public abstract object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName); public virtual object ReadObject(System.Xml.XmlReader reader) { throw null; } public virtual object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; } public abstract void WriteEndObject(System.Xml.XmlDictionaryWriter writer); public virtual void WriteEndObject(System.Xml.XmlWriter writer) { } public virtual void WriteObject(System.IO.Stream stream, object graph) { } public virtual void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph) { } public virtual void WriteObject(System.Xml.XmlWriter writer, object graph) { } public abstract void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph); public virtual void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { } public abstract void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph); public virtual void WriteStartObject(System.Xml.XmlWriter writer, object graph) { } } public static partial class XmlSerializableServices { public static void AddDefaultSchema(System.Xml.Schema.XmlSchemaSet schemas, System.Xml.XmlQualifiedName typeQName) { } public static System.Xml.XmlNode[] ReadNodes(System.Xml.XmlReader xmlReader) { throw null; } public static void WriteNodes(System.Xml.XmlWriter xmlWriter, System.Xml.XmlNode[] nodes) { } } public static partial class XPathQueryGenerator { public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { namespaces = default(System.Xml.XmlNamespaceManager); throw null; } public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, out System.Xml.XmlNamespaceManager namespaces) { namespaces = default(System.Xml.XmlNamespaceManager); throw null; } } public partial class XsdDataContractExporter { public XsdDataContractExporter() { } public XsdDataContractExporter(System.Xml.Schema.XmlSchemaSet schemas) { } public System.Runtime.Serialization.ExportOptions Options { get { throw null; } set { } } public System.Xml.Schema.XmlSchemaSet Schemas { get { throw null; } } public bool CanExport(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { throw null; } public bool CanExport(System.Collections.Generic.ICollection<System.Type> types) { throw null; } public bool CanExport(System.Type type) { throw null; } public void Export(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { } public void Export(System.Collections.Generic.ICollection<System.Type> types) { } public void Export(System.Type type) { } public System.Xml.XmlQualifiedName GetRootElementName(System.Type type) { throw null; } public System.Xml.Schema.XmlSchemaType GetSchemaType(System.Type type) { throw null; } public System.Xml.XmlQualifiedName GetSchemaTypeName(System.Type type) { throw null; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC.Version1_6 { using Microsoft.Azure; using Microsoft.Azure.Graph; using Microsoft.Azure.Graph.RBAC; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The Graph RBAC Management Client /// </summary> public partial class GraphRbacManagementClient : ServiceClient<GraphRbacManagementClient>, IGraphRbacManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Client API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// The tenant ID. /// </summary> public string TenantID { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IObjectsOperations. /// </summary> public virtual IObjectsOperations Objects { get; private set; } /// <summary> /// Gets the IApplicationsOperations. /// </summary> public virtual IApplicationsOperations Applications { get; private set; } /// <summary> /// Gets the IGroupsOperations. /// </summary> public virtual IGroupsOperations Groups { get; private set; } /// <summary> /// Gets the IServicePrincipalsOperations. /// </summary> public virtual IServicePrincipalsOperations ServicePrincipals { get; private set; } /// <summary> /// Gets the IUsersOperations. /// </summary> public virtual IUsersOperations Users { get; private set; } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected GraphRbacManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected GraphRbacManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected GraphRbacManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected GraphRbacManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public GraphRbacManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public GraphRbacManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public GraphRbacManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the GraphRbacManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public GraphRbacManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Objects = new ObjectsOperations(this); Applications = new ApplicationsOperations(this); Groups = new GroupsOperations(this); ServicePrincipals = new ServicePrincipalsOperations(this); Users = new UsersOperations(this); BaseUri = new System.Uri("https://graph.windows.net"); ApiVersion = "1.6"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// // Salsa Binding Generator // // Licence: BSD3 (see LICENSE) // using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; using System.Linq; namespace Generator { class Generator { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: {0} [input-files]", Path.GetFileName(Environment.GetCommandLineArgs()[0])); } else new Generator().Run(args); } private TextWriter w; private Set<string> _labels = new Set<string>(); private Set<string> _invokers = new Set<string>(); /// <summary> /// Instead of using long strings for identifiers inside the binding, we generate /// shorter, unique ids using this dictionary. /// </summary> private Dictionary<string, long> _uniqueIds = new Dictionary<string, long>(); /// <summary> /// Set of types that are required by the types generated so far. /// </summary> private Set<Type> _requiredTypes = new Set<Type>(); /// <summary> /// Set of types that have been generated so far. /// </summary> private Set<Type> _generatedTypes = new Set<Type>(); /// <summary> /// Set of types that were originally requested to be generated. /// </summary> private Set<Type> _requestedTypes = new Set<Type>(); private Dictionary<Type, List<string>> _requestedMembers = new Dictionary<Type, List<string>>(); private long GetUnique(params string[] keys) { string key = Util.Join("\0", keys); // Combine the keys long id; if (_uniqueIds.TryGetValue(key, out id)) return id; else { id = _uniqueIds.Count + 1; _uniqueIds.Add(key, id); return id; } } private void RequestAll(Type t) { _requestedTypes.Add(t); List<string> ms;// = new List<string>(); if (!_requestedMembers.TryGetValue(t, out ms)) ms = new List<string>(); foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)) ms.Add(mi.Name); _requestedMembers[t] = ms; } private void Request(Type t, params string[] members) { _requestedTypes.Add(t); List<string> ms;// = new List<string>(); if (!_requestedMembers.TryGetValue(t, out ms)) ms = new List<string>(); ms.AddRange(members); _requestedMembers[t] = ms; } /// <summary> /// Returns true iff the given member 'm' in type 't' has been requested, /// either directly or indirectly (i.e. if 'm' is inherited from a /// requested member). /// </summary> private bool IsMemberRequested(Type targetType, string m) { List<string> ms; foreach (Type t in EnumerateAncestors(targetType)) { // Was the member requested in a supertype? if (_requestedMembers.TryGetValue(t, out ms)) { if (ms.Contains(m)) return true; } } return false; } private void ReadImports(string path) { List<Assembly> references = new List<Assembly>(); references.Add(Assembly.GetAssembly(typeof(object))); using (StreamReader r = File.OpenText(path)) { string line; while ((line = r.ReadLine()) != null) { if (line.Trim() == string.Empty) continue; if (line.StartsWith("--") || line.StartsWith("#")) continue; string[] sides = line.Split(new char[] { ':', ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries); if (sides[0] == "reference") { if (sides.Length != 2) throw new Exception("Must specify assembly name after 'reference'"); string assemNameOrPath = sides[1]; Assembly assem = null; bool failedToLoad = false; try { assem = Assembly.LoadFile(Path.GetFullPath(assemNameOrPath)); } catch { failedToLoad = true; } if (failedToLoad) try { failedToLoad = false; assem = Assembly.Load(assemNameOrPath); } catch { failedToLoad = true; } if (failedToLoad) throw new Exception("Failed to load reference: '" + assemNameOrPath + "'"); references.Add(assem); } else { string[] members; if (sides.Length > 1) members = sides[1].Split(new char[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); else members = new string[0]; bool foundType = false; foreach (Assembly a in references) { Type t = a.GetType(sides[0]); if (t != null) { if (members.Length > 0 && members[0] == "*") RequestAll(t); else Request(t, members); foundType = true; break; } } if (!foundType) throw new Exception(string.Format( "The type '{0}' does not exist (are you missing an assembly reference?)", sides[0])); } } } } private void Run(string[] args) { string outputPath = @"."; foreach (string arg in args) ReadImports(arg); // Require System.Array (the base class of all arrays), and its // CreateInstance method, because the Salsa library uses it to // instantiate arrays. // Request(typeof(System.Array), "CreateInstance"); using (w = File.CreateText(Path.Combine(outputPath, "Bindings.hs"))) { // Explicitly request all supertypes too (since their members are inherited // by the requested types) foreach (Type requestedType in Enumerable.ToList(_requestedTypes)) { foreach (Type superRequestedType in EnumerateAncestors(requestedType)) { _requestedTypes.Add(superRequestedType); if (_requestedMembers.ContainsKey(requestedType)) Request(superRequestedType, _requestedMembers[requestedType].ToArray()); } } foreach (Type requestedType in _requestedTypes) { RequireType(requestedType); if (!_requestedMembers.ContainsKey(requestedType)) _requestedMembers.Add(requestedType, new List<string>()); } w.WriteLine("{-# LANGUAGE ForeignFunctionInterface, MultiParamTypeClasses, FlexibleInstances, TypeFamilies, TypeOperators, TypeSynonymInstances, UndecidableInstances, DataKinds #-}"); w.WriteLine("module {0} (", "Bindings"); w.WriteLine(" module Labels"); w.WriteLine(" ) where"); w.WriteLine(); w.WriteLine("import Labels"); w.WriteLine("import Foreign.Salsa.Binding"); while (_requiredTypes.Count > 0) { Type t = _requiredTypes.Pop(); if (_generatedTypes.Contains(t)) continue; // Already generated if (IsUnsupportedType(t)) continue; if (IsPrim(t)) continue; // TODO: Support boxed primitive types later. Console.WriteLine("Binding " + t.ToString()); WriteClass(t); _generatedTypes.Add(t); } Console.WriteLine("Generated bindings for {0} classes", _generatedTypes.Count); } using (w = File.CreateText(Path.Combine(outputPath, "Labels.hs"))) { w.WriteLine("{-# LANGUAGE EmptyDataDecls, FlexibleContexts #-}"); w.WriteLine("module Labels where"); w.WriteLine("import Foreign.Salsa (invoke)"); w.WriteLine(); WriteLabels(); WriteInvokers(); } } /// <summary> /// Indicates that a particular type should be generated (if it hasn't /// already been generated). /// </summary> private void RequireType(Type t) { if (!_generatedTypes.Contains(t)) _requiredTypes.Add(t); } private void WriteClass(Type targetType) { // if (targetType.IsArray) // { // // Explicit bindings for array types are not generated by the code generator. // // We only need to generate bindings for the element type, the base type // // (System.Array) (which is always generated) and the parameterised 'Arr t' // // type (see end of this method). // // // Require the element type of the array // RequireType(targetType.GetElementType()); // // return; // } string classLabel = TypeToLabel(targetType); w.WriteLine(); w.WriteLine("--"); w.WriteLine("-- Class: {0}", targetType.FullName); w.WriteLine("--"); w.WriteLine(); // // Write a Salsa.SalsaForeignType instance for this class // // Note: Type.GetType always returns the same instance for a given type, so it is // safe to use 'unsafePerformIO' below. // w.WriteLine("instance SalsaForeignType {0} where", classLabel); w.WriteLine(" foreignTypeOf _ = unsafePerformIO $ type_GetType \"{0}\"", targetType.AssemblyQualifiedName); w.WriteLine(); // TODO: Cache result of 'foreignTypeOf' in an IORef? { // // Instance and static methods // { // Build a list of relevant instance methods for the target class. // Filter out 'override' methods and 'get/set/add/remove' methods. // Also filter out methods with the same name and signature in a base // class (i.e. hide by signature). List<MemberInfo> relevantMethods = new List<MemberInfo>(); // Go down the inheritance tree from object to the target type foreach (Type implementedType in Enumerable.Reverse(EnumerateAncestors(targetType))) { foreach (MethodInfo mi in implementedType.GetMethods( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (mi.IsSpecialName) continue; // Skip get/set/add/remove methods // Skip overridden (virtual but not a new slot) methods if (mi.IsVirtual && (mi.Attributes & MethodAttributes.NewSlot) == 0) continue; // Ignore methods containing parameters of unsupported types, or an // unsupported result type if (IsUnsupportedType(mi.ReturnType) || Enumerable.Any(mi.GetParameters(), delegate(ParameterInfo pi) { return IsUnsupportedType(pi.ParameterType); })) continue; // Remove any methods (from base classes) with this name and signature // (i.e. implement hide-by-signature semantics, like C#) relevantMethods.RemoveAll(delegate(MemberInfo mi2) { return HasSameSignature((MethodInfo)mi, (MethodInfo)mi2); }); relevantMethods.Add(mi); } } // Enumerate over the method groups in the relevant instance methods, // generating bindings for each group foreach (IGrouping<string, MemberInfo> mg in Enumerable.GroupBy<MemberInfo, string>( relevantMethods, delegate(MemberInfo mi) { return (((MethodInfo)mi).IsStatic ? "static " : "") + mi.Name; })) { if (!IsMemberRequested(targetType, Enumerable.First(mg).Name)) continue; w.WriteLine("-- " + mg.Key); WriteMethodGroup(mg, targetType); } } // // Constructors // if (typeof(Delegate).IsAssignableFrom(targetType)) { // Delegate constructors are special, since they accept a normal // Haskell function as an argument WriteDelegateConstructor(targetType); } else { // Build a list of relevant constructors for the target class (if any) List<ConstructorInfo> relevantConstructors = new List<ConstructorInfo>(); foreach (ConstructorInfo ci in targetType.GetConstructors()) { // Ignore methods containing parameters of unsupported types if (Enumerable.Any(ci.GetParameters(), delegate(ParameterInfo pi) { return IsUnsupportedType(pi.ParameterType); })) continue; relevantConstructors.Add(ci); } if (relevantConstructors.Count > 0) { // Generate bindings for the constructors (treated as a single method group) w.WriteLine("-- Constructors"); WriteConstructorGroup(relevantConstructors, targetType); w.WriteLine(); } } // // Instance and static properties // { // Build a list accessors for accessable, non-indexed, properties in the target class List<AccessorInfo<PropertyInfo>> relevantPropertyAccessors = new List<AccessorInfo<PropertyInfo>>(); // Go down the inheritance tree from object to the target type foreach (Type implementedType in Enumerable.Reverse(EnumerateAncestors(targetType))) { foreach (PropertyInfo pi in implementedType.GetProperties( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { // Ignore indexed properties (since they're currently out of scope, FIXME) if (pi.GetIndexParameters().Length > 0) continue; // Ignore properties of unsupported types if (IsUnsupportedType(pi.PropertyType)) continue; foreach (MethodInfo mi in pi.GetAccessors()) { // Skip static properties declared outside of the target type AccessorInfo<PropertyInfo> ai = new AccessorInfo<PropertyInfo>( mi == pi.GetGetMethod() ? AccessorType.Get : AccessorType.Set, pi, mi); // Remove any shadowed properties (from base classes) relevantPropertyAccessors.RemoveAll( delegate(AccessorInfo<PropertyInfo> ai2) { return HasSameSignature(ai.Accessor, ai2.Accessor); }); relevantPropertyAccessors.Add(ai); } } } // Enumerate over the properties and generate attribute bindings for each // pair of get/set accessors foreach (IGrouping<string, AccessorInfo<PropertyInfo>> mg in Enumerable.GroupBy<AccessorInfo<PropertyInfo>, string>( relevantPropertyAccessors, delegate(AccessorInfo<PropertyInfo> ai) { return (ai.Accessor.IsStatic ? "static " : "") + ai.Owner.Name; })) { if (!IsMemberRequested(targetType, Enumerable.First(mg).Owner.Name)) continue; WriteProperty(mg, targetType); } } // // Static and instance events // { // Build a list accessors for events in the target class List<AccessorInfo<EventInfo>> relevantEventAccessors = new List<AccessorInfo<EventInfo>>(); // Go down the inheritance tree from object to the target type foreach (Type implementedType in Enumerable.Reverse(EnumerateAncestors(targetType))) { foreach (EventInfo ei in implementedType.GetEvents( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { // Ignore events of unsupported types if (IsUnsupportedType(ei.EventHandlerType)) continue; foreach (MethodInfo mi in new MethodInfo[] { ei.GetAddMethod(), ei.GetRemoveMethod() }) { // Skip static events declared outside of the target type AccessorInfo<EventInfo> ai = new AccessorInfo<EventInfo>( mi == ei.GetAddMethod() ? AccessorType.Add : AccessorType.Remove, ei, mi); // Remove any shadowed events (from base classes) relevantEventAccessors.RemoveAll( delegate(AccessorInfo<EventInfo> ai2) { return HasSameSignature(ai.Accessor, ai2.Accessor); }); relevantEventAccessors.Add(ai); } } } // Enumerate over the events and generate attribute bindings for each // pair of add/remove accessors foreach (IGrouping<string, AccessorInfo<EventInfo>> mg in Enumerable.GroupBy<AccessorInfo<EventInfo>, string>( relevantEventAccessors, delegate(AccessorInfo<EventInfo> ai) { return (ai.Accessor.IsStatic ? "static " : "") + ai.Owner.Name; })) { if (!IsMemberRequested(targetType, Enumerable.First(mg).Owner.Name)) continue; WriteEvent(mg, targetType); } } // // Instance and static fields // { // Build a list accessible fields in the target class List<FieldInfo> relevantFields = new List<FieldInfo>(); // Go down the inheritance tree from object to the target type foreach (Type implementedType in Enumerable.Reverse(EnumerateAncestors(targetType))) { foreach (FieldInfo fi in implementedType.GetFields( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { // Ignore fields of unsupported types if (IsUnsupportedType(fi.FieldType)) continue; // Remove any shadowed fields (from base classes) relevantFields.RemoveAll( delegate(FieldInfo fi2) { return fi.Name == fi2.Name; }); relevantFields.Add(fi); } } // Enumerate over the fields and generate bindings for each foreach (FieldInfo fi in relevantFields) { if (!IsMemberRequested(targetType, fi.Name)) continue; WriteField(fi, targetType); } } } // // Ancestors // List<Type> supertypes = new List<Type>(); foreach (Type t in EnumerateAncestors(targetType)) supertypes.Add(t); supertypes.AddRange(targetType.GetInterfaces()); // Remove any unsupported types from 'supertypes' foreach (Type t in Enumerable.ToList(supertypes)) { if (IsUnsupportedType(t)) supertypes.Remove(t); } w.WriteLine("type instance SupertypesOf {0} = {1}", ToHaskellType(targetType), Util.JoinSuffix(" ': ", Enumerable.Select<Type, string>(supertypes, delegate(Type t) { return ToHaskellType(t); }), "'[]")); foreach (Type supertype in supertypes) RequireType(supertype); // if (targetType == typeof(System.Array)) // { // // // // Delegate the members of any array type (i.e. any 'Arr t') to System.Array // // // w.WriteLine(); // w.WriteLine("--"); // w.WriteLine("-- 'Arr t' to 'System.Array' delegation code"); // w.WriteLine("--"); // w.WriteLine(); // Console.WriteLine(string.Join(", ", Assembly.GetExecutingAssembly().GetManifestResourceNames())); // using (StreamReader r = new StreamReader( // Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Generator), "Array.hs"))) // { // string line; // while ((line = r.ReadLine()) != null) // w.WriteLine(line); // } // } } /// <summary> /// Generates bindings for a delegate constructor for the given delegate type. /// </summary> private void WriteDelegateConstructor(Type delegateType) { string classLabel = TypeToLabel(delegateType); w.WriteLine(); w.WriteLine("--"); w.WriteLine("-- Delegate: {0}", delegateType.Name); w.WriteLine("--"); w.WriteLine(); if (delegateType != typeof(Delegate) && delegateType != typeof(MulticastDelegate)) { ConstructorInfo constructorCi = delegateType.GetConstructors()[0]; MethodInfo invokerMi = delegateType.GetMethod("Invoke"); string target = TypeToLabel(delegateType); string stubFunction = ToStubName(constructorCi); string wrapperFunction = "wrap_" + stubFunction; string wrapperType = "Type_" + wrapperFunction; ParameterInfo[] parameters = GetParameters(invokerMi); // Generate the base type signature for Haskell implementation of the delegate w.WriteLine("type {0} = {1}", wrapperType, Util.JoinSuffix(" -> ", Enumerable.Select<ParameterInfo, string>(parameters, delegate(ParameterInfo pi) { return ToBaseType(pi.ParameterType); }), ToBaseReturnType(GetMemberReturnType(invokerMi)))); w.WriteLine("foreign import ccall \"wrapper\" {0} :: {1} -> (IO (FunPtr {1}))", wrapperFunction, wrapperType); w.WriteLine(); // Generate the delegate-object-generating stub function w.WriteLine("{{-# NOINLINE {0} #-}}", stubFunction); w.WriteLine("{0} :: {1} -> IO ObjectId", stubFunction, wrapperType); w.WriteLine("{0} = unsafePerformIO $ getDelegateConstructorStub", stubFunction); w.WriteLine(" \"{0}\"", delegateType.AssemblyQualifiedName); w.WriteLine(" {0}", wrapperFunction); w.WriteLine(); // Generate the 'delegate' instance for calling the delegate constructor w.WriteLine("instance Delegate {0} where", target); w.WriteLine(" type DelegateT {0} = {1}", target, Util.JoinSuffix(" -> ", Enumerable.Select<ParameterInfo, string>(parameters, delegate(ParameterInfo pi) { return ToHaskellType(pi.ParameterType); }), ToReturnType(GetMemberReturnType(invokerMi)))); w.WriteLine(" delegate _ handler = {0} (marshalFn{1} handler) >>= unmarshal", stubFunction, parameters.Length); w.WriteLine(); } w.WriteLine(); } /// <summary> /// Generates bindings for a method group containing: all instance methods, /// all static methods, or all instance constructors. /// </summary> private void WriteMethodGroup(IEnumerable<MemberInfo> members, Type forType) { MemberInfo firstMi = Enumerable.First(members); Console.WriteLine(" {0}", firstMi.Name); ParameterInfo[] parameters = GetParameters(firstMi); Type returnType = GetMemberReturnType(firstMi); bool isStatic = IsMemberStatic(firstMi); string label = GetMemberLabel(firstMi); string target = isStatic ? TypeToLabel(forType) : ToHaskellType(forType); // Output the parameter lists for the members of the method group w.WriteLine("type instance Candidates {0} {1} = {2}", target, label, Util.JoinSuffix(" ': ", Enumerable.Select<MemberInfo, string>(members, delegate(MemberInfo mi) { return ToListType(GetParameters(mi)); }), "'[]")); // Output instances for invoking each method group member foreach (MemberInfo mi in members) WriteMethod(mi, forType); w.WriteLine(); // Require the return type of this method RequireType(returnType); } /// <summary> /// Generates bindings for a group of instance constructors. /// </summary> private void WriteConstructorGroup(IEnumerable<ConstructorInfo> members, Type forType) { ConstructorInfo firstCi = Enumerable.First(members); string target = TypeToLabel(forType); string label = "Ctor"; // Output the parameter lists for the constructors w.WriteLine("type instance Candidates {0} {1} = {2}", target, label, Util.JoinSuffix(" ': ", Enumerable.Select<ConstructorInfo, string>(members, delegate(ConstructorInfo ci) { return ToListType(ci.GetParameters()); }), "'[]")); // Output instances for invoking each constructor foreach (ConstructorInfo ci in members) WriteMethod(ci, forType); } /// <summary> /// Generate bindings for a static method, instance method, or instance constructor, /// for use in a particular class (which, in the case of an instance method, may be a /// descendant of the class in which the method was declared). /// </summary> private void WriteMethod(MemberInfo mi, Type forType) { // If the method was declared on the target type (forType), then produce // the FFI stub function (which is called by Invoker instances down the // hierarchy) if (mi.DeclaringType == forType) WriteMethodStub(mi); // Invoker instance: w.WriteLine("instance Invoker {0} {1} {2} where", IsMemberStatic(mi) ? TypeToLabel(forType) : ToHaskellType(forType), GetMemberLabel(mi), ToTupleType(GetParameters(mi))); w.WriteLine(" type Result {0} {1} {2} = {3}", IsMemberStatic(mi) ? TypeToLabel(forType) : ToHaskellType(forType), GetMemberLabel(mi), ToTupleType(GetParameters(mi)), ToReturnType(GetMemberReturnType(mi))); w.WriteLine(" rawInvoke = {0}", ToMethodMarshaler(mi)); // Require any parameter types for this method/constructor foreach (ParameterInfo pi in GetParameters(mi)) RequireType(pi.ParameterType); } /// <summary> /// Returns true iff the given member should be treated as a static member. /// Static methods, static properties, and instance constructors are all /// treated as static members. /// </summary> private bool IsMemberStatic(MemberInfo mi) { if (mi is ConstructorInfo) return true; if (mi is MethodInfo) return ((MethodInfo)mi).IsStatic; if (mi is FieldInfo) return ((FieldInfo)mi).IsStatic; throw new ArgumentException("Expected a ConstructorInfo, MethodInfo or FieldInfo."); } /// <summary> /// Returns the Haskell code for a function that calls the given method, /// constructor, or property accessor, marshaling the arguments and result /// value as necessary. /// </summary> private string ToMethodMarshaler(MemberInfo mi) { return string.Format("marshalMethod{0}{1} {2}", GetParameters(mi).Length, IsMemberStatic(mi) ? "s" : "i", ToStubName(mi)); } /// <summary> /// Generates an FFI stub function for calling a particular .NET method /// or property accessor. /// </summary> private void WriteMethodStub(MemberInfo mi) { // TODO: Perhaps use unboxed string literals? string stubFunction = ToStubName(mi); string stubType = "Type_" + stubFunction; string makeFunction = "make_" + stubFunction; w.WriteLine(); w.WriteLine("-- Foreign Interface Stub for {0}.{1}:", mi.DeclaringType.Name, mi.Name); w.WriteLine("type {0} = {1}{2}", stubType, IsMemberStatic(mi) ? "" : (ToBaseType(mi.DeclaringType) + " -> "), Util.JoinSuffix(" -> ", Enumerable.Select<ParameterInfo, string>(GetParameters(mi), delegate(ParameterInfo pi) { return ToBaseType(pi.ParameterType); }), ToBaseReturnType(GetMemberReturnType(mi)))); w.WriteLine("foreign import ccall \"dynamic\" {0} :: FunPtr {1} -> {1}", makeFunction, stubType); w.WriteLine(); w.WriteLine("{{-# NOINLINE {0} #-}}", stubFunction); w.WriteLine("{0} :: {1}", stubFunction, stubType); w.WriteLine("{0} = {1} $ unsafePerformIO $ getMethodStub", stubFunction, makeFunction); w.WriteLine(" \"{0}\" \"{1}\"", mi.DeclaringType.AssemblyQualifiedName, mi.Name); w.WriteLine(" \"{0}\"", Util.Join(";", Enumerable.Select<ParameterInfo, string>(GetParameters(mi), delegate(ParameterInfo pi) { return ToQualifiedType(pi.ParameterType); }))); w.WriteLine(); } /// <summary> /// Generates FFI stub functions for retrieving or setting a particular .NET field. /// </summary> private void WriteFieldStub(FieldInfo fi, AccessorType accessorType) { bool isGet = (accessorType == AccessorType.Get); string stubFunction = ToStubName(fi) + "_" + (isGet ? "get" : "set"); string stubType = "Type_" + stubFunction; string makeFunction = "make_" + stubFunction; w.WriteLine(); w.WriteLine("-- Field accessor stub for {0}.{1}:", fi.DeclaringType.Name, fi.Name); w.WriteLine("type {0} = {1}{2}{3}", stubType, fi.IsStatic ? "" : (ToBaseType(fi.DeclaringType) + " -> "), isGet ? "" : (ToBaseType(fi.FieldType) + " -> "), isGet ? ToBaseReturnType(fi.FieldType) : "IO ()"); w.WriteLine("foreign import ccall \"dynamic\" {0} :: FunPtr {1} -> {1}", makeFunction, stubType); w.WriteLine(); w.WriteLine("{{-# NOINLINE {0} #-}}", stubFunction); w.WriteLine("{0} :: {1}", stubFunction, stubType); w.WriteLine("{0} = {1} $ unsafePerformIO $ {2}", stubFunction, makeFunction, isGet ? "getFieldGetStub" : "getFieldSetStub"); w.WriteLine(" \"{0}\" \"{1}\"", fi.DeclaringType.AssemblyQualifiedName, fi.Name); w.WriteLine(); } private void WriteProperty(IEnumerable<AccessorInfo<PropertyInfo>> accessors, Type forType) { AccessorInfo<PropertyInfo> firstAccessor = Enumerable.First(accessors); bool isStatic = IsMemberStatic(firstAccessor.Accessor); string target = isStatic ? TypeToLabel(forType) : ToHaskellType(forType); string label = ToLabelType(firstAccessor.Owner.Name); w.WriteLine("instance Prop {0} {1} where", target, label); AccessorInfo<PropertyInfo> getAccessor = Enumerable.FirstOrDefault(accessors, delegate(AccessorInfo<PropertyInfo> ai) { return ai.Type == AccessorType.Get; }); AccessorInfo<PropertyInfo> setAccessor = Enumerable.FirstOrDefault(accessors, delegate(AccessorInfo<PropertyInfo> ai) { return ai.Type == AccessorType.Set; }); if (getAccessor != null) { w.WriteLine(" type PropGT {0} {1} = {2}", target, label, ToHaskellType(getAccessor.Owner.PropertyType)); w.WriteLine(" getProp t pn = {0} t pn ()", ToMethodMarshaler(getAccessor.Accessor)); } else { w.WriteLine(" type PropGT {0} {1} = ()", target, label); w.WriteLine(" getProp _ _ = return ()"); // Return nothing } if (setAccessor != null) { w.WriteLine(" type PropST {0} {1} = {2}", target, label, ToHaskellType(setAccessor.Owner.PropertyType)); w.WriteLine(" setProp = {0}", ToMethodMarshaler(setAccessor.Accessor)); } else { w.WriteLine(" type PropST {0} {1} = ()", target, label); w.WriteLine(" setProp _ _ _ = return ()"); // Do nothing } foreach (AccessorInfo<PropertyInfo> accessor in accessors) { // Generate the get/set stub caller (in declared type only) if (accessor.Accessor.DeclaringType == forType) WriteMethodStub(accessor.Accessor); } w.WriteLine(); } private void WriteEvent(IEnumerable<AccessorInfo<EventInfo>> accessors, Type forType) { AccessorInfo<EventInfo> firstAccessor = Enumerable.First(accessors); bool isStatic = IsMemberStatic(firstAccessor.Accessor); string target = isStatic ? TypeToLabel(forType) : ToHaskellType(forType); string label = ToLabelType(firstAccessor.Owner.Name); w.WriteLine("instance Event {0} {1} where", target, label); w.WriteLine(" type EventT {0} {1} = {2}", target, label, ToHaskellType(firstAccessor.Owner.EventHandlerType)); foreach (AccessorInfo<EventInfo> accessor in accessors) { if (accessor.Type == AccessorType.Add) w.WriteLine(" addEvent = {0}", ToMethodMarshaler(accessor.Accessor)); else // AccessorType.Remove w.WriteLine(" removeEvent = {0}", ToMethodMarshaler(accessor.Accessor)); } foreach (AccessorInfo<EventInfo> accessor in accessors) { // Generate the add/remove stub caller (in declared type only) if (accessor.Accessor.DeclaringType == forType) WriteMethodStub(accessor.Accessor); } w.WriteLine(); // Require the event type of this event RequireType(firstAccessor.Owner.EventHandlerType); } private void WriteField(FieldInfo field, Type forType) { bool isStatic = field.IsStatic; bool isReadOnly = field.IsLiteral || field.IsInitOnly; // TODO: Add support for literal fields. The constant value from // the metadata should be included in the generated code. string target = isStatic ? TypeToLabel(forType) : ToHaskellType(forType); string label = ToLabelType(field.Name); w.WriteLine("instance Prop {0} {1} where", target, label); w.WriteLine(" type PropGT {0} {1} = {2}", target, label, ToHaskellType(field.FieldType)); w.WriteLine(" getProp t pn = marshalMethod0{0} {1}_get t pn ()", isStatic ? "s" : "i", ToStubName(field)); if (!isReadOnly) { w.WriteLine(" type PropST {0} {1} = {2}", target, label, ToHaskellType(field.FieldType)); w.WriteLine(" setProp = marshalMethod1{0} {1}_set", isStatic ? "s" : "i", ToStubName(field)); } else { w.WriteLine(" type PropST {0} {1} = ()", target, label); w.WriteLine(" setProp _ _ _ = return ()"); // Do nothing } // Generate the get/set stub caller (in declared type only) if (field.DeclaringType == forType) { if (!isReadOnly) WriteFieldStub(field, AccessorType.Set); WriteFieldStub(field, AccessorType.Get); } // For readonly fields, generate an IO-less method getting the value if (isReadOnly) { // Ensure that an invoker is generated for invoking the label with '#' ToInvoker(field.Name); w.WriteLine("type instance Candidates {0} {1} = '[]", target, label); w.WriteLine("instance Invoker {0} {1} () where", target, label); w.WriteLine(" type Result {0} {1} () = {2}", target, label, ToHaskellType(field.FieldType)); w.WriteLine(" rawInvoke t m () = unsafePerformIO $ get t m "); } w.WriteLine(); } private string ToHaskellType(Type t) { if (t == typeof(void)) return "()"; if (t == typeof(int)) return "Int32"; if (t == typeof(string)) return "String"; if (t == typeof(bool)) return "Bool"; if (t == typeof(Double)) return "Double"; if (t == typeof(bool?)) return "(Maybe Bool)"; // if (t.IsArray) // return string.Format("(Obj (Arr {0}))", ToHaskellType(t.GetElementType())); return "(Obj " + TypeToLabel(t) + ")"; } private string ToReturnType(Type t) { return "IO " + ToHaskellType(t); } /// <summary> /// Gives the low-level Haskell type for the given .NET type 't'. This is the /// base type used in FFI declarations. /// </summary> private string ToBaseType(Type t) { if (t == typeof(void)) return "()"; if (t == typeof(Int32)) return "Int32"; if (t == typeof(String)) return "SalsaString"; if (t == typeof(Boolean)) return "Bool"; if (t == typeof(Double)) return "Double"; return "ObjectId"; } private string ToBaseReturnType(Type t) { return "IO " + ToBaseType(t); } private bool IsPrim(Type t) { return t == typeof(void) || t == typeof(Int32) || t == typeof(String) || t == typeof(Boolean) || t == typeof(Double); } private bool IsUnsupportedType(Type t) { return t.Name.StartsWith("_") || t.IsByRef || // FIXME: Support this? t.IsPointer || // Salsa doesn't support generic types yet, but there's a special case for Nullable<bool> (t.IsGenericType && t != typeof(Nullable<bool>)) || t.IsGenericParameter || t.IsArray; // Temporarily removed array support // // Salsa only supports arrays of non-generic types at present // (t.IsArray && IsUnsupportedType(t.GetElementType())); } /// <summary> /// Returns a tuple of high-level Haskell types corresponding to the given /// list of method parameters. /// </summary> private string ToTupleType(ParameterInfo[] ts) { return "(" + Util.Join(", ", Enumerable.Select<ParameterInfo, string>(ts, delegate(ParameterInfo pi) { return ToHaskellType(pi.ParameterType); } )) + ")"; } /// <summary> /// Returns a type-level list of high-level Haskell types corresponding to /// the given list of method parameters. /// </summary> private string ToListType(ParameterInfo[] ts) { return "(" + Util.JoinSuffix(" ': ", Enumerable.Select<ParameterInfo, string>(ts, delegate(ParameterInfo pi) { return ToHaskellType(pi.ParameterType); } ), "'[]") + ")"; } /// <summary> /// Returns the name of the raw FFI stub method associated with the given .NET method /// or constructor. There is a unique stub name for every declared method overload, /// and constructor. /// </summary> private string ToStubName(MemberInfo mi) { string parameterDetails = ""; if (mi is ConstructorInfo || mi is MethodInfo) parameterDetails = Util.Join(" ", Enumerable.Select<ParameterInfo, string>(GetParameters(mi), delegate(ParameterInfo pi) { return pi.ParameterType.AssemblyQualifiedName; })); return string.Format("stub_{0}", GetUnique("stub", mi.DeclaringType.AssemblyQualifiedName, mi.Name, parameterDetails)); } /// <summary> /// Returns the name of the FFI wrapper function that is used to wrap Haskell /// functions that implement the given .NET delegate type. /// </summary> private string ToWrapperName(Type dt) { return string.Format("wrap_{0}", GetUnique("wrap", dt.AssemblyQualifiedName)); } /// <summary> /// Returns a string that uniquely identifies the given type. It is /// used to retrieve stub functions for the particular type at runtime. /// </summary> private string ToQualifiedType(Type t) { // Unless the type is in mscorlib, use the (long) assembly qualified name if (t.Assembly == typeof(object).Assembly) return t.FullName; else return t.AssemblyQualifiedName; } private ParameterInfo[] GetParameters(MemberInfo mi) { if (mi is MethodInfo) return ((MethodInfo)mi).GetParameters(); if (mi is ConstructorInfo) return ((ConstructorInfo)mi).GetParameters(); throw new ArgumentException("Must be a MethodInfo or ConstructorInfo.", "mi"); } private Type GetMemberReturnType(MemberInfo mi) { if (mi is MethodInfo) return ((MethodInfo)mi).ReturnType; if (mi is ConstructorInfo) return ((ConstructorInfo)mi).DeclaringType; throw new ArgumentException("Must be a MethodInfo or ConstructorInfo.", "mi"); } private string GetMemberLabel(MemberInfo mi) { if (mi is MethodInfo) return MethodToLabel((MethodInfo)mi); if (mi is ConstructorInfo) return "Ctor"; throw new ArgumentException("Must be a MethodInfo or ConstructorInfo.", "mi"); } /// <summary> /// Returns true iff the given methods have the same name, number and type of /// parameters. /// </summary> private bool HasSameSignature(MethodInfo mi1, MethodInfo mi2) { if (mi1.Name != mi2.Name) return false; ParameterInfo[] pi1 = mi1.GetParameters(); ParameterInfo[] pi2 = mi2.GetParameters(); if (pi1.Length != pi2.Length) return false; for (int i = 0; i < pi1.Length; i++) { if (pi1[i].ParameterType != pi2[i].ParameterType) return false; } return true; } /// <summary> /// Returns an irrefutable Haskell pattern for matching a value of the given type. /// 'index' is included in the identified used (if any). /// </summary> private string ToPattern(Type t, int index) { if (t == typeof(void)) return "()"; if (t == typeof(int) || t == typeof(bool) || t == typeof(string)) return string.Format("a{0}", index); return string.Format("(Obj a{0})", index); } /// <summary> /// Enumerate ancestors of 't', starting with 't' and finishing with object. /// </summary> private IEnumerable<Type> EnumerateAncestors(Type t) { while (t != null) { yield return t; t = t.BaseType; } } private string MethodToLabel(MethodInfo mi) { ToInvoker(mi.Name); return ToLabelType(mi.Name); } private string TypeToLabel(Type t) { if (IsUnsupportedType(t)) return ToLabelType("NotSupported"); if (t.IsNested && t.DeclaringType != null) { // FIXME: This only handles one level of nested classes // (and it doesn't handle nested generic types) return ToLabelType(t.DeclaringType.Name + "_" + t.Name); } else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) { return string.Format("(Maybe {0})", TypeToLabel(t.GetGenericArguments()[0])); } else return ToLabelType(t.Name); } private string ToLabelHelper(string s) { if (string.IsNullOrEmpty(s)) throw new ArgumentException("Expected non-empty string."); s = char.ToUpper(s[0]) + s.Substring(1); if (!_labels.Contains(s) && s != "Object" && s != "Type" && s != "Array") // These labels are defined in the Salsa library _labels.Add(s); return s; } private string ToLabelValue(string s) { return "_" + ToLabelHelper(s); } private string ToLabelType(string s) { return ToLabelHelper(s) + "_"; } private void WriteLabels() { w.WriteLine("-- Labels for .NET types, methods, properties, fields and events"); foreach (string label in _labels) w.WriteLine("data {0,-25}", ToLabelType(label)); w.WriteLine(); foreach (string label in _labels) w.WriteLine("{0,-30} = undefined :: {1}", ToLabelValue(label), ToLabelType(label)); w.WriteLine(); } private string ToInvoker(string s) { s = Util.ToLowerFirst(s); if (!_invokers.Contains(s)) _invokers.Add(s); return "_" + s; } private void WriteInvokers() { w.WriteLine("-- Functions for invoking methods with '#'"); foreach (string invoker in _invokers) { // Output an invoker (and a unit invoker, for convenience and consistency) w.WriteLine("{0} args target = invoke target {1} args", ToInvoker(invoker), ToLabelValue(invoker)); w.WriteLine("{0}_ target = invoke target {1} ()", ToInvoker(invoker), ToLabelValue(invoker)); } w.WriteLine(); } } public static class Util { public static string Join(string separator, IEnumerable<string> xs) { StringBuilder sb = new StringBuilder(); foreach (string x in xs) { sb.Append(x); sb.Append(separator); } if (sb.Length > 0) sb.Length -= separator.Length; return sb.ToString(); } public static string JoinSuffix(string separator, IEnumerable<string> xs, string end) { StringBuilder sb = new StringBuilder(); foreach (string x in xs) { sb.Append(x); sb.Append(separator); } sb.Append(end); return sb.ToString(); } public static string ToLowerFirst(string s) { if (s == "") return ""; return s.Substring(0, 1).ToLower() + s.Substring(1); } public static string ToUpperFirst(string s) { if (s == "") return ""; return s.Substring(0, 1).ToUpper() + s.Substring(1); } } public class AccessorInfo<T> where T : MemberInfo { private AccessorType _type; private T _owner; private MethodInfo _accessor; public AccessorInfo(AccessorType type, T owner, MethodInfo accessor) { _type = type; _owner = owner; _accessor = accessor; } public AccessorType Type { get { return _type; } } public MethodInfo Accessor { get { return _accessor; } } public T Owner { get { return _owner; } } } public enum AccessorType { Get, Set, Add, Remove }; }
// 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.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class SymbolEquivalenceComparerTests { public static readonly CS.CSharpCompilationOptions CSharpDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); public static readonly CS.CSharpCompilationOptions CSharpSignedDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithCryptoKeyFile(SigningTestHelpers.KeyPairFile). WithStrongNameProvider(new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create<string>())); [WpfFact] public async Task TestArraysAreEquivalent() { var csharpCode = @"class C { int intField1; int[] intArrayField1; string[] stringArrayField1; int[][] intArrayArrayField1; int[,] intArrayRank2Field1; System.Int32 int32Field1; int intField2; int[] intArrayField2; string[] stringArrayField2; int[][] intArrayArrayField2; int[,] intArrayRank2Field2; System.Int32 int32Field2; }"; using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode)) { var type = (ITypeSymbol)(await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var intField1 = (IFieldSymbol)type.GetMembers("intField1").Single(); var intArrayField1 = (IFieldSymbol)type.GetMembers("intArrayField1").Single(); var stringArrayField1 = (IFieldSymbol)type.GetMembers("stringArrayField1").Single(); var intArrayArrayField1 = (IFieldSymbol)type.GetMembers("intArrayArrayField1").Single(); var intArrayRank2Field1 = (IFieldSymbol)type.GetMembers("intArrayRank2Field1").Single(); var int32Field1 = (IFieldSymbol)type.GetMembers("int32Field1").Single(); var intField2 = (IFieldSymbol)type.GetMembers("intField2").Single(); var intArrayField2 = (IFieldSymbol)type.GetMembers("intArrayField2").Single(); var stringArrayField2 = (IFieldSymbol)type.GetMembers("stringArrayField2").Single(); var intArrayArrayField2 = (IFieldSymbol)type.GetMembers("intArrayArrayField2").Single(); var intArrayRank2Field2 = (IFieldSymbol)type.GetMembers("intArrayRank2Field2").Single(); var int32Field2 = (IFieldSymbol)type.GetMembers("int32Field2").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField2.Type)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intField1.Type), SymbolEquivalenceComparer.Instance.GetHashCode(intField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField2.Type)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField1.Type), SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field2.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, stringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, intArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, int32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, intField1.Type)); } } [WpfFact] public async Task TestArraysInDifferentLanguagesAreEquivalent() { var csharpCode = @"class C { int intField1; int[] intArrayField1; string[] stringArrayField1; int[][] intArrayArrayField1; int[,] intArrayRank2Field1; System.Int32 int32Field1; }"; var vbCode = @"class C dim intField1 as Integer; dim intArrayField1 as Integer() dim stringArrayField1 as String() dim intArrayArrayField1 as Integer()() dim intArrayRank2Field1 as Integer(,) dim int32Field1 as System.Int32 end class"; using (var csharpWorkspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode)) using (var vbWorkspace = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode)) { var csharpType = (ITypeSymbol)(await csharpWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var vbType = (await vbWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var csharpIntField1 = (IFieldSymbol)csharpType.GetMembers("intField1").Single(); var csharpIntArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayField1").Single(); var csharpStringArrayField1 = (IFieldSymbol)csharpType.GetMembers("stringArrayField1").Single(); var csharpIntArrayArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayArrayField1").Single(); var csharpIntArrayRank2Field1 = (IFieldSymbol)csharpType.GetMembers("intArrayRank2Field1").Single(); var csharpInt32Field1 = (IFieldSymbol)csharpType.GetMembers("int32Field1").Single(); var vbIntField1 = (IFieldSymbol)vbType.GetMembers("intField1").Single(); var vbIntArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayField1").Single(); var vbStringArrayField1 = (IFieldSymbol)vbType.GetMembers("stringArrayField1").Single(); var vbIntArrayArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayArrayField1").Single(); var vbIntArrayRank2Field1 = (IFieldSymbol)vbType.GetMembers("intArrayRank2Field1").Single(); var vbInt32Field1 = (IFieldSymbol)vbType.GetMembers("int32Field1").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbIntArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbStringArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbInt32Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayField1.Type, csharpStringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbIntArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayArrayField1.Type, csharpIntArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayRank2Field1.Type, vbInt32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbIntField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntField1.Type, csharpIntArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbStringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbStringArrayField1.Type, csharpIntArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayRank2Field1.Type, csharpInt32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(vbInt32Field1.Type, csharpIntField1.Type)); } } [WpfFact] public async Task TestFields() { var csharpCode1 = @"class Type1 { int field1; string field2; } class Type2 { bool field3; short field4; }"; var csharpCode2 = @"class Type1 { int field1; short field4; } class Type2 { bool field3; string field2; }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field1_v2 = type1_v2.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); var field2_v2 = type2_v2.GetMembers("field2").Single(); var field3_v1 = type2_v1.GetMembers("field3").Single(); var field3_v2 = type2_v2.GetMembers("field3").Single(); var field4_v1 = type2_v1.GetMembers("field4").Single(); var field4_v2 = type1_v2.GetMembers("field4").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(field1_v1), SymbolEquivalenceComparer.Instance.GetHashCode(field1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2)); } } [WorkItem(538124)] [WpfFact] public async Task TestFieldsAcrossLanguages() { var csharpCode1 = @"class Type1 { int field1; string field2; } class Type2 { bool field3; short field4; }"; var vbCode1 = @"class Type1 dim field1 as Integer; dim field4 as Short; end class class Type2 dim field3 as Boolean; dim field2 as String; end class"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode1)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field1_v2 = type1_v2.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); var field2_v2 = type2_v2.GetMembers("field2").Single(); var field3_v1 = type2_v1.GetMembers("field3").Single(); var field3_v2 = type2_v2.GetMembers("field3").Single(); var field4_v1 = type2_v1.GetMembers("field4").Single(); var field4_v2 = type1_v2.GetMembers("field4").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2)); } } [WpfFact] public async Task TestFieldsInGenericTypes() { var code = @"class C<T> { int foo; C<int> intInstantiation1; C<string> stringInstantiation; C<T> instanceInstantiation; } class D { C<int> intInstantiation2; } "; using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) { var typeC = (await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var typeD = (await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("D").Single(); var intInstantiation1 = (IFieldSymbol)typeC.GetMembers("intInstantiation1").Single(); var stringInstantiation = (IFieldSymbol)typeC.GetMembers("stringInstantiation").Single(); var instanceInstantiation = (IFieldSymbol)typeC.GetMembers("instanceInstantiation").Single(); var intInstantiation2 = (IFieldSymbol)typeD.GetMembers("intInstantiation2").Single(); var foo = typeC.GetMembers("foo").Single(); var foo_intInstantiation1 = intInstantiation1.Type.GetMembers("foo").Single(); var foo_stringInstantiation = stringInstantiation.Type.GetMembers("foo").Single(); var foo_instanceInstantiation = instanceInstantiation.Type.GetMembers("foo").Single(); var foo_intInstantiation2 = intInstantiation2.Type.GetMembers("foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_stringInstantiation)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_stringInstantiation)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo, foo_instanceInstantiation)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo), SymbolEquivalenceComparer.Instance.GetHashCode(foo_instanceInstantiation)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_intInstantiation2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation1), SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation2)); } } [WpfFact] public async Task TestMethodsWithDifferentReturnTypeNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { int Foo() {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [WpfFact] public async Task TestMethodsWithDifferentNamesAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo1() {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [WpfFact] public async Task TestMethodsWithDifferentAritiesAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo<T>() {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [WpfFact] public async Task TestMethodsWithDifferentParametersAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [WpfFact] public async Task TestMethodsWithDifferentTypeParameters() { var csharpCode1 = @"class Type1 { void Foo<A>(A a) {} }"; var csharpCode2 = @"class Type1 { void Foo<B>(B a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WpfFact] public async Task TestMethodsWithSameParameters() { var csharpCode1 = @"class Type1 { void Foo(int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WpfFact] public async Task TestMethodsWithDifferentParameterNames() { var csharpCode1 = @"class Type1 { void Foo(int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int b) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WpfFact] public async Task TestMethodsAreEquivalentOutToRef() { var csharpCode1 = @"class Type1 { void Foo(out int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(ref int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [WpfFact] public async Task TestMethodsNotEquivalentRemoveOut() { var csharpCode1 = @"class Type1 { void Foo(out int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [WpfFact] public async Task TestMethodsAreEquivalentIgnoreParams() { var csharpCode1 = @"class Type1 { void Foo(params int[] a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int[] a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WpfFact] public async Task TestMethodsNotEquivalentDifferentParameterTypes() { var csharpCode1 = @"class Type1 { void Foo(int[] a) {} }"; var csharpCode2 = @"class Type1 { void Foo(string[] a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [WpfFact] public async Task TestMethodsAcrossLanguages() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { T Foo<T>(IList<T> list, int a) {} void Bar() { } }"; var vbCode1 = @" Imports System.Collections.Generic class Type1 function Foo(of U)(list as IList(of U), a as Integer) as U end function sub Quux() end sub end class"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode1)) { var csharpType1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var vbType1 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var csharpFooMethod = csharpType1.GetMembers("Foo").Single(); var csharpBarMethod = csharpType1.GetMembers("Bar").Single(); var vbFooMethod = vbType1.GetMembers("Foo").Single(); var vbQuuxMethod = vbType1.GetMembers("Quux").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod), SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbQuuxMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbQuuxMethod)); } } [WpfFact] public async Task TestMethodsInGenericTypesAcrossLanguages() { var csharpCode1 = @" using System.Collections.Generic; class Type1<X> { T Foo<T>(IList<T> list, X a) {} void Bar(X x) { } }"; var vbCode1 = @" Imports System.Collections.Generic class Type1(of M) function Foo(of U)(list as IList(of U), a as M) as U end function sub Bar(x as Object) end sub end class"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode1)) { var csharpType1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var vbType1 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var csharpFooMethod = csharpType1.GetMembers("Foo").Single(); var csharpBarMethod = csharpType1.GetMembers("Bar").Single(); var vbFooMethod = vbType1.GetMembers("Foo").Single(); var vbBarMethod = vbType1.GetMembers("Bar").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod), SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbBarMethod)); } } [WpfFact] public async Task TestObjectAndDynamicAreNotEqualNormally() { var csharpCode1 = @"class Type1 { object field1; dynamic field2; }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field2_v1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field1_v1)); } } [WpfFact] public async Task TestObjectAndDynamicAreEqualInSignatures() { var csharpCode1 = @"class Type1 { void Foo(object o1) { } }"; var csharpCode2 = @"class Type1 { void Foo(dynamic o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WpfFact] public async Task TestUnequalGenericsInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(IList<int> o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(IList<string> o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); } } [WpfFact] public async Task TestGenericsWithDynamicAndObjectInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(IList<object> o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(IList<dynamic> o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WpfFact] public async Task TestDynamicAndUnrelatedTypeInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(dynamic o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(string o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); } } [WpfFact] public async Task TestNamespaces() { var csharpCode1 = @"namespace Outer { namespace Inner { class Type { } } class Type { } } "; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) { var outer1 = (INamespaceSymbol)(await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetMembers("Outer").Single(); var outer2 = (INamespaceSymbol)(await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetMembers("Outer").Single(); var inner1 = (INamespaceSymbol)outer1.GetMembers("Inner").Single(); var inner2 = (INamespaceSymbol)outer2.GetMembers("Inner").Single(); var outerType1 = outer1.GetTypeMembers("Type").Single(); var outerType2 = outer2.GetTypeMembers("Type").Single(); var innerType1 = inner1.GetTypeMembers("Type").Single(); var innerType2 = inner2.GetTypeMembers("Type").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outer2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(outer2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, inner2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1), SymbolEquivalenceComparer.Instance.GetHashCode(inner2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outerType1, outerType2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outerType1), SymbolEquivalenceComparer.Instance.GetHashCode(outerType2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(innerType1, innerType2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(innerType1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(inner1, outerType1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(outerType1, innerType1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(innerType1, outer1)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(inner1.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, innerType1.ContainingSymbol.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, innerType1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outerType1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(outerType1.ContainingSymbol)); } } [WpfFact] public async Task TestNamedTypesEquivalent() { var csharpCode1 = @" class Type1 { } class Type2<X> { } "; var csharpCode2 = @" class Type1 { void Foo(); } class Type2<Y> { }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var type2_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type1_v1), SymbolEquivalenceComparer.Instance.GetHashCode(type1_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v2, type2_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type2_v1), SymbolEquivalenceComparer.Instance.GetHashCode(type2_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type2_v1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type1_v1)); } } [WpfFact] public async Task TestNamedTypesDifferentIfNameChanges() { var csharpCode1 = @" class Type1 { }"; var csharpCode2 = @" class Type2 { void Foo(); }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [WpfFact] public async Task TestNamedTypesDifferentIfTypeKindChanges() { var csharpCode1 = @" struct Type1 { }"; var csharpCode2 = @" class Type1 { void Foo(); }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [WpfFact] public async Task TestNamedTypesDifferentIfArityChanges() { var csharpCode1 = @" class Type1 { }"; var csharpCode2 = @" class Type1<T> { void Foo(); }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [WpfFact] public async Task TestNamedTypesDifferentIfContainerDifferent() { var csharpCode1 = @" class Outer { class Type1 { } }"; var csharpCode2 = @" class Other { class Type1 { void Foo(); } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var outer = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Outer").Single(); var other = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Other").Single(); var type1_v1 = outer.GetTypeMembers("Type1").Single(); var type1_v2 = other.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [WpfFact] public async Task TestAliasedTypes1() { var csharpCode1 = @" using i = System.Int32; class Type1 { void Foo(i o1) { } }"; var csharpCode2 = @" class Type1 { void Foo(int o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")] [WpfFact] public async Task TestRefVersusOut() { var csharpCode1 = @" class C { void M(out int i) { } }"; var csharpCode2 = @" class C { void M(ref int i) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var method_v1 = type1_v1.GetMembers("M").Single(); var method_v2 = type1_v2.GetMembers("M").Single(); var trueComp = new SymbolEquivalenceComparer(assemblyComparerOpt: null, distinguishRefFromOut: true); var falseComp = new SymbolEquivalenceComparer(assemblyComparerOpt: null, distinguishRefFromOut: false); Assert.False(trueComp.Equals(method_v1, method_v2)); Assert.False(trueComp.Equals(method_v2, method_v1)); // The hashcodes of distinct objects don't have to be distinct. Assert.True(falseComp.Equals(method_v1, method_v2)); Assert.True(falseComp.Equals(method_v2, method_v1)); Assert.Equal(falseComp.GetHashCode(method_v1), falseComp.GetHashCode(method_v2)); } } [WpfFact] public async Task TestCSharpReducedExtensionMethodsAreEquivalent() { var code = @" class Zed {} public static class Extensions { public static void NotGeneric(this Zed z, int data) { } public static void GenericThis<T>(this T me, int data) where T : Zed { } public static void GenericNotThis<T>(this Zed z, T data) { } public static void GenericThisAndMore<T,S>(this T me, S data) where T : Zed { } public static void GenericThisAndOther<T>(this T me, T data) where T : Zed { } } class Test { void NotGeneric() { Zed z; int n; z.NotGeneric(n); } void GenericThis() { Zed z; int n; z.GenericThis(n); } void GenericNotThis() { Zed z; int n; z.GenericNotThis(n); } void GenericThisAndMore() { Zed z; int n; z.GenericThisAndMore(n); } void GenericThisAndOther() { Zed z; z.GenericThisAndOther(z); } } "; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) { var comp1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()); var comp2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther"); } } [WpfFact] public async Task TestVisualBasicReducedExtensionMethodsAreEquivalent() { var code = @" Imports System.Runtime.CompilerServices Class Zed End Class Module Extensions <Extension> Public Sub NotGeneric(z As Zed, data As Integer) End Sub <Extension> Public Sub GenericThis(Of T As Zed)(m As T, data as Integer) End Sub <Extension> Public Sub GenericNotThis(Of T)(z As Zed, data As T) End Sub <Extension> Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S) End Sub <Extension> Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T) End Sub End Module Class Test Sub NotGeneric() Dim z As Zed Dim n As Integer z.NotGeneric(n) End Sub Sub GenericThis() Dim z As Zed Dim n As Integer z.GenericThis(n) End Sub Sub GenericNotThis() Dim z As Zed Dim n As Integer z.GenericNotThis(n) End Sub Sub GenericThisAndMore() Dim z As Zed Dim n As Integer z.GenericThisAndMore(n) End Sub Sub GenericThisAndOther() Dim z As Zed z.GenericThisAndOther(z) End Sub End Class "; using (var workspace1 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) { var comp1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()); var comp2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther"); } } [WpfFact] public async Task TestDifferentModules() { var csharpCode = @"namespace N { namespace M { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "FooModule"))) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "BarModule"))) { var namespace1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M"); var namespace2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M"); Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(namespace1, namespace2)); Assert.Equal(SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace1), SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(namespace1, namespace2)); Assert.NotEqual(SymbolEquivalenceComparer.Instance.GetHashCode(namespace1), SymbolEquivalenceComparer.Instance.GetHashCode(namespace2)); } } [WpfFact] public void AssemblyComparer1() { var references = new[] { TestReferences.NetFx.v4_0_30319.mscorlib }; string source = "public class T {}"; string sourceV1 = "[assembly: System.Reflection.AssemblyVersion(\"1.0.0.0\")] public class T {}"; string sourceV2 = "[assembly: System.Reflection.AssemblyVersion(\"2.0.0.0\")] public class T {}"; var a1 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions); var a2 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions); var b1 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV1) }, references, CSharpSignedDllOptions); var b2 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions); var b3 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions); var ta1 = (ITypeSymbol)a1.GlobalNamespace.GetMembers("T").Single(); var ta2 = (ITypeSymbol)a2.GlobalNamespace.GetMembers("T").Single(); var tb1 = (ITypeSymbol)b1.GlobalNamespace.GetMembers("T").Single(); var tb2 = (ITypeSymbol)b2.GlobalNamespace.GetMembers("T").Single(); var tb3 = (ITypeSymbol)b3.GlobalNamespace.GetMembers("T").Single(); var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance, distinguishRefFromOut: false); // same name: Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, ta2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(ta1, ta2)); Assert.True(identityComparer.Equals(ta1, ta2)); // different name: Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, tb1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(ta1, tb1)); Assert.False(identityComparer.Equals(ta1, tb1)); // different identity Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb1, tb2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb1, tb2)); Assert.False(identityComparer.Equals(tb1, tb2)); // same identity Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb2, tb3)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb2, tb3)); Assert.True(identityComparer.Equals(tb2, tb3)); } private sealed class AssemblySymbolIdentityComparer : IEqualityComparer<IAssemblySymbol> { public static readonly IEqualityComparer<IAssemblySymbol> Instance = new AssemblySymbolIdentityComparer(); public bool Equals(IAssemblySymbol x, IAssemblySymbol y) { return x.Identity.Equals(y.Identity); } public int GetHashCode(IAssemblySymbol obj) { return obj.Identity.GetHashCode(); } } [WpfFact] public void CustomModifiers_Methods1() { const string ilSource = @" .class public C { .method public instance int32 [] modopt([mscorlib]System.Int64) F( // 0 int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32 [] modopt([mscorlib]System.Boolean) F( // 1 int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32[] F( // 2 int32 a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32[] F( // 3 int32 a, int32 b) { ldnull throw } } "; MetadataReference r1, r2; using (var tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)) { byte[] bytes = File.ReadAllBytes(tempAssembly.Path); r1 = MetadataReference.CreateFromImage(bytes); r2 = MetadataReference.CreateFromImage(bytes); } var c1 = CS.CSharpCompilation.Create("comp1", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r1 }); var c2 = CS.CSharpCompilation.Create("comp2", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r2 }); var type1 = (ITypeSymbol)c1.GlobalNamespace.GetMembers("C").Single(); var type2 = (ITypeSymbol)c2.GlobalNamespace.GetMembers("C").Single(); var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance, distinguishRefFromOut: false); var f1 = type1.GetMembers("F"); var f2 = type2.GetMembers("F"); Assert.True(identityComparer.Equals(f1[0], f2[0])); Assert.False(identityComparer.Equals(f1[0], f2[1])); Assert.False(identityComparer.Equals(f1[0], f2[2])); Assert.False(identityComparer.Equals(f1[0], f2[3])); Assert.False(identityComparer.Equals(f1[1], f2[0])); Assert.True(identityComparer.Equals(f1[1], f2[1])); Assert.False(identityComparer.Equals(f1[1], f2[2])); Assert.False(identityComparer.Equals(f1[1], f2[3])); Assert.False(identityComparer.Equals(f1[2], f2[0])); Assert.False(identityComparer.Equals(f1[2], f2[1])); Assert.True(identityComparer.Equals(f1[2], f2[2])); Assert.False(identityComparer.Equals(f1[2], f2[3])); Assert.False(identityComparer.Equals(f1[3], f2[0])); Assert.False(identityComparer.Equals(f1[3], f2[1])); Assert.False(identityComparer.Equals(f1[3], f2[2])); Assert.True(identityComparer.Equals(f1[3], f2[3])); } private void TestReducedExtension<TInvocation>(Compilation comp1, Compilation comp2, string typeName, string methodName) where TInvocation : SyntaxNode { var method1 = GetInvokedSymbol<TInvocation>(comp1, typeName, methodName); var method2 = GetInvokedSymbol<TInvocation>(comp2, typeName, methodName); Assert.NotNull(method1); Assert.Equal(method1.MethodKind, MethodKind.ReducedExtension); Assert.NotNull(method2); Assert.Equal(method2.MethodKind, MethodKind.ReducedExtension); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method1, method2)); var cfmethod1 = method1.ConstructedFrom; var cfmethod2 = method2.ConstructedFrom; Assert.True(SymbolEquivalenceComparer.Instance.Equals(cfmethod1, cfmethod2)); } private IMethodSymbol GetInvokedSymbol<TInvocation>(Compilation compilation, string typeName, string methodName) where TInvocation : SyntaxNode { var type1 = compilation.GlobalNamespace.GetTypeMembers(typeName).Single(); var method = type1.GetMembers(methodName).Single(); var method_root = method.DeclaringSyntaxReferences[0].GetSyntax(); var invocation = method_root.DescendantNodes().OfType<TInvocation>().FirstOrDefault(); if (invocation == null) { // vb method root is statement, but we need block to find body with invocation invocation = method_root.Parent.DescendantNodes().OfType<TInvocation>().First(); } var model = compilation.GetSemanticModel(invocation.SyntaxTree); var info = model.GetSymbolInfo(invocation); return info.Symbol as IMethodSymbol; } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UsePatternMatching; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching { public partial class CSharpAsAndNullCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new CSharpAsAndNullCheckDiagnosticAnalyzer(), new CSharpAsAndNullCheckCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheck1() { await TestAsync( @"class C { void M() { [|var|] x = o as string; if (x != null) { } } }", @"class C { void M() { if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckInvertedCheck1() { await TestAsync( @"class C { void M() { [|var|] x = o as string; if (null != x) { } } }", @"class C { void M() { if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|var|] x = o as string; if (x != null) { } } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInWrongName() { await TestMissingAsync( @"class C { void M() { [|var|] y = o as string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnNonDeclaration() { await TestMissingAsync( @"class C { void M() { [|y|] = o as string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnIsExpression() { await TestMissingAsync( @"class C { void M() { [|var|] x = o is string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexExpression1() { await TestAsync( @"class C { void M() { [|var|] x = (o ? z : w) as string; if (x != null) { } } }", @"class C { void M() { if ((o ? z : w) is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnNullEquality() { await TestMissingAsync( @"class C { void M() { [|var|] x = o is string; if (x == null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestInlineTypeCheckWithElse() { await TestAsync( @"class C { void M() { [|var|] x = o as string; if (null != x) { } else { } } }", @"class C { void M() { if (o is string x) { } else { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments1() { await TestAsync( @"class C { void M() { // prefix comment [|var|] x = o as string; if (x != null) { } } }", @"class C { void M() { // prefix comment if (o is string x) { } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments2() { await TestAsync( @"class C { void M() { [|var|] x = o as string; // suffix comment if (x != null) { } } }", @"class C { void M() { // suffix comment if (o is string x) { } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments3() { await TestAsync( @"class C { void M() { // prefix comment [|var|] x = o as string; // suffix comment if (x != null) { } } }", @"class C { void M() { // prefix comment // suffix comment if (o is string x) { } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition1() { await TestAsync( @"class C { void M() { [|var|] x = o as string; if (x != null ? 0 : 1) { } } }", @"class C { void M() { if (o is string x ? 0 : 1) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition2() { await TestAsync( @"class C { void M() { [|var|] x = o as string; if ((x != null)) { } } }", @"class C { void M() { if ((o is string x)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition3() { await TestAsync( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } } }", @"class C { void M() { if (o is string x && x.Length > 0) { } } }"); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/ml/v1beta1/project_service.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Ml.V1Beta1 { /// <summary>Holder for reflection information generated from google/cloud/ml/v1beta1/project_service.proto</summary> public static partial class ProjectServiceReflection { #region Descriptor /// <summary>File descriptor for google/cloud/ml/v1beta1/project_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ProjectServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci1nb29nbGUvY2xvdWQvbWwvdjFiZXRhMS9wcm9qZWN0X3NlcnZpY2UucHJv", "dG8SF2dvb2dsZS5jbG91ZC5tbC52MWJldGExGhxnb29nbGUvYXBpL2Fubm90", "YXRpb25zLnByb3RvIiAKEEdldENvbmZpZ1JlcXVlc3QSDAoEbmFtZRgBIAEo", "CSJNChFHZXRDb25maWdSZXNwb25zZRIXCg9zZXJ2aWNlX2FjY291bnQYASAB", "KAkSHwoXc2VydmljZV9hY2NvdW50X3Byb2plY3QYAiABKAMyrQEKGFByb2pl", "Y3RNYW5hZ2VtZW50U2VydmljZRKQAQoJR2V0Q29uZmlnEikuZ29vZ2xlLmNs", "b3VkLm1sLnYxYmV0YTEuR2V0Q29uZmlnUmVxdWVzdBoqLmdvb2dsZS5jbG91", "ZC5tbC52MWJldGExLkdldENvbmZpZ1Jlc3BvbnNlIiyC0+STAiYSJC92MWJl", "dGExL3tuYW1lPXByb2plY3RzLyp9OmdldENvbmZpZ0JzCh9jb20uZ29vZ2xl", "LmNsb3VkLm1sLmFwaS52MWJldGExQhNQcm9qZWN0U2VydmljZVByb3RvUAFa", "OWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvY2xvdWQv", "bWwvdjFiZXRhMTttbGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Ml.V1Beta1.GetConfigRequest), global::Google.Cloud.Ml.V1Beta1.GetConfigRequest.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Ml.V1Beta1.GetConfigResponse), global::Google.Cloud.Ml.V1Beta1.GetConfigResponse.Parser, new[]{ "ServiceAccount", "ServiceAccountProject" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Requests service account information associated with a project. /// </summary> public sealed partial class GetConfigRequest : pb::IMessage<GetConfigRequest> { private static readonly pb::MessageParser<GetConfigRequest> _parser = new pb::MessageParser<GetConfigRequest>(() => new GetConfigRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetConfigRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Ml.V1Beta1.ProjectServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetConfigRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetConfigRequest(GetConfigRequest other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetConfigRequest Clone() { return new GetConfigRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. The project name. /// /// Authorization: requires `Viewer` role on the specified project. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetConfigRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetConfigRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetConfigRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } /// <summary> /// Returns service account information associated with a project. /// </summary> public sealed partial class GetConfigResponse : pb::IMessage<GetConfigResponse> { private static readonly pb::MessageParser<GetConfigResponse> _parser = new pb::MessageParser<GetConfigResponse>(() => new GetConfigResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetConfigResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Ml.V1Beta1.ProjectServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetConfigResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetConfigResponse(GetConfigResponse other) : this() { serviceAccount_ = other.serviceAccount_; serviceAccountProject_ = other.serviceAccountProject_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetConfigResponse Clone() { return new GetConfigResponse(this); } /// <summary>Field number for the "service_account" field.</summary> public const int ServiceAccountFieldNumber = 1; private string serviceAccount_ = ""; /// <summary> /// The service account Cloud ML uses to access resources in the project. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceAccount { get { return serviceAccount_; } set { serviceAccount_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "service_account_project" field.</summary> public const int ServiceAccountProjectFieldNumber = 2; private long serviceAccountProject_; /// <summary> /// The project number for `service_account`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long ServiceAccountProject { get { return serviceAccountProject_; } set { serviceAccountProject_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetConfigResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetConfigResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ServiceAccount != other.ServiceAccount) return false; if (ServiceAccountProject != other.ServiceAccountProject) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ServiceAccount.Length != 0) hash ^= ServiceAccount.GetHashCode(); if (ServiceAccountProject != 0L) hash ^= ServiceAccountProject.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ServiceAccount.Length != 0) { output.WriteRawTag(10); output.WriteString(ServiceAccount); } if (ServiceAccountProject != 0L) { output.WriteRawTag(16); output.WriteInt64(ServiceAccountProject); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ServiceAccount.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceAccount); } if (ServiceAccountProject != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(ServiceAccountProject); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetConfigResponse other) { if (other == null) { return; } if (other.ServiceAccount.Length != 0) { ServiceAccount = other.ServiceAccount; } if (other.ServiceAccountProject != 0L) { ServiceAccountProject = other.ServiceAccountProject; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ServiceAccount = input.ReadString(); break; } case 16: { ServiceAccountProject = input.ReadInt64(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net; using System.Threading.Tasks; using Orleans.Runtime; using OrleansSQLUtils.Storage; namespace Orleans.SqlUtils { /// <summary> /// A class for all relational storages that support all systems stores : membership, reminders and statistics /// </summary> internal class RelationalOrleansQueries { /// <summary> /// the underlying storage /// </summary> private readonly IRelationalStorage storage; /// <summary> /// When inserting statistics and generating a batch insert clause, these are the columns in the statistics /// table that will be updated with multiple values. The other ones are updated with one value only. /// </summary> private readonly static string[] InsertStatisticsMultiupdateColumns = { $"@{DbStoredQueries.Columns.IsValueDelta}", $"@{DbStoredQueries.Columns.StatValue}", $"@{DbStoredQueries.Columns.Statistic}" }; /// <summary> /// the orleans functional queries /// </summary> private readonly DbStoredQueries dbStoredQueries; private readonly IGrainReferenceConverter grainReferenceConverter; /// <summary> /// Constructor /// </summary> /// <param name="storage">the underlying relational storage</param> /// <param name="dbStoredQueries">Orleans functional queries</param> /// <param name="grainReferenceConverter"></param> private RelationalOrleansQueries(IRelationalStorage storage, DbStoredQueries dbStoredQueries, IGrainReferenceConverter grainReferenceConverter) { this.storage = storage; this.dbStoredQueries = dbStoredQueries; this.grainReferenceConverter = grainReferenceConverter; } /// <summary> /// Creates an instance of a database of type <see cref="RelationalOrleansQueries"/> and Initializes Orleans queries from the database. /// Orleans uses only these queries and the variables therein, nothing more. /// </summary> /// <param name="invariantName">The invariant name of the connector for this database.</param> /// <param name="connectionString">The connection string this database should use for database operations.</param> /// <param name="grainReferenceConverter"></param> internal static async Task<RelationalOrleansQueries> CreateInstance(string invariantName, string connectionString, IGrainReferenceConverter grainReferenceConverter) { var storage = RelationalStorage.CreateInstance(invariantName, connectionString); var queries = await storage.ReadAsync(DbStoredQueries.GetQueriesKey, DbStoredQueries.Converters.GetQueryKeyAndValue, null); return new RelationalOrleansQueries(storage, new DbStoredQueries(queries.ToDictionary(q => q.Key, q => q.Value)), grainReferenceConverter); } private Task ExecuteAsync(string query, Func<IDbCommand, DbStoredQueries.Columns> parameterProvider) { return storage.ExecuteAsync(query, command => parameterProvider(command)); } private async Task<TAggregate> ReadAsync<TResult, TAggregate>(string query, Func<IDataRecord, TResult> selector, Func<IDbCommand, DbStoredQueries.Columns> parameterProvider, Func<IEnumerable<TResult>, TAggregate> aggregator) { var ret = await storage.ReadAsync(query, selector, command => parameterProvider(command)); return aggregator(ret); } /// <summary> /// Either inserts or updates a silo metrics row. /// </summary> /// <param name="deploymentId">The deployment ID.</param> /// <param name="siloId">The silo ID.</param> /// <param name="gateway">The gateway information.</param> /// <param name="siloAddress">The silo address information.</param> /// <param name="hostName">The host name.</param> /// <param name="siloMetrics">The silo metrics to be either updated or inserted.</param> /// <returns></returns> internal Task UpsertSiloMetricsAsync(string deploymentId, string siloId, IPEndPoint gateway, SiloAddress siloAddress, string hostName, ISiloPerformanceMetrics siloMetrics) { return ExecuteAsync(dbStoredQueries.UpsertSiloMetricsKey, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, HostName = hostName, SiloMetrics = siloMetrics, SiloAddress = siloAddress, GatewayAddress = gateway.Address, GatewayPort = gateway.Port, SiloId = siloId }); } /// <summary> /// Either inserts or updates a silo metrics row. /// </summary> /// <param name="deploymentId">The deployment ID.</param> /// <param name="clientId">The client ID.</param> /// <param name="address">The client address information.</param> /// <param name="hostName">The hostname.</param> /// <param name="clientMetrics">The client metrics to be either updated or inserted.</param> /// <returns></returns> internal Task UpsertReportClientMetricsAsync(string deploymentId, string clientId, IPAddress address, string hostName, IClientPerformanceMetrics clientMetrics) { return ExecuteAsync(dbStoredQueries.UpsertReportClientMetricsKey, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, HostName = hostName, ClientMetrics = clientMetrics, ClientId = clientId, Address = address }); } /// <summary> /// Inserts the given statistics counters to the Orleans database. /// </summary> /// <param name="deploymentId">The deployment ID.</param> /// <param name="hostName">The hostname.</param> /// <param name="siloOrClientName">The silo or client name.</param> /// <param name="id">The silo address or client ID.</param> /// <param name="counters">The counters to be inserted.</param> internal Task InsertStatisticsCountersAsync(string deploymentId, string hostName, string siloOrClientName, string id, List<ICounter> counters) { var queryTemplate = dbStoredQueries.InsertOrleansStatisticsKey; //Zero statistic values mean either that the system is not running or no updates. Such values are not inserted and pruned //here so that no insert query or parameters are generated. counters = counters.Where(i => !"0".Equals(i.IsValueDelta ? i.GetDeltaString() : i.GetValueString())).ToList(); if (counters.Count == 0) { return TaskDone.Done; } //Note that the following is almost the same as RelationalStorageExtensions.ExecuteMultipleInsertIntoAsync //the only difference being that some columns are skipped. Likely it would be beneficial to introduce //a "skip list" to RelationalStorageExtensions.ExecuteMultipleInsertIntoAsync. //The template contains an insert for online. The part after SELECT is copied //out so that certain parameters can be multiplied by their count. Effectively //this turns a query of type (transaction details vary by vendor) //BEGIN TRANSACTION; INSERT INTO [OrleansStatisticsTable] <columns> SELECT <variables>; COMMIT TRANSACTION; //to BEGIN TRANSACTION; INSERT INTO [OrleansStatisticsTable] <columns> SELECT <variables>; UNION ALL <variables> COMMIT TRANSACTION; //where the UNION ALL is multiplied as many times as there are counters to insert. int startFrom = queryTemplate.IndexOf("SELECT", StringComparison.Ordinal) + "SELECT".Length + 1; //This +1 is to have a space between SELECT and the first parameter name to not to have a SQL syntax error. int lastSemicolon = queryTemplate.LastIndexOf(";", StringComparison.Ordinal); int endTo = lastSemicolon > 0 ? queryTemplate.LastIndexOf(";", lastSemicolon - 1, StringComparison.Ordinal) : -1; var template = queryTemplate.Substring(startFrom, endTo - startFrom); var parameterNames = template.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).ToArray(); var collectionOfParametersToBeUnionized = new List<string>(); var parametersToBeUnioned = new string[parameterNames.Length]; for (int counterIndex = 0; counterIndex < counters.Count; ++counterIndex) { for (int parameterNameIndex = 0; parameterNameIndex < parameterNames.Length; ++parameterNameIndex) { if (InsertStatisticsMultiupdateColumns.Contains(parameterNames[parameterNameIndex])) { //These parameters change for each row. The format is //@StatValue0, @StatValue1, @StatValue2, ... @sStatValue{counters.Count}. parametersToBeUnioned[parameterNameIndex] = $"{parameterNames[parameterNameIndex]}{counterIndex}"; } else { //These parameters remain constant for every and each row. parametersToBeUnioned[parameterNameIndex] = parameterNames[parameterNameIndex]; } } collectionOfParametersToBeUnionized.Add($"{string.Join(",", parametersToBeUnioned)}"); } var storageConsts = DbConstantsStore.GetDbConstants(storage.InvariantName); var query = queryTemplate.Replace(template, string.Join(storageConsts.UnionAllSelectTemplate, collectionOfParametersToBeUnionized)); return ExecuteAsync(query, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, HostName = hostName, Counters = counters, Name = siloOrClientName, Id = id }); } /// <summary> /// Reads Orleans reminder data from the tables. /// </summary> /// <param name="serviceId">The service ID.</param> /// <param name="grainRef">The grain reference (ID).</param> /// <returns>Reminder table data.</returns> internal Task<ReminderTableData> ReadReminderRowsAsync(string serviceId, GrainReference grainRef) { return ReadAsync(dbStoredQueries.ReadReminderRowsKey, record => DbStoredQueries.Converters.GetReminderEntry(record, this.grainReferenceConverter), command => new DbStoredQueries.Columns(command) {ServiceId = serviceId, GrainId = grainRef.ToKeyString()}, ret => new ReminderTableData(ret.ToList())); } /// <summary> /// Reads Orleans reminder data from the tables. /// </summary> /// <param name="serviceId">The service ID.</param> /// <param name="beginHash">The begin hash.</param> /// <param name="endHash">The end hash.</param> /// <returns>Reminder table data.</returns> internal Task<ReminderTableData> ReadReminderRowsAsync(string serviceId, uint beginHash, uint endHash) { var query = (int) beginHash < (int) endHash ? dbStoredQueries.ReadRangeRows1Key : dbStoredQueries.ReadRangeRows2Key; return ReadAsync(query, record => DbStoredQueries.Converters.GetReminderEntry(record, this.grainReferenceConverter), command => new DbStoredQueries.Columns(command) {ServiceId = serviceId, BeginHash = beginHash, EndHash = endHash}, ret => new ReminderTableData(ret.ToList())); } /// <summary> /// Reads one row of reminder data. /// </summary> /// <param name="serviceId">Service ID.</param> /// <param name="grainRef">The grain reference (ID).</param> /// <param name="reminderName">The reminder name to retrieve.</param> /// <returns>A remainder entry.</returns> internal Task<ReminderEntry> ReadReminderRowAsync(string serviceId, GrainReference grainRef, string reminderName) { return ReadAsync(dbStoredQueries.ReadReminderRowKey, record => DbStoredQueries.Converters.GetReminderEntry(record, this.grainReferenceConverter), command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, GrainId = grainRef.ToKeyString(), ReminderName = reminderName }, ret => ret.FirstOrDefault()); } /// <summary> /// Either inserts or updates a reminder row. /// </summary> /// <param name="serviceId">The service ID.</param> /// <param name="grainRef">The grain reference (ID).</param> /// <param name="reminderName">The reminder name to retrieve.</param> /// <param name="startTime">Start time of the reminder.</param> /// <param name="period">Period of the reminder.</param> /// <returns>The new etag of the either or updated or inserted reminder row.</returns> internal Task<string> UpsertReminderRowAsync(string serviceId, GrainReference grainRef, string reminderName, DateTime startTime, TimeSpan period) { return ReadAsync(dbStoredQueries.UpsertReminderRowKey, DbStoredQueries.Converters.GetVersion, command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, GrainHash = grainRef.GetUniformHashCode(), GrainId = grainRef.ToKeyString(), ReminderName = reminderName, StartTime = startTime, Period = period }, ret => ret.First().ToString()); } /// <summary> /// Deletes a reminder /// </summary> /// <param name="serviceId">Service ID.</param> /// <param name="grainRef"></param> /// <param name="reminderName"></param> /// <param name="etag"></param> /// <returns></returns> internal Task<bool> DeleteReminderRowAsync(string serviceId, GrainReference grainRef, string reminderName, string etag) { return ReadAsync(dbStoredQueries.DeleteReminderRowKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, GrainId = grainRef.ToKeyString(), ReminderName = reminderName, Version = etag }, ret => ret.First()); } /// <summary> /// Deletes all reminders rows of a service id. /// </summary> /// <param name="serviceId"></param> /// <returns></returns> internal Task DeleteReminderRowsAsync(string serviceId) { return ExecuteAsync(dbStoredQueries.DeleteReminderRowsKey, command => new DbStoredQueries.Columns(command) {ServiceId = serviceId}); } /// <summary> /// Lists active gateways. Used mainly by Orleans clients. /// </summary> /// <param name="deploymentId">The deployment for which to query the gateways.</param> /// <returns>The gateways for the silo.</returns> internal Task<List<Uri>> ActiveGatewaysAsync(string deploymentId) { return ReadAsync(dbStoredQueries.GatewaysQueryKey, DbStoredQueries.Converters.GetGatewayUri, command => new DbStoredQueries.Columns(command) {DeploymentId = deploymentId, Status = SiloStatus.Active}, ret => ret.ToList()); } /// <summary> /// Queries Orleans membership data. /// </summary> /// <param name="deploymentId">The deployment for which to query data.</param> /// <param name="siloAddress">Silo data used as parameters in the query.</param> /// <returns>Membership table data.</returns> internal Task<MembershipTableData> MembershipReadRowAsync(string deploymentId, SiloAddress siloAddress) { return ReadAsync(dbStoredQueries.MembershipReadRowKey, DbStoredQueries.Converters.GetMembershipEntry, command => new DbStoredQueries.Columns(command) {DeploymentId = deploymentId, SiloAddress = siloAddress}, ConvertToMembershipTableData); } /// <summary> /// returns all membership data for a deployment id /// </summary> /// <param name="deploymentId"></param> /// <returns></returns> internal Task<MembershipTableData> MembershipReadAllAsync(string deploymentId) { return ReadAsync(dbStoredQueries.MembershipReadAllKey, DbStoredQueries.Converters.GetMembershipEntry, command => new DbStoredQueries.Columns(command) {DeploymentId = deploymentId}, ConvertToMembershipTableData); } /// <summary> /// deletes all membership entries for a deployment id /// </summary> /// <param name="deploymentId"></param> /// <returns></returns> internal Task DeleteMembershipTableEntriesAsync(string deploymentId) { return ExecuteAsync(dbStoredQueries.DeleteMembershipTableEntriesKey, command => new DbStoredQueries.Columns(command) {DeploymentId = deploymentId}); } /// <summary> /// Updates IAmAlive for a silo /// </summary> /// <param name="deploymentId"></param> /// <param name="siloAddress"></param> /// <param name="iAmAliveTime"></param> /// <returns></returns> internal Task UpdateIAmAliveTimeAsync(string deploymentId, SiloAddress siloAddress,DateTime iAmAliveTime) { return ExecuteAsync(dbStoredQueries.UpdateIAmAlivetimeKey, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, SiloAddress = siloAddress, IAmAliveTime = iAmAliveTime }); } /// <summary> /// Inserts a version row if one does not already exist. /// </summary> /// <param name="deploymentId">The deployment for which to query data.</param> /// <returns><em>TRUE</em> if a row was inserted. <em>FALSE</em> otherwise.</returns> internal Task<bool> InsertMembershipVersionRowAsync(string deploymentId) { return ReadAsync(dbStoredQueries.InsertMembershipVersionKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) {DeploymentId = deploymentId}, ret => ret.First()); } /// <summary> /// Inserts a membership row if one does not already exist. /// </summary> /// <param name="deploymentId">The deployment with which to insert row.</param> /// <param name="membershipEntry">The membership entry data to insert.</param> /// <param name="etag">The table expected version etag.</param> /// <returns><em>TRUE</em> if insert succeeds. <em>FALSE</em> otherwise.</returns> internal Task<bool> InsertMembershipRowAsync(string deploymentId, MembershipEntry membershipEntry, string etag) { return ReadAsync(dbStoredQueries.InsertMembershipKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, IAmAliveTime = membershipEntry.IAmAliveTime, SiloName = membershipEntry.SiloName, HostName = membershipEntry.HostName, SiloAddress = membershipEntry.SiloAddress, StartTime = membershipEntry.StartTime, Status = membershipEntry.Status, ProxyPort = membershipEntry.ProxyPort, Version = etag }, ret => ret.First()); } /// <summary> /// Updates membership row data. /// </summary> /// <param name="deploymentId">The deployment with which to insert row.</param> /// <param name="membershipEntry">The membership data to used to update database.</param> /// <param name="etag">The table expected version etag.</param> /// <returns><em>TRUE</em> if update SUCCEEDS. <em>FALSE</em> ot</returns> internal Task<bool> UpdateMembershipRowAsync(string deploymentId, MembershipEntry membershipEntry, string etag) { return ReadAsync(dbStoredQueries.UpdateMembershipKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, SiloAddress = membershipEntry.SiloAddress, IAmAliveTime = membershipEntry.IAmAliveTime, Status = membershipEntry.Status, SuspectTimes = membershipEntry.SuspectTimes, Version = etag }, ret => ret.First()); } private static MembershipTableData ConvertToMembershipTableData(IEnumerable<Tuple<MembershipEntry, int>> ret) { var retList = ret.ToList(); var tableVersionEtag = retList[0].Item2; var membershipEntries = new List<Tuple<MembershipEntry, string>>(); if (retList[0].Item1 != null) { membershipEntries.AddRange(retList.Select(i => new Tuple<MembershipEntry, string>(i.Item1, string.Empty))); } return new MembershipTableData(membershipEntries, new TableVersion(tableVersionEtag, tableVersionEtag.ToString())); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MTG.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// RoleResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Chat.V2.Service { public class RoleResource : Resource { public sealed class RoleTypeEnum : StringEnum { private RoleTypeEnum(string value) : base(value) {} public RoleTypeEnum() {} public static implicit operator RoleTypeEnum(string value) { return new RoleTypeEnum(value); } public static readonly RoleTypeEnum Channel = new RoleTypeEnum("channel"); public static readonly RoleTypeEnum Deployment = new RoleTypeEnum("deployment"); } private static Request BuildFetchRequest(FetchRoleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Roles/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static RoleResource Fetch(FetchRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<RoleResource> FetchAsync(FetchRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathSid"> The SID of the Role resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static RoleResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchRoleOptions(pathServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathSid"> The SID of the Role resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<RoleResource> FetchAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchRoleOptions(pathServiceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteRoleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Roles/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static bool Delete(DeleteRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The SID of the Role resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteRoleOptions(pathServiceSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The SID of the Role resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteRoleOptions(pathServiceSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateRoleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Roles", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static RoleResource Create(CreateRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<RoleResource> CreateAsync(CreateRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the resource under </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="type"> The type of role </param> /// <param name="permission"> A permission the role should have </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static RoleResource Create(string pathServiceSid, string friendlyName, RoleResource.RoleTypeEnum type, List<string> permission, ITwilioRestClient client = null) { var options = new CreateRoleOptions(pathServiceSid, friendlyName, type, permission); return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the resource under </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="type"> The type of role </param> /// <param name="permission"> A permission the role should have </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<RoleResource> CreateAsync(string pathServiceSid, string friendlyName, RoleResource.RoleTypeEnum type, List<string> permission, ITwilioRestClient client = null) { var options = new CreateRoleOptions(pathServiceSid, friendlyName, type, permission); return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadRoleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Roles", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static ResourceSet<RoleResource> Read(ReadRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<RoleResource>.FromJson("roles", response.Content); return new ResourceSet<RoleResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<ResourceSet<RoleResource>> ReadAsync(ReadRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<RoleResource>.FromJson("roles", response.Content); return new ResourceSet<RoleResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static ResourceSet<RoleResource> Read(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRoleOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<ResourceSet<RoleResource>> ReadAsync(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRoleOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<RoleResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<RoleResource>.FromJson("roles", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<RoleResource> NextPage(Page<RoleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<RoleResource>.FromJson("roles", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<RoleResource> PreviousPage(Page<RoleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<RoleResource>.FromJson("roles", response.Content); } private static Request BuildUpdateRequest(UpdateRoleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Roles/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static RoleResource Update(UpdateRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Role parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<RoleResource> UpdateAsync(UpdateRoleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the resource from </param> /// <param name="pathSid"> The SID of the Role resource to update </param> /// <param name="permission"> A permission the role should have </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Role </returns> public static RoleResource Update(string pathServiceSid, string pathSid, List<string> permission, ITwilioRestClient client = null) { var options = new UpdateRoleOptions(pathServiceSid, pathSid, permission); return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the resource from </param> /// <param name="pathSid"> The SID of the Role resource to update </param> /// <param name="permission"> A permission the role should have </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Role </returns> public static async System.Threading.Tasks.Task<RoleResource> UpdateAsync(string pathServiceSid, string pathSid, List<string> permission, ITwilioRestClient client = null) { var options = new UpdateRoleOptions(pathServiceSid, pathSid, permission); return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a RoleResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> RoleResource object represented by the provided JSON </returns> public static RoleResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<RoleResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The type of role /// </summary> [JsonProperty("type")] [JsonConverter(typeof(StringEnumConverter))] public RoleResource.RoleTypeEnum Type { get; private set; } /// <summary> /// An array of the permissions the role has been granted /// </summary> [JsonProperty("permissions")] public List<string> Permissions { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the Role resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private RoleResource() { } } }
// Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Oren Gurfinkel <oreng@mainsoft.com> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // 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 NUnit.Framework; using MonoTests.System.Data.Test.Utils; using System; using System.Collections; using System.ComponentModel; using System.Data; namespace MonoTests.System.Data { [TestFixture] public class ConstraintCollectionTest2 { private bool CollectionChangedFlag = false; [Test] public void CanRemove_ParentForeign() { DataSet ds = DataProvider.CreateForigenConstraint(); Assert.AreEqual(false, ds.Tables["parent"].Constraints.CanRemove(ds.Tables["parent"].Constraints[0]), "CN1"); } [Test] public void CanRemove_ChildForeign() { DataSet ds = DataProvider.CreateForigenConstraint(); Assert.AreEqual(true, ds.Tables["child"].Constraints.CanRemove(ds.Tables["child"].Constraints[0]), "CN2"); } [Test] public void CanRemove_ParentAndChildForeign() { DataSet ds = DataProvider.CreateForigenConstraint(); //remove the forigen and ask about the unique ds.Tables["child"].Constraints.Remove(ds.Tables["child"].Constraints[0]); Assert.AreEqual(true, ds.Tables["parent"].Constraints.CanRemove(ds.Tables["parent"].Constraints[0]), "CN3"); } // FIXME. This test isn't complete. public void CanRemove_Unique() { DataTable dt = DataProvider.CreateUniqueConstraint(); //remove the forigen and ask about the unique dt.Constraints.Remove(dt.Constraints[0]); Assert.AreEqual(true, dt.Constraints.CanRemove(dt.Constraints[0]), "CN4"); } [Test] public void Clear_Foreign() { DataSet ds = DataProvider.CreateForigenConstraint(); foreach(DataTable dt in ds.Tables) { dt.Constraints.Clear(); } Assert.AreEqual(0, ds.Tables[0].Constraints.Count, "CN5"); Assert.AreEqual(0, ds.Tables[0].Constraints.Count, "CN6"); } [Test] public void Clear_Unique() { DataTable dt = DataProvider.CreateUniqueConstraint(); int rowsCount = dt.Rows.Count; dt.Constraints.Clear(); DataRow dr = dt.NewRow(); dr[0] = 1; dt.Rows.Add(dr); Assert.AreEqual(rowsCount+1, dt.Rows.Count, "CN7"); //Just checking that no expection ocuured } [Test] public void CollectionChanged() { DataTable dt = DataProvider.CreateParentDataTable(); CollectionChangedFlag = false; dt.Constraints.CollectionChanged += new CollectionChangeEventHandler(Constraints_CollectionChangedHandler); dt = DataProvider.CreateUniqueConstraint(dt); Assert.AreEqual(true, CollectionChangedFlag, "CN8"); } [Test] public void Contains_ByName() { DataSet ds = DataProvider.CreateForigenConstraint(); //changing the constraints's name ds.Tables["child"].Constraints[0].ConstraintName = "name1"; ds.Tables["parent"].Constraints[0].ConstraintName = "name2"; Assert.AreEqual(true, ds.Tables["child"].Constraints.Contains("name1"), "CN9"); Assert.AreEqual(false, ds.Tables["child"].Constraints.Contains("xxx"), "CN10"); Assert.AreEqual(true, ds.Tables["parent"].Constraints.Contains("name2"), "CN11"); Assert.AreEqual(false, ds.Tables["parent"].Constraints.Contains("xxx"), "CN12"); } [Test] public void CopyTo() { DataTable dt = DataProvider.CreateUniqueConstraint(); dt.Constraints.Add("constraint2",dt.Columns["String1"],true); object[] ar = new object[2]; dt.Constraints.CopyTo(ar,0); Assert.AreEqual(2, ar.Length, "CN13"); } [Test] public void Count() { DataTable dt = DataProvider.CreateUniqueConstraint(); Assert.AreEqual(1, dt.Constraints.Count, "CN14"); //Add dt.Constraints.Add("constraint2",dt.Columns["String1"],false); Assert.AreEqual(2, dt.Constraints.Count, "CN15"); //Remove dt.Constraints.Remove("constraint2"); Assert.AreEqual(1, dt.Constraints.Count, "CN16"); } [Test] public void GetEnumerator() { DataTable dt = DataProvider.CreateUniqueConstraint(); dt.Constraints.Add("constraint2",dt.Columns["String1"],false); int counter=0; IEnumerator myEnumerator = dt.Constraints.GetEnumerator(); while (myEnumerator.MoveNext()) { counter++; } Assert.AreEqual(2, counter, "CN17"); } [Test] public void IndexOf() { DataTable dt = DataProvider.CreateUniqueConstraint(); Assert.AreEqual(0, dt.Constraints.IndexOf(dt.Constraints[0]), "CN18"); //Add new constraint Constraint con = new UniqueConstraint(dt.Columns["String1"],false); dt.Constraints.Add(con); Assert.AreEqual(1, dt.Constraints.IndexOf(con), "CN19"); //Remove it and try to look for it dt.Constraints.Remove(con); Assert.AreEqual(-1, dt.Constraints.IndexOf(con), "CN20"); } [Test] public void IndexOf_ByName() { DataTable dt = DataProvider.CreateUniqueConstraint(); dt.Constraints[0].ConstraintName="name1"; Assert.AreEqual(0, dt.Constraints.IndexOf("name1"), "CN21"); //Add new constraint Constraint con = new UniqueConstraint(dt.Columns["String1"],false); con.ConstraintName="name2"; dt.Constraints.Add(con); Assert.AreEqual(1, dt.Constraints.IndexOf("name2"), "CN22"); //Remove it and try to look for it dt.Constraints.Remove(con); Assert.AreEqual(-1, dt.Constraints.IndexOf("name2"), "CN23"); } [Test] public void IsReadOnly() { DataTable dt = DataProvider.CreateUniqueConstraint(); Assert.AreEqual(false, dt.Constraints.IsReadOnly, "CN24"); } [Test] public void IsSynchronized() { DataTable dt = DataProvider.CreateUniqueConstraint(); Assert.AreEqual(false, dt.Constraints.IsSynchronized, "CN25"); ConstraintCollection col = (ConstraintCollection)dt.Constraints.SyncRoot; // lock(dt.Constraints.SyncRoot) // { // Assert.AreEqual(true, col.IsSynchronized, "CN26"); //} } [Test] public void Remove() { DataTable dt = DataProvider.CreateUniqueConstraint(); dt.Constraints.Remove(dt.Constraints[0]); Assert.AreEqual(0, dt.Constraints.Count, "CN27"); } [Test] public void Remove_ByNameSimple() { DataTable dt = DataProvider.CreateUniqueConstraint(); dt.Constraints[0].ConstraintName = "constraint1"; dt.Constraints.Remove("constraint1"); Assert.AreEqual(0, dt.Constraints.Count, "CN28"); } [Test] public void Remove_ByNameWithAdd() { DataTable dt = DataProvider.CreateUniqueConstraint(); dt.Constraints[0].ConstraintName = "constraint1"; Constraint con = new UniqueConstraint(dt.Columns["String1"],false); dt.Constraints.Add(con); dt.Constraints.Remove(con); Assert.AreEqual(1, dt.Constraints.Count, "CN29"); Assert.AreEqual("constraint1", dt.Constraints[0].ConstraintName, "CN30"); } [Test] public void Remove_CollectionChangedEvent() { DataTable dt = DataProvider.CreateUniqueConstraint(); CollectionChangedFlag = false; dt.Constraints.CollectionChanged += new CollectionChangeEventHandler(Constraints_CollectionChangedHandler); dt.Constraints.Remove(dt.Constraints[0]); Assert.AreEqual(true, CollectionChangedFlag, "CN31"); //Checking that event has raised } [Test] public void Remove_ByNameCollectionChangedEvent() { DataTable dt = DataProvider.CreateUniqueConstraint(); CollectionChangedFlag = false; dt.Constraints.CollectionChanged += new CollectionChangeEventHandler(Constraints_CollectionChangedHandler); dt.Constraints.Remove("constraint1"); Assert.AreEqual(true, CollectionChangedFlag, "CN32"); //Checking that event has raised } [Test] public void add_CollectionChanged() { DataTable dt = DataProvider.CreateParentDataTable(); CollectionChangedFlag = false; dt.Constraints.CollectionChanged += new CollectionChangeEventHandler(Constraints_CollectionChangedHandler); dt = DataProvider.CreateUniqueConstraint(dt); Assert.AreEqual(true, CollectionChangedFlag, "CN33"); } private void Constraints_CollectionChangedHandler(object sender, CollectionChangeEventArgs e) { CollectionChangedFlag = true; } } }
namespace Oculus.Platform.Samples.VrVoiceChat { using UnityEngine; using System; using System.Collections.Generic; using Oculus.Platform; using Oculus.Platform.Models; // Helper class to manage Room creation, membership and invites. // Rooms are a mechanism to help Oculus users create a shared experience. // Users can only be in one Room at a time. If the Owner of a room // leaves, then ownership is transferred to some other member. // Here we use rooms to create the notion of a 'call' to help us // invite a Friend and establish a VOIP and P2P connection. public class RoomManager { // the ID of the Room that I'm in private ulong m_roomID; // the other User in the Room private User m_remoteUser; // how often I should poll for invites private static readonly float INVITE_POLL_FREQ_SECONDS = 5.0f; // the next time I should poll Oculus Platform for valid Room Invite requests private float m_nextPollTime; public struct Invite { public readonly ulong RoomID; public readonly string OwnerID; public Invite(ulong roomID, string owner) { this.RoomID = roomID; this.OwnerID = owner; } } // cached list of rooms that I've been invited to and I'm waiting // for more information about private HashSet<ulong> m_pendingRoomRequests; // accumulation list of room invites and the room owner private List<Invite> m_invites; public RoomManager() { Rooms.SetRoomInviteAcceptedNotificationCallback(LaunchedFromAcceptingInviteCallback); Rooms.SetUpdateNotificationCallback(RoomUpdateCallback); } public ulong RemoteUserID { get { return m_remoteUser != null ? m_remoteUser.ID : 0; } } public String RemoteOculusID { get { return m_remoteUser != null ? m_remoteUser.OculusID : String.Empty; } } #region Launched Application from Accepting Invite // Callback to check whether the User accepted the invite as // a notification which caused the Application to launch. If so, then // we know we need to try to join that room. void LaunchedFromAcceptingInviteCallback(Message<string> msg) { if (msg.IsError) { PlatformManager.TerminateWithError(msg); return; } Debug.Log("Launched Invite to join Room: " + msg.Data); m_roomID = Convert.ToUInt64(msg.GetString()); } // Check to see if the App was launched by accepting the Notication from the main Oculus app. // If so, we can directly join that room. (If it's still available.) public bool CheckForLaunchInvite() { if (m_roomID != 0) { JoinExistingRoom(m_roomID); return true; } else { return false; } } #endregion #region Create a Room and Invite Friend(s) from the Oculus Universal Menu public void CreateRoomAndLaunchInviteMenu() { Rooms.CreateAndJoinPrivate(RoomJoinPolicy.InvitedUsers, 2, true) .OnComplete(CreateAndJoinPrivateRoomCallback); } void CreateAndJoinPrivateRoomCallback(Message<Room> msg) { if (msg.IsError) { PlatformManager.TerminateWithError(msg); return; } m_roomID = msg.Data.ID; m_remoteUser = null; PlatformManager.TransitionToState(PlatformManager.State.WAITING_FOR_ANSWER); // launch the Room Invite workflow in the Oculus Univeral Menu Rooms.LaunchInvitableUserFlow(m_roomID).OnComplete(OnLaunchInviteWorkflowComplete); } void OnLaunchInviteWorkflowComplete(Message msg) { if (msg.IsError) { PlatformManager.TerminateWithError(msg); return; } } #endregion #region Polling for Invites public bool ShouldPollInviteList { get { return m_pendingRoomRequests == null && Time.time >= m_nextPollTime; } } public void UpdateActiveInvitesList() { m_nextPollTime = Time.time + INVITE_POLL_FREQ_SECONDS; m_pendingRoomRequests = new HashSet<ulong>(); m_invites = new List<Invite>(); Notifications.GetRoomInviteNotifications().OnComplete(GetRoomInviteNotificationsCallback); } // task 13572454: add the type to callback definition void GetRoomInviteNotificationsCallback(Message msg_untyped) { Message<RoomInviteNotificationList> msg = (Message<RoomInviteNotificationList>)msg_untyped; if (msg.IsError) { PlatformManager.TerminateWithError(msg); return; } // loop over all the rooms we're invited to and request more info foreach (RoomInviteNotification invite in msg.Data) { m_pendingRoomRequests.Add(invite.RoomID); Rooms.Get(invite.RoomID).OnComplete(GetRoomInfoCallback); } if (msg.Data.Count == 0) { m_pendingRoomRequests = null; PlatformManager.SetActiveInvites(m_invites); } } void GetRoomInfoCallback(Message<Room> msg) { if (msg.IsError) { PlatformManager.TerminateWithError(msg); return; } if (msg.Data.OwnerOptional != null) { Invite invite = new Invite(msg.Data.ID, msg.Data.OwnerOptional.OculusID); m_pendingRoomRequests.Remove(invite.RoomID); // make sure the room still looks usable // (e.g. they aren't currently talking to someone) if (msg.Data.UsersOptional != null && msg.Data.UsersOptional.Count == 1) { m_invites.Add(invite); } } // once we're received all the room info, let the platform update // its display if (m_pendingRoomRequests.Count == 0) { m_pendingRoomRequests = null; PlatformManager.SetActiveInvites(m_invites); } } #endregion #region Accept Invite public void JoinExistingRoom(ulong roomID) { Rooms.Join(roomID, true).OnComplete(JoinRoomCallback); } void JoinRoomCallback(Message<Room> msg) { if (msg.IsError) { // is reasonable if caller called more than 1 person, and I didn't answer first return; } string oculusOwnerID = msg.Data.OwnerOptional != null ? msg.Data.OwnerOptional.OculusID : ""; int numUsers = msg.Data.UsersOptional != null ? msg.Data.UsersOptional.Count : 0; Debug.LogFormat("Joined room: {0} owner: {1} count: ", msg.Data.ID, oculusOwnerID, numUsers); m_roomID = msg.Data.ID; // if the caller left while I was in the process of joining, just hangup if (msg.Data.UsersOptional == null || msg.Data.UsersOptional.Count != 2) { PlatformManager.TransitionToState(PlatformManager.State.HANGUP); } else { foreach (User user in msg.Data.UsersOptional) { if (user.ID != PlatformManager.MyID) { m_remoteUser = user; } } PlatformManager.TransitionToState(PlatformManager.State.CONNECTED_IN_A_ROOM); } // update the invite list sooner m_nextPollTime = Time.time; } #endregion #region Room Updates void RoomUpdateCallback(Message<Room> msg) { if (msg.IsError) { PlatformManager.TerminateWithError(msg); return; } string oculusOwnerID = msg.Data.OwnerOptional != null ? msg.Data.OwnerOptional.OculusID : ""; int numUsers = msg.Data.UsersOptional != null ? msg.Data.UsersOptional.Count : 0; Debug.LogFormat("Room {0} Update: {1} owner: {2} count: ", msg.Data.ID, oculusOwnerID, numUsers); // if the Room count is not 2 then the other party has left. // We'll just hangup the connection here. // If the other User created then room, ownership would switch to me. if (msg.Data.UsersOptional == null || msg.Data.UsersOptional.Count != 2) { PlatformManager.TransitionToState(PlatformManager.State.HANGUP); } else { foreach (User user in msg.Data.UsersOptional) { if (user.ID != PlatformManager.MyID) { m_remoteUser = user; } } PlatformManager.TransitionToState(PlatformManager.State.CONNECTED_IN_A_ROOM); } } #endregion #region Room Exit public void LeaveCurrentRoom() { if (m_roomID != 0) { Rooms.Leave(m_roomID); m_roomID = 0; m_remoteUser = null; } PlatformManager.TransitionToState(PlatformManager.State.WAITING_TO_CALL_OR_ANSWER); } #endregion } }
using Bivi.Data.Context; using Bivi.Domaine; using Bivi.Business.Depots; using System.Linq; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System; namespace Bivi.Data.Depots { public partial class DepotAbonnement : Depot<Abonnement>, IDepotAbonnement { private readonly IDepotLien_Abonnement_NiveauAbonnement _lienAbonnementNiveauAbonnement; private readonly IDepotLien_Abonnement_Personne _lienAbonnementPersonne; private readonly IDepotAbonnementIP _abonnementIP; public DepotAbonnement(IBiviDbContext dataContext, IDepotLien_Abonnement_Personne lienAbonnementPersonne, IDepotLien_Abonnement_NiveauAbonnement lienAbonnementNiveauAbonnement, IDepotAbonnementIP abonnementIP) : this(dataContext) { _lienAbonnementNiveauAbonnement = lienAbonnementNiveauAbonnement; _abonnementIP = abonnementIP; _lienAbonnementPersonne = lienAbonnementPersonne; } public long? Convert(string ip) { if (string.IsNullOrWhiteSpace(ip)) return null; string[] splittedIP = ip.Split(new char[] { '.' }, System.StringSplitOptions.RemoveEmptyEntries); if (splittedIP.Length != 4) return null; splittedIP = splittedIP.Select(s => s.PadLeft(3, '0')).ToArray(); foreach (string part in splittedIP) { int parsedIpPart; bool tryIntResult = int.TryParse(part, out parsedIpPart); if (!tryIntResult || parsedIpPart < 0 || parsedIpPart > 255) return null; } long retour; bool tryLongResult = long.TryParse(splittedIP.Aggregate((s, next) => string.Format("{0}{1}", s, next)), out retour); if (tryLongResult) return retour; return null; } public IEnumerable<dynamic> Search(SearchAbonnementCriteria criterias) { List<SqlParameter> Parameters = new List<SqlParameter>(); Parameters.Add(new SqlParameter("@RaisonSociale", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.RaisonSociale) ? criterias.RaisonSociale : null }); Parameters.Add(new SqlParameter("@CodeClient", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.CodeClient) ? criterias.CodeClient : null }); Parameters.Add(new SqlParameter("@Email", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.Email) ? criterias.Email : null }); Parameters.Add(new SqlParameter("@Nom", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.Nom) ? criterias.Nom : null }); Parameters.Add(new SqlParameter("@Prenom", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.Prenom) ? criterias.Prenom : null }); Parameters.Add(new SqlParameter("@NumQualiac", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.NumQualiac) ? criterias.NumQualiac : null }); DateTime datetime; if (DateTime.TryParse(criterias.DateFinAboFrom, out datetime)) { Parameters.Add(new SqlParameter("@DateFinAboFrom", SqlDbType.Date) { Value = datetime }); } if (DateTime.TryParse(criterias.DateFinAboTo, out datetime)) { Parameters.Add(new SqlParameter("@DateFinAboTo", SqlDbType.Date) { Value = datetime }); } Parameters.Add(new SqlParameter("@IsFree", SqlDbType.NVarChar) { Value = criterias.IsFree }); Parameters.Add(new SqlParameter("@IsInactif", SqlDbType.NVarChar) { Value = criterias.IsInactif }); Parameters.Add(new SqlParameter("@CodePostal", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.CodePostal) ? criterias.CodePostal : null }); Parameters.Add(new SqlParameter("@Ville", SqlDbType.NVarChar) { Value = !string.IsNullOrWhiteSpace(criterias.Ville) ? criterias.Ville : null }); Parameters.Add(new SqlParameter("@IP", SqlDbType.BigInt) { Value = !string.IsNullOrWhiteSpace(criterias.IP) ? Convert(criterias.IP) : null }); if (criterias.AbonnementID.HasValue) { Parameters.Add(new SqlParameter("@AbonnementID", SqlDbType.BigInt) { Value = criterias.AbonnementID.Value }); } if (criterias.Site.HasValue) { Parameters.Add(new SqlParameter("@SiteID", SqlDbType.BigInt) { Value = criterias.Site.Value }); } if (criterias.NiveauAbonnement.HasValue) { Parameters.Add(new SqlParameter("@NiveauAbonnementID", SqlDbType.BigInt) { Value = criterias.NiveauAbonnement.Value }); } return DbContext.ExecuteStoredProcedureDynamic("sp_SearchAbonnement", Parameters); } public AbonnementResult GetInfosGenerales(long utilisateurID, long id) { List<SqlParameter> Parameters = new List<SqlParameter>(); Parameters.Add(new SqlParameter("@UtilisateurID", SqlDbType.BigInt) { Value = utilisateurID }); Parameters.Add(new SqlParameter("@AbonnementID", SqlDbType.BigInt) { Value = id }); return DbContext.ExecuteStoredProcedure<AbonnementResult>("sp_GetAbonnementDetail", Parameters).FirstOrDefault(); } public IEnumerable<AbonnementResult> GetAbonnementsPourPersonnes(long abonnementID, long utilisateurID) { List<SqlParameter> Parameters = new List<SqlParameter>(); Parameters.Add(new SqlParameter("@UtilisateurID", SqlDbType.BigInt) { Value = utilisateurID }); Parameters.Add(new SqlParameter("@AbonnementID", SqlDbType.BigInt) { Value = abonnementID }); return DbContext.ExecuteStoredProcedure<AbonnementResult>("sp_GetAbonnementPourPersonnes", Parameters); } public IEnumerable<AbonnementResult> GetAbonnementsPourSociete(long abonnementID, long utilisateurID) { List<SqlParameter> Parameters = new List<SqlParameter>(); Parameters.Add(new SqlParameter("@UtilisateurID", SqlDbType.BigInt) { Value = utilisateurID }); Parameters.Add(new SqlParameter("@AbonnementID", SqlDbType.BigInt) { Value = abonnementID }); return DbContext.ExecuteStoredProcedure<AbonnementResult>("sp_GetAbonnementPourSociete", Parameters); } public Abonnement SaveInfosGenerales(AbonnementComposite composite) { Abonnement _abonnement; if (composite.Abonnement.ID > 0) { _abonnement = this.GetById(composite.Abonnement.ID); } else { _abonnement = new Abonnement(); _abonnement.DateCreation = DateTime.Now; } _abonnement.DateModification = DateTime.Now; if (!_abonnement.BlockQualiacFields) { _abonnement.BlockQualiacFields = composite.Abonnement.BlockQualiacFields; } _abonnement.Commentaire = composite.Abonnement.Commentaire; _abonnement.DateDebutAbonnement = composite.Abonnement.DateDebutAbonnement; _abonnement.PasImpressiondeNormes = composite.Abonnement.PasImpressiondeNormes; _abonnement.DateFinAbonnement = composite.Abonnement.DateFinAbonnement; _abonnement.DateFinProlongation = composite.Abonnement.DateFinProlongation; _abonnement.SocieteID = composite.Abonnement.SocieteID; _abonnement.GestionnaireQualiac = composite.Abonnement.GestionnaireQualiac; _abonnement.Gratuit = composite.Abonnement.Gratuit; _abonnement.Suspendu = composite.Abonnement.Suspendu; _abonnement.IdentificationIP = composite.Abonnement.IdentificationIP; _abonnement.NatureAbonnement = composite.Abonnement.NatureAbonnement; _abonnement.NumeroQualiac = composite.Abonnement.NumeroQualiac; _abonnement.SiteID = composite.Abonnement.SiteID; //TODO societe id if (composite.Abonnement.ID > 0) { this.Update(); } else { this.Add(_abonnement); } #region AbonnementIP var abonnementIPsBdd = _abonnementIP.Find(x => x.AbonnementID == _abonnement.ID).ToList(); foreach (var d in abonnementIPsBdd.Where(x => !composite.IPs.Select(z => z.ID).Contains(x.ID))) { _abonnementIP.Delete(d); } foreach (var ip in composite.IPs) { AbonnementIP _ip = null; if (ip.ID > 0) { _ip = _abonnementIP.GetById(ip.ID); } if (_ip == null) { _ip = new AbonnementIP(); } _ip.AbonnementID = _abonnement.ID; _ip.IPDebut = ip.IPDebut; _ip.IPFin = ip.IPFin; _ip.Description = ip.Description; if (_ip.ID > 0) { _abonnementIP.Update(); } else { _abonnementIP.Add(_ip); } } #endregion #region NiveauAbonnements var abonnementsBdd = _lienAbonnementNiveauAbonnement.Find(x => x.AbonnementID == _abonnement.ID).ToList(); foreach (var d in abonnementsBdd.Where(x => !composite.NiveauAbonnements.Select(z => z.ID).Contains(x.ID))) { _lienAbonnementNiveauAbonnement.Delete(d); } foreach (var lien in composite.NiveauAbonnements) { Lien_Abonnement_NiveauAbonnement _lien = null; if (lien.ID > 0) { _lien = _lienAbonnementNiveauAbonnement.GetById(lien.ID); } if (_lien == null) { _lien = new Lien_Abonnement_NiveauAbonnement(); _lien.AbonnementID = _abonnement.ID; } _lien.NiveauAbonnementID = lien.NiveauAbonnementID; if (_lien.ID > 0) { _lienAbonnementNiveauAbonnement.Update(); } else { _lienAbonnementNiveauAbonnement.Add(_lien); } } #endregion #region personnes var personnesBdd = _lienAbonnementPersonne.Find(x => x.AbonnementID == _abonnement.ID).ToList(); foreach (var d in personnesBdd.Where(x => !composite.Personnes.Select(z => z.ID).Contains(x.ID))) { _lienAbonnementPersonne.Delete(d); } foreach (var lien in composite.Personnes.Where(x => x.PersonneID > 0)) { Lien_Abonnement_Personne _lien = null; if (lien.ID > 0) { _lien = _lienAbonnementPersonne.GetById(lien.ID); } if (_lien == null) { _lien = new Lien_Abonnement_Personne(); _lien.AbonnementID = _abonnement.ID; } _lien.PersonneID = lien.PersonneID; _lien.Notify = lien.Notify; if (_lien.ID > 0) { _lienAbonnementPersonne.Update(); } else { _lienAbonnementPersonne.Add(_lien); } } #endregion return _abonnement; } public IEnumerable<QualiacAbonnementResult> ParseQualiacXml(long utilisateurID, string xmlContent) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@UtilisateurID", SqlDbType.BigInt) { Value = utilisateurID }); parameters.Add(new SqlParameter("@XmlContent", SqlDbType.NVarChar) { Value = xmlContent }); return DbContext.ExecuteStoredProcedure<QualiacAbonnementResult>("sp_ParserQualiacAbonnement", parameters); } public IEnumerable<ClientAbonnementResult> GetClientAbonnements(long personneID, long siteID) { List<SqlParameter> Parameters = new List<SqlParameter>(); Parameters.Add(new SqlParameter("@PersonneID", SqlDbType.BigInt) { Value = personneID }); Parameters.Add(new SqlParameter("@SiteID", SqlDbType.BigInt) { Value = siteID }); return DbContext.ExecuteStoredProcedure<ClientAbonnementResult>("sp_GetAbonnementInformation", Parameters); } public string GetClientPerimetreAbonnementToXml(long personneID, long PerimetreAbonnementID) { List<SqlParameter> Parameters = new List<SqlParameter>(); Parameters.Add(new SqlParameter("@PersonneID", SqlDbType.BigInt) { Value = personneID }); Parameters.Add(new SqlParameter("@PerimetreAbonnementID", SqlDbType.BigInt) { Value = PerimetreAbonnementID }); return DbContext.ExecuteStoredProcedureToXls("sp_ClientPerimetreAbonnementExport", Parameters); } } }
#pragma warning disable 1591 using Braintree.Exceptions; using System; using System.IO; using System.Net; #if netcore using System.Net.Http; #else using System.IO.Compression; #endif using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Collections.Generic; namespace Braintree { public class HttpService { protected static readonly Encoding encoding = Encoding.UTF8; #if netcore protected HttpClient httpClient; #endif protected Configuration Configuration; public Environment Environment => Configuration.Environment; public string MerchantId => Configuration.MerchantId; public string PublicKey => Configuration.PublicKey; public string PrivateKey => Configuration.PrivateKey; public string ClientId => Configuration.ClientId; public string ClientSecret => Configuration.ClientSecret; public IWebProxy WebProxy => Configuration.WebProxy; public HttpService(Configuration configuration) { Configuration = configuration; // NEXT_MAJOR_VERSION setting Configuration in an existing gateway instance does NOT update // the underlying httpClient in this service. We should pull Proxy and Timeout settings out // of the Configuration class for easier setting an existing gateway #if netcore var httpClientHandler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, }; if (Configuration.WebProxy != null) { httpClientHandler.UseProxy = true; httpClientHandler.Proxy = Configuration.WebProxy; } httpClient = new HttpClient(httpClientHandler, false); httpClient.Timeout = TimeSpan.FromMilliseconds(Configuration.Timeout); #endif } #if netcore public virtual void SetRequestHeaders(HttpRequestMessage request) { request.Headers.Add("Accept-Encoding", "gzip"); request.Headers.Add("User-Agent", "Braintree .NET " + typeof(BraintreeService).GetTypeInfo().Assembly.GetName().Version.ToString()); request.Headers.Add("Keep-Alive", "false"); // NET Core sends Expect:100-Continue by default which causes sporadic API errors. This setting turns off this default behavior. request.Headers.ExpectContinue = false; } #else public virtual void SetRequestHeaders(HttpWebRequest request) { request.Headers.Add("Authorization", GetAuthorizationHeader()); request.Headers.Add("Accept-Encoding", "gzip"); request.UserAgent = "Braintree .NET " + typeof(BraintreeService).Assembly.GetName().Version.ToString(); // NET Framework sends Expect:100-Continue by default which causes sporadic API errors. This setting turns off this default behavior. request.ServicePoint.Expect100Continue = false; } #endif #if netcore public HttpRequestMessage GetHttpRequest(string URL, string method) { var request = Configuration.HttpRequestMessageFactory(new HttpMethod(method), URL); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(GetAuthorizationSchema(), GetAuthorizationHeader()); SetRequestHeaders(request); return request; } public string GetHttpResponse(HttpRequestMessage request) { var response = httpClient.SendAsync(request).GetAwaiter().GetResult(); if (response.StatusCode != (HttpStatusCode)422) { ThrowExceptionIfErrorStatusCode(response.StatusCode, null); } return ParseResponseStream(response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()); } public async Task<string> GetHttpResponseAsync(HttpRequestMessage request) { var response = await httpClient.SendAsync(request).ConfigureAwait(false); if (response.StatusCode != (HttpStatusCode)422) { ThrowExceptionIfErrorStatusCode(response.StatusCode, null); } return await ParseResponseStreamAsync(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); } #else public HttpWebRequest GetHttpRequest(string URL, string method) { const int SecurityProtocolTypeTls12 = 3072; ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | ((SecurityProtocolType) SecurityProtocolTypeTls12); var request = Configuration.HttpWebRequestFactory(URL); SetRequestProxy(request); SetRequestHeaders(request); request.Method = method; request.KeepAlive = false; request.Timeout = Configuration.Timeout; request.ReadWriteTimeout = Configuration.Timeout; return request; } public string GetHttpResponse(HttpWebRequest request) { try { using (var response = (HttpWebResponse) request.GetResponse()) { return ParseResponseStream(GetResponseStream(response)); } } catch (WebException e) { using (var response = (HttpWebResponse) e.Response) { if (response == null) throw e; if (response.StatusCode == (HttpStatusCode)422) // UnprocessableEntity { return ParseResponseStream(GetResponseStream((HttpWebResponse)e.Response)); } ThrowExceptionIfErrorStatusCode(response.StatusCode, null); } throw e; } } public async Task<string> GetHttpResponseAsync(HttpWebRequest request) { try { using (var response = (HttpWebResponse) await request.GetResponseAsync().ConfigureAwait(false)) { return await ParseResponseStreamAsync(GetResponseStream(response)).ConfigureAwait(false); } } catch (WebException e) { using (var response = (HttpWebResponse) e.Response) { if (response == null) throw e; if (response.StatusCode == (HttpStatusCode)422) // UnprocessableEntity { return await ParseResponseStreamAsync(GetResponseStream((HttpWebResponse) e.Response)).ConfigureAwait(false); } ThrowExceptionIfErrorStatusCode(response.StatusCode, null); } throw e; } } #endif #if net452 protected void SetRequestProxy(WebRequest request) { var proxy = GetWebProxy(); if (proxy != null) { request.Proxy = proxy; } } protected Stream GetResponseStream(HttpWebResponse response) { var stream = response.GetResponseStream(); if (response.ContentEncoding.Equals("gzip", StringComparison.CurrentCultureIgnoreCase)) { stream = new GZipStream(stream, CompressionMode.Decompress); } return stream; } #endif protected string ParseResponseStream(Stream stream) { string body; using (var streamReader = new StreamReader(stream)) { body = streamReader.ReadToEnd(); } return body; } protected async Task<string> ParseResponseStreamAsync(Stream stream) { string body; using (var streamReader = new StreamReader(stream)) { body = await streamReader.ReadToEndAsync().ConfigureAwait(false); } return body; } public IWebProxy GetWebProxy() { return Configuration.WebProxy; } public string GetAuthorizationSchema() { if (Configuration.IsAccessToken) { return "Bearer"; } else { return "Basic"; } } public string GetAuthorizationHeader() { string credentials; #if netcore if (Configuration.IsAccessToken) { return Configuration.AccessToken; } else { if (Configuration.IsClientCredentials) { credentials = ClientId + ":" + ClientSecret; } else { credentials = PublicKey + ":" + PrivateKey; } return Convert.ToBase64String(Encoding.GetEncoding(0).GetBytes(credentials)).Trim(); } #else if (Configuration.IsAccessToken) { return "Bearer " + Configuration.AccessToken; } else { if (Configuration.IsClientCredentials) { credentials = ClientId + ":" + ClientSecret; } else { credentials = PublicKey + ":" + PrivateKey; } return "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(credentials)).Trim(); } #endif } public static void ThrowExceptionIfErrorStatusCode(HttpStatusCode httpStatusCode, string message) { if (httpStatusCode != HttpStatusCode.OK && httpStatusCode != HttpStatusCode.Created) { switch ((int) httpStatusCode) { case 401: throw new AuthenticationException(); case 403: throw new AuthorizationException(message); case 404: throw new NotFoundException(); case 408: throw new RequestTimeoutException(); case 426: throw new UpgradeRequiredException(); case 429: throw new TooManyRequestsException(); case 500: throw new ServerException(); case 503: throw new ServiceUnavailableException(); case 504: throw new GatewayTimeoutException(); default: var exception = new UnexpectedException(); exception.Source = "Unexpected HTTP_RESPONSE " + httpStatusCode; throw exception; } } } protected static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; foreach (var param in postParameters) { if (needsCLRF) { formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); } needsCLRF = true; if (param.Value is FileStream) { FileStream fileToUpload = (FileStream)param.Value; string filename = fileToUpload.Name; string mimeType = GetMIMEType(filename); string header = $"--{boundary}\r\nContent-Disposition: form-data; name=\"{param.Key}\"; filename=\"{filename ?? param.Key}\"\r\nContent-Type: {mimeType ?? "application/octet-stream"}\r\n\r\n"; formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header)); byte[] fileData = null; using (FileStream fs = fileToUpload) { var binaryReader = new BinaryReader(fs, encoding); fileData = binaryReader.ReadBytes((int)fs.Length); } formDataStream.Write(fileData, 0, fileData.Length); } else { string postData = $"--{boundary}\r\nContent-Disposition: form-data; name=\"{param.Key}\"\r\n\r\n{param.Value}"; formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); } } string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer)); formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Dispose(); return formData; } protected static readonly Dictionary<string, string> MIMETypesDictionary = new Dictionary<string, string> { {"bmp", "image/bmp"}, {"jpe", "image/jpeg"}, {"jpeg", "image/jpeg"}, {"jpg", "image/jpeg"}, {"pdf", "application/pdf"}, {"png", "image/png"} }; public static string GetMIMEType(string fileName) { string extension = Path.GetExtension(fileName).ToLowerInvariant(); if (extension.Length > 0 && MIMETypesDictionary.ContainsKey(extension.Remove(0, 1))) { return MIMETypesDictionary[extension.Remove(0, 1)]; } return "application/octet-stream"; } public static string GenerateMultipartFormBoundary() { return $"---------------------{Guid.NewGuid():N}"; } public static string MultipartFormContentType(string boundary) { return "multipart/form-data; boundary=" + boundary; } } } #pragma warning restore 1591
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Orleans.Hosting; using Orleans.Runtime.TestHooks; using Orleans.Configuration; using Orleans.Messaging; using Orleans.Runtime; using Orleans.Runtime.MembershipService; using Orleans.Statistics; using Orleans.TestingHost.Utils; using Orleans.TestingHost.Logging; using Orleans.Configuration.Internal; namespace Orleans.TestingHost { /// <summary> /// Utility for creating silos given a name and collection of configuration sources. /// </summary> public class TestClusterHostFactory { /// <summary> /// Creates an returns a new silo. /// </summary> /// <param name="hostName">The silo name if it is not already specified in the configuration.</param> /// <param name="configuration">The configuration.</param> /// <returns>A new silo.</returns> public static IHost CreateSiloHost(string hostName, IConfiguration configuration) { string siloName = configuration[nameof(TestSiloSpecificOptions.SiloName)] ?? hostName; var hostBuilder = new HostBuilder(); hostBuilder.Properties["Configuration"] = configuration; hostBuilder.ConfigureHostConfiguration(cb => cb.AddConfiguration(configuration)); hostBuilder.UseOrleans(siloBuilder => { siloBuilder .Configure<ClusterOptions>(configuration) .Configure<SiloOptions>(options => options.SiloName = siloName) .Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(30)); }); ConfigureAppServices(configuration, hostBuilder); hostBuilder.ConfigureServices((context, services) => { services.AddSingleton<TestHooksHostEnvironmentStatistics>(); services.AddFromExisting<IHostEnvironmentStatistics, TestHooksHostEnvironmentStatistics>(); services.AddSingleton<TestHooksSystemTarget>(); ConfigureListeningPorts(context.Configuration, services); TryConfigureClusterMembership(context.Configuration, services); TryConfigureFileLogging(configuration, services, siloName); if (Debugger.IsAttached) { // Test is running inside debugger - Make timeout ~= infinite services.Configure<SiloMessagingOptions>(op => op.ResponseTimeout = TimeSpan.FromMilliseconds(1000000)); } }); var host = hostBuilder.Build(); var silo = host.Services.GetRequiredService<IHost>(); InitializeTestHooksSystemTarget(silo); return silo; } public static IHost CreateClusterClient(string hostName, IEnumerable<IConfigurationSource> configurationSources) { var configBuilder = new ConfigurationBuilder(); foreach (var source in configurationSources) { configBuilder.Add(source); } var configuration = configBuilder.Build(); var hostBuilder = new HostBuilder(); hostBuilder.Properties["Configuration"] = configuration; hostBuilder.ConfigureHostConfiguration(cb => cb.AddConfiguration(configuration)) .UseOrleansClient(clientBuilder => { clientBuilder.Configure<ClusterOptions>(configuration); ConfigureAppServices(configuration, clientBuilder); }) .ConfigureServices(services => { TryConfigureClientMembership(configuration, services); TryConfigureFileLogging(configuration, services, hostName); }); var host = hostBuilder.Build(); return host; } public static string SerializeConfiguration(IConfiguration configuration) { var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.None, }; KeyValuePair<string, string>[] enumerated = configuration.AsEnumerable().ToArray(); return JsonConvert.SerializeObject(enumerated, settings); } public static IConfiguration DeserializeConfiguration(string serializedSources) { var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, }; var builder = new ConfigurationBuilder(); var enumerated = JsonConvert.DeserializeObject<KeyValuePair<string, string>[]>(serializedSources, settings); builder.AddInMemoryCollection(enumerated); return builder.Build(); } private static void ConfigureListeningPorts(IConfiguration configuration, IServiceCollection services) { int siloPort = int.Parse(configuration[nameof(TestSiloSpecificOptions.SiloPort)]); int gatewayPort = int.Parse(configuration[nameof(TestSiloSpecificOptions.GatewayPort)]); services.Configure<EndpointOptions>(options => { options.AdvertisedIPAddress = IPAddress.Loopback; options.SiloPort = siloPort; options.GatewayPort = gatewayPort; options.SiloListeningEndpoint = new IPEndPoint(IPAddress.Loopback, siloPort); if (gatewayPort != 0) { options.GatewayListeningEndpoint = new IPEndPoint(IPAddress.Loopback, gatewayPort); } }); } private static void ConfigureAppServices(IConfiguration configuration, IHostBuilder hostBuilder) { var builderConfiguratorTypes = configuration.GetSection(nameof(TestClusterOptions.SiloBuilderConfiguratorTypes))?.Get<string[]>(); if (builderConfiguratorTypes == null) return; foreach (var builderConfiguratorType in builderConfiguratorTypes) { if (!string.IsNullOrWhiteSpace(builderConfiguratorType)) { var configurator = Activator.CreateInstance(Type.GetType(builderConfiguratorType, true)); (configurator as IHostConfigurator)?.Configure(hostBuilder); hostBuilder.UseOrleans(siloBuilder => (configurator as ISiloConfigurator)?.Configure(siloBuilder)); } } } private static void ConfigureAppServices(IConfiguration configuration, IClientBuilder clientBuilder) { var builderConfiguratorTypes = configuration.GetSection(nameof(TestClusterOptions.ClientBuilderConfiguratorTypes))?.Get<string[]>(); if (builderConfiguratorTypes == null) return; foreach (var builderConfiguratorType in builderConfiguratorTypes) { if (!string.IsNullOrWhiteSpace(builderConfiguratorType)) { var builderConfigurator = (IClientBuilderConfigurator)Activator.CreateInstance(Type.GetType(builderConfiguratorType, true)); builderConfigurator?.Configure(configuration, clientBuilder); } } } private static void TryConfigureClusterMembership(IConfiguration configuration, IServiceCollection services) { bool.TryParse(configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership); // Configure test cluster membership if requested and if no membership table implementation has been registered. // If the test involves a custom membership oracle and no membership table, special care will be required if (useTestClusterMembership && services.All(svc => svc.ServiceType != typeof(IMembershipTable))) { var primarySiloEndPoint = new IPEndPoint(IPAddress.Loopback, int.Parse(configuration[nameof(TestSiloSpecificOptions.PrimarySiloPort)])); services.Configure<DevelopmentClusterMembershipOptions>(options => options.PrimarySiloEndpoint = primarySiloEndPoint); services .AddSingleton<SystemTargetBasedMembershipTable>() .AddFromExisting<IMembershipTable, SystemTargetBasedMembershipTable>(); } } private static void TryConfigureClientMembership(IConfiguration configuration, IClientBuilder clientBuilder) { bool.TryParse(configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership); if (useTestClusterMembership) { Action<StaticGatewayListProviderOptions> configureOptions = options => { int baseGatewayPort = int.Parse(configuration[nameof(TestClusterOptions.BaseGatewayPort)]); int initialSilosCount = int.Parse(configuration[nameof(TestClusterOptions.InitialSilosCount)]); bool gatewayPerSilo = bool.Parse(configuration[nameof(TestClusterOptions.GatewayPerSilo)]); if (gatewayPerSilo) { options.Gateways = Enumerable.Range(baseGatewayPort, initialSilosCount) .Select(port => new IPEndPoint(IPAddress.Loopback, port).ToGatewayUri()) .ToList(); } else { options.Gateways = new List<Uri> { new IPEndPoint(IPAddress.Loopback, baseGatewayPort).ToGatewayUri() }; } }; clientBuilder.Configure(configureOptions); clientBuilder.ConfigureServices(services => { services.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>() .ConfigureFormatter<StaticGatewayListProviderOptions>(); }); } } private static void TryConfigureClientMembership(IConfiguration configuration, IServiceCollection services) { bool.TryParse(configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership); if (useTestClusterMembership && services.All(svc => svc.ServiceType != typeof(IGatewayListProvider))) { Action<StaticGatewayListProviderOptions> configureOptions = options => { int baseGatewayPort = int.Parse(configuration[nameof(TestClusterOptions.BaseGatewayPort)]); int initialSilosCount = int.Parse(configuration[nameof(TestClusterOptions.InitialSilosCount)]); bool gatewayPerSilo = bool.Parse(configuration[nameof(TestClusterOptions.GatewayPerSilo)]); if (gatewayPerSilo) { options.Gateways = Enumerable.Range(baseGatewayPort, initialSilosCount) .Select(port => new IPEndPoint(IPAddress.Loopback, port).ToGatewayUri()) .ToList(); } else { options.Gateways = new List<Uri> { new IPEndPoint(IPAddress.Loopback, baseGatewayPort).ToGatewayUri() }; } }; if (configureOptions != null) { services.Configure(configureOptions); } services.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>() .ConfigureFormatter<StaticGatewayListProviderOptions>(); } } private static void TryConfigureFileLogging(IConfiguration configuration, IServiceCollection services, string name) { bool.TryParse(configuration[nameof(TestClusterOptions.ConfigureFileLogging)], out bool configureFileLogging); if (configureFileLogging) { var fileName = TestingUtils.CreateTraceFileName(name, configuration[nameof(TestClusterOptions.ClusterId)]); services.AddLogging(loggingBuilder => loggingBuilder.AddFile(fileName)); } } private static void InitializeTestHooksSystemTarget(IHost host) { var testHook = host.Services.GetRequiredService<TestHooksSystemTarget>(); var catalog = host.Services.GetRequiredService<Catalog>(); catalog.RegisterSystemTarget(testHook); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Routing; using Microsoft.Framework.Logging; using Hawk.Models; using Hawk.Services; namespace Hawk.Controllers { [Route("blog")] public class BlogController : Controller { const int PAGE_SIZE = 5; readonly IPostRepository _repo; readonly ILogger _logger; public BlogController(IPostRepository repo, ILoggerFactory loggerFactory) { if (repo == null) { throw new ArgumentNullException(nameof(repo)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } this._repo = repo; this._logger = loggerFactory.CreateLogger(nameof(BlogController)); } void Log([CallerMemberName] string methodName = null) { _logger.LogInformation(methodName); } RouteValueDictionary GetRouteValues(int pageNum, object routeValues = null) { var routeValueDict = new RouteValueDictionary(routeValues); routeValueDict.Add("pageNum", pageNum); return routeValueDict; } IActionResult PostsHelper(IEnumerable<Post> posts, int pageNum, string action, object routeValues = null) { // if the user asks for a page less than or equal to zero, redirect to the first page if (pageNum <= 0) { return RedirectToAction(action); } // if there are no posts, return 404 var postCount = posts.Count(); if (postCount == 0) { return View("MultiplePosts", posts.ToArray()); //return HttpNotFound(); } // if the user asks for a page beyond the last page, redirect to the last page var pageCount = postCount / PAGE_SIZE + (postCount % PAGE_SIZE == 0 ? 0 : 1); if (pageNum > pageCount) { return RedirectToAction(action + "Page", GetRouteValues(pageCount, routeValues)); } var actionPage = action + "Page"; var skip = (pageNum - 1) * PAGE_SIZE; var pagePosts = posts.Skip(skip).Take(PAGE_SIZE).ToArray(); // generate previous / next page link URLs // If we're already on the first/last page, then don't generate prev/next page URLs // If we're on page 2, generate the prev page link to the root action instead of action/page/1 ViewBag.NewerPostsLink = pageNum == 1 ? string.Empty : (pageNum == 2 ? Url.Action(action, routeValues) : Url.Action(actionPage, GetRouteValues(pageNum - 1, routeValues))); ViewBag.OlderPostsLink = pageNum == pageCount ? string.Empty : Url.Action(actionPage, GetRouteValues(pageNum + 1, routeValues)); return View("MultiplePosts", pagePosts); } public IActionResult Index() { Log(); return IndexPage(1); } [Route("archives")] public IActionResult Archives() { var posts = _repo.Posts().ToArray(); return View(posts); } [Route("page/{pageNum}")] public IActionResult IndexPage(int pageNum) { Log(); ViewBag.Title = "Blog Home"; return PostsHelper(_repo.Posts(), pageNum, "Index"); } [Route("{year:int}")] public IActionResult PostsByYear(int year) { return PostsByYearPage(year, 1); } [Route("{year:int}/page/{pageNum:int}")] public IActionResult PostsByYearPage(int year, int pageNum) { Log(); ViewBag.Title = $"Posts from ({year})"; ViewBag.PageHeader = $"Posts from {year}"; return PostsHelper(_repo.Posts().Where(p => p.Date.Year == year), pageNum, "PostsByYear", new { year }); } [Route("{year:int}/{month:range(1,12)}")] public IActionResult PostsByMonth(int year, int month) { return PostsByMonthPage(year, month, 1); } [Route("{year:int}/{month:range(1,12)}/page/{pageNum}")] public IActionResult PostsByMonthPage(int year, int month, int pageNum) { Log(); var monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month); ViewBag.Title = $"Posts from ({year}-{month})"; ViewBag.PageHeader = $"Posts from {monthName} {year}"; return PostsHelper( _repo.Posts().Where(p => p.Date.Year == year && p.Date.Month == month), pageNum, "PostsByMonth", new { year, month }); } [Route("{year:int}/{month:range(1,12)}/{day:range(1,31)}")] public IActionResult PostsByDay(int year, int month, int day) { return PostsByDayPage(year, month, day, 1); } [Route("{year:int}/{month:range(1,12)}/{day:range(1,31)}/page/{pageNum}")] public IActionResult PostsByDayPage(int year, int month, int day, int pageNum) { Log(); var monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month); ViewBag.Title = $"Posts from ({year}-{month}-{day})"; ViewBag.PageHeader = $"Posts from {monthName} {day}, {year}"; return PostsHelper( _repo.Posts().Where(p => p.Date.Year == year && p.Date.Month == month && p.Date.Day == day), pageNum, "PostsByMonth", new { year, month, day }); } string GeneratePostUrl(Post post) { return Url.Action("Post", new {year = post.Date.Year, month = post.Date.Month, day = post.Date.Day, slug = post.Slug}); } [Route("{year:int}/{month:range(1,12)}/{day:range(1,31)}/{slug}")] public IActionResult Post(int year, int month, int day, string slug) { Log(); var post = _repo.Posts().FirstOrDefault(p => p.Date.Year == year && p.Date.Month == month && p.Date.Day == day && p.Slug == slug); if (post == null) { return HttpNotFound(); } ViewBag.Title = $"- {post.Title}"; return View("Post", post); } [Route("{slug}")] public IActionResult SlugPost(string slug) { Log(); var post = _repo.Posts().FirstOrDefault(p => p.Slug == slug); if (post == null) { return HttpNotFound(); } return RedirectToAction("Post", new { year = post.Date.Year, month = post.Date.Month, day = post.Date.Day, slug } ); } [Route("category/{name}")] public IActionResult Category(string name) { return CategoryPage(name, 1); } [Route("category/{name}/page/{pageNum}")] public IActionResult CategoryPage(string name, int pageNum) { Log(); var title = _repo.Categories() .Where(s => s.Item1.Slug == name) .Select(s => s.Item1.Title) .Single(); ViewBag.Title = $"({title}) Posts"; ViewBag.PageHeader = $"{title} Posts"; return PostsHelper( _repo.Posts().Where(p => p.Categories.Any(c => c.Slug == name)), pageNum, "Category", new { name }); } [Route("tag/{name}")] public IActionResult Tag(string name) { return TagPage(name, 1); } [Route("tag/{name}/page/{pageNum}")] public IActionResult TagPage(string name, int pageNum) { Log(); var title = _repo.Tags() .Where(s => s.Item1.Slug == name) .Select(s => s.Item1.Title) .Single(); ViewBag.Title = $"({title}) Posts"; ViewBag.PageHeader = $"{title} Posts"; return PostsHelper( _repo.Posts().Where(p => p.Tags.Any(c => c.Slug == name)), pageNum, "Tag", new { name }); } [Route("author/{slug}")] public IActionResult Author(string slug) { return AuthorPage(slug, 1); } [Route("author/{slug}/page/{pageNum}")] public IActionResult AuthorPage(string slug, int pageNum) { Log(); var name = _repo.Posts() .Where(p => p.Author.Slug == slug) .Select(p => p.Author.Name) .First(); ViewBag.Title = $"Posts by ({name})"; ViewBag.PageHeader = $"Posts by {name}"; return PostsHelper( _repo.Posts().Where(p => p.Author.Slug == slug), pageNum, "Author", new { slug }); } } }
//----------------------------------------------------------------------- // <copyright company="TheNucleus"> // Copyright (c) TheNucleus. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Abstractions; using System.Linq; using System.Security.AccessControl; namespace Test.Mocks { [SuppressMessage( "Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "This class is used in other assemblies")] internal sealed class MockDirectory : DirectoryBase { private readonly IEnumerable<string> _files; private readonly bool _throwOnCreate; public MockDirectory( IEnumerable<string> files, bool throwOnCreate = false) { _files = files; _throwOnCreate = throwOnCreate; } public override DirectoryInfoBase CreateDirectory(string path) { return CreateDirectory(path, new DirectorySecurity()); } public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity) { if (_throwOnCreate) { throw new IOException(); } return null; } public override void Delete(string path) { // Do nothing for now ... } public override void Delete(string path, bool recursive) { // Do nothing for now ... } public override IEnumerable<string> EnumerateDirectories(string path) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateDirectories(string path, string searchPattern) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateFiles(string path) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateFiles(string path, string searchPattern) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateFileSystemEntries(string path) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern) { throw new NotImplementedException(); } public override IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) { throw new NotImplementedException(); } public override bool Exists(string path) { return _files.Contains(path); } public override DirectorySecurity GetAccessControl(string path) { throw new NotImplementedException(); } public override DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections) { throw new NotImplementedException(); } public override DateTime GetCreationTime(string path) { return DateTime.Now.AddHours(-1); } public override DateTime GetCreationTimeUtc(string path) { return DateTime.Now.AddHours(-1); } public override string GetCurrentDirectory() { throw new NotImplementedException(); } public override string[] GetDirectories(string path) { throw new NotImplementedException(); } public override string[] GetDirectories(string path, string searchPattern) { throw new NotImplementedException(); } public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { throw new NotImplementedException(); } public override string GetDirectoryRoot(string path) { throw new NotImplementedException(); } public override string[] GetFiles(string path) { return GetFiles(path, "*.*"); } public override string[] GetFiles(string path, string searchPattern) { return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { return _files.ToArray(); } public override string[] GetFileSystemEntries(string path) { throw new NotImplementedException(); } public override string[] GetFileSystemEntries(string path, string searchPattern) { throw new NotImplementedException(); } public override DateTime GetLastAccessTime(string path) { return DateTime.Now.AddHours(-1); } public override DateTime GetLastAccessTimeUtc(string path) { return DateTime.Now.AddHours(-1); } public override DateTime GetLastWriteTime(string path) { return DateTime.Now.AddHours(-1); } public override DateTime GetLastWriteTimeUtc(string path) { return DateTime.Now.AddHours(-1); } public override string[] GetLogicalDrives() { throw new NotImplementedException(); } public override DirectoryInfoBase GetParent(string path) { throw new NotImplementedException(); } public override void Move(string sourceDirName, string destDirName) { // Do nothing for now ... } public override void SetAccessControl(string path, DirectorySecurity directorySecurity) { // Do nothing for now ... } public override void SetCreationTime(string path, DateTime creationTime) { // Do nothing for now ... } public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { // Do nothing for now ... } public override void SetCurrentDirectory(string path) { // Do nothing for now ... } public override void SetLastAccessTime(string path, DateTime lastAccessTime) { // Do nothing for now ... } public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { // Do nothing for now ... } public override void SetLastWriteTime(string path, DateTime lastWriteTime) { // Do nothing for now ... } public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { // Do nothing for now ... } } }
using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Web; using Appleseed.Framework.DataTypes; using Appleseed.Framework.Settings; using Appleseed.Framework.Site.Configuration; using Appleseed.Framework.Web.UI.WebControls; namespace Appleseed.Framework.Localization { using System.Collections.Generic; using System.Web.UI.WebControls; /// <summary> /// Summary description for LanguageSwitcher. /// </summary> public class LanguageSwitcher : PortalModuleControl { /// <summary> /// /// </summary> public const string LANGUAGE_DEFAULT = "en-US"; /// <summary> /// /// </summary> protected Web.UI.WebControls.LanguageSwitcher LanguageSwitcher1; /// <summary> /// /// </summary> /// <param name="addInvariantCulture"></param> /// <returns></returns> public static CultureInfo[] GetLanguageList(bool addInvariantCulture) { return GetLanguageCultureList().ToUICultureArray(addInvariantCulture); } /// <summary> /// Gets the language culture list. /// </summary> /// <returns></returns> public static LanguageCultureCollection GetLanguageCultureList() { string strLangList = LANGUAGE_DEFAULT; //default for design time // Obtain PortalSettings from Current Context if (HttpContext.Current != null && HttpContext.Current.Items["PortalSettings"] != null) { //Do not remove these checks!! It fails installing modules on startup PortalSettings PortalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"]; strLangList = PortalSettings.GetLanguageList(); } LanguageCultureCollection langList; try { langList = (LanguageCultureCollection) TypeDescriptor.GetConverter(typeof (LanguageCultureCollection)).ConvertTo(strLangList, typeof ( LanguageCultureCollection )); } catch (Exception ex) { //ErrorHandler.HandleException("Failed to load languages, loading defaults", ex); ErrorHandler.Publish(LogLevel.Warn, "Failed to load languages, loading defaults", ex); langList = (LanguageCultureCollection) TypeDescriptor.GetConverter(typeof(LanguageCultureCollection)).ConvertTo( LANGUAGE_DEFAULT, typeof(LanguageCultureCollection)); } return langList; } /// <summary> /// Initializes a new instance of the <see cref="LanguageSwitcher"/> class. /// </summary> /// <remarks> /// </remarks> public LanguageSwitcher() { // Language Switcher Module - Type var languageSwitcherTypesOptions = new List<SettingOption> { new SettingOption( (int)LanguageSwitcherType.DropDownList, General.GetString("LANGSWITCHTYPE_DROPDOWNLIST", "DropDownList", null)), new SettingOption( (int)LanguageSwitcherType.VerticalLinksList, General.GetString("LANGSWITCHTYPE_LINKS", "Links", null)), new SettingOption( (int)LanguageSwitcherType.HorizontalLinksList, General.GetString("LANGSWITCHTYPE_LINKSHORIZONTAL", "Links Horizontal", null)) }; var languageSwitchType = new SettingItem<string, ListControl>( new CustomListDataType(languageSwitcherTypesOptions, "Name", "Val")) { EnglishName = "Language Switcher Type", Description = "Select here how your language switcher should look like.", Value = ((int)LanguageSwitcherType.VerticalLinksList).ToString(), Order = (int)SettingItemGroup.THEME_LAYOUT_SETTINGS + 910, Group = SettingItemGroup.THEME_LAYOUT_SETTINGS }; this.BaseSettings.Add("LANGUAGESWITCHER_TYPES", languageSwitchType); // Language Switcher Module - DisplayOptions var languageSwitcherDisplayOptions = new List<SettingOption> { new SettingOption( (int)LanguageSwitcherDisplay.DisplayCultureList, General.GetString("LANGSWITCHTDISPLAY_CULTURELIST", "Using Culture Name", null)), new SettingOption( (int)LanguageSwitcherDisplay.DisplayUICultureList, General.GetString("LANGSWITCHTDISPLAY_UICULTURELIST", "Using UI Culture Name", null)), new SettingOption( (int)LanguageSwitcherDisplay.DisplayNone, General.GetString("LANGSWITCHTDISPLAY_NONE", "None", null)) }; // Flags var languageSwitchFlags = new SettingItem<string, ListControl>( new CustomListDataType(languageSwitcherDisplayOptions, "Name", "Val")) { EnglishName = "Show Flags as", Description = "Select here how flags should look like.", Value = ((int)LanguageSwitcherDisplay.DisplayCultureList).ToString(), Order = (int)SettingItemGroup.THEME_LAYOUT_SETTINGS + 920, Group = SettingItemGroup.THEME_LAYOUT_SETTINGS }; this.BaseSettings.Add("LANGUAGESWITCHER_FLAGS", languageSwitchFlags); // Labels var languageSwitchLabels = new SettingItem<string, ListControl>( new CustomListDataType(languageSwitcherDisplayOptions, "Name", "Val")) { EnglishName = "Show Labels as", Description = "Select here how Labels should look like.", Value = ((int)LanguageSwitcherDisplay.DisplayCultureList).ToString(), Order = (int)SettingItemGroup.THEME_LAYOUT_SETTINGS + 930, Group = SettingItemGroup.THEME_LAYOUT_SETTINGS }; this.BaseSettings.Add("LANGUAGESWITCHER_LABELS", languageSwitchLabels); // Language Switcher Module - NamesOptions var languageSwitcherNamesOptions = new List<SettingOption> { new SettingOption( (int)LanguageSwitcherName.NativeName, General.GetString("LANGSWITCHTNAMES_NATIVENAME", "Native Name", null)), new SettingOption( (int)LanguageSwitcherName.EnglishName, General.GetString("LANGSWITCHTNAMES_ENGLISHNAME", "English Name", null)), new SettingOption( (int)LanguageSwitcherName.DisplayName, General.GetString("LANGSWITCHTNAMES_DISPLAYNAME", "Display Name", null)) }; // Names var languageSwitcherName = new SettingItem<string, ListControl>(new CustomListDataType(languageSwitcherNamesOptions, "Name", "Val")) { EnglishName = "Show names as", Description = "Select here how names should look like.", Value = ((int)LanguageSwitcherName.NativeName).ToString(), Order = (int)SettingItemGroup.THEME_LAYOUT_SETTINGS + 940, Group = SettingItemGroup.THEME_LAYOUT_SETTINGS }; this.BaseSettings.Add("LANGUAGESWITCHER_NAMES", languageSwitcherName); // Use flag images from portal's images folder? var customFlags = new SettingItem<bool, CheckBox> { Order = (int)SettingItemGroup.THEME_LAYOUT_SETTINGS + 950, Group = SettingItemGroup.THEME_LAYOUT_SETTINGS, EnglishName = "Use custom flags?", Description = "Check this if you want to use custom flags from portal's images folder. Custom flags are located in portal folder. /images/flags/", Value = false }; this.BaseSettings.Add("LANGUAGESWITCHER_CUSTOMFLAGS", customFlags); SupportsWorkflow = false; } /// <summary> /// GUID of module (mandatory) /// </summary> /// <value></value> public override Guid GuidID { get { return new Guid("{25E3290E-3B9A-4302-9384-9CA01243C00F}"); } } #region Web Form Designer generated code /// <summary> /// Raises OnInit event. /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { // CODEGEN: This call is required by the ASP.NET Web Form Designer. //this.Cultures = LANGUAGE_DEFAULT; //completely wrong line! it removes culture check on this module and hides it :S this.Load += new EventHandler(this.LanguageSwitcher_Load); // create ModuleTitle // ModuleTitle = new DesktopModuleTitle(); // Controls.AddAt(0, ModuleTitle); LanguageSwitcher1 = new Appleseed.Framework.Web.UI.WebControls.LanguageSwitcher(); Controls.Add(LanguageSwitcher1); // Jes1111 if (!((Appleseed.Framework.Web.UI.Page) this.Page).IsCssFileRegistered("Mod_LanguageSwitcher")) ((Appleseed.Framework.Web.UI.Page) this.Page).RegisterCssFile("Mod_LanguageSwitcher"); base.OnInit(e); } #endregion /// <summary> /// Handles the Load event of the LanguageSwitcher control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void LanguageSwitcher_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { LanguageSwitcher1.LanguageListString = GetLanguageCultureList().ToString(); LanguageSwitcher1.ChangeLanguageAction = LanguageSwitcherAction.LinkRedirect; LanguageSwitcher1.Type = (LanguageSwitcherType) Enum.Parse(typeof (LanguageSwitcherType), Settings["LANGUAGESWITCHER_TYPES"].ToString()); LanguageSwitcher1.Flags = (LanguageSwitcherDisplay) Enum.Parse(typeof (LanguageSwitcherDisplay), Settings["LANGUAGESWITCHER_FLAGS"].ToString()); LanguageSwitcher1.Labels = (LanguageSwitcherDisplay) Enum.Parse(typeof (LanguageSwitcherDisplay), Settings["LANGUAGESWITCHER_LABELS"].ToString()); LanguageSwitcher1.ShowNameAs = (LanguageSwitcherName) Enum.Parse(typeof (LanguageSwitcherName), Settings["LANGUAGESWITCHER_NAMES"].ToString()); //LanguageSwitcher1.ChangeLanguageUrl = Page.Request.RawUrl; if (bool.Parse(Settings["LANGUAGESWITCHER_CUSTOMFLAGS"].ToString())) LanguageSwitcher1.ImagePath = this.PortalSettings.PortalFullPath + "/images/flags/"; else LanguageSwitcher1.ImagePath = Path.WebPathCombine(Path.ApplicationRoot, "aspnet_client/flags/"); } } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Translate.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTranslationServiceClientTest { [xunit::FactAttribute] public void TranslateTextRequestObject() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, MimeType = "mime_type606a0ffc", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", Model = "model635ef320", GlossaryConfig = new TranslateTextGlossaryConfig(), ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse response = client.TranslateText(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TranslateTextRequestObjectAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, MimeType = "mime_type606a0ffc", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", Model = "model635ef320", GlossaryConfig = new TranslateTextGlossaryConfig(), ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TranslateText1() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, TargetLanguageCode = "target_language_code6ec12c87", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse response = client.TranslateText(request.Parent, request.TargetLanguageCode, request.Contents); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TranslateText1Async() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, TargetLanguageCode = "target_language_code6ec12c87", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.Parent, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.Parent, request.TargetLanguageCode, request.Contents, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TranslateText1ResourceNames() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, TargetLanguageCode = "target_language_code6ec12c87", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse response = client.TranslateText(request.ParentAsLocationName, request.TargetLanguageCode, request.Contents); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TranslateText1ResourceNamesAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, TargetLanguageCode = "target_language_code6ec12c87", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.ParentAsLocationName, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.ParentAsLocationName, request.TargetLanguageCode, request.Contents, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TranslateText2() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, MimeType = "mime_type606a0ffc", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse response = client.TranslateText(request.Parent, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TranslateText2Async() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, MimeType = "mime_type606a0ffc", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.Parent, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.Parent, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TranslateText2ResourceNames() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, MimeType = "mime_type606a0ffc", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse response = client.TranslateText(request.ParentAsLocationName, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TranslateText2ResourceNamesAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateTextRequest request = new TranslateTextRequest { Contents = { "contents8c7dbf98", }, MimeType = "mime_type606a0ffc", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; TranslateTextResponse expectedResponse = new TranslateTextResponse { Translations = { new Translation(), }, GlossaryTranslations = { new Translation(), }, }; mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DetectLanguageRequestObject() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DetectLanguageRequest request = new DetectLanguageRequest { Content = "contentb964039a", MimeType = "mime_type606a0ffc", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; DetectLanguageResponse expectedResponse = new DetectLanguageResponse { Languages = { new DetectedLanguage(), }, }; mockGrpcClient.Setup(x => x.DetectLanguage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); DetectLanguageResponse response = client.DetectLanguage(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DetectLanguageRequestObjectAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DetectLanguageRequest request = new DetectLanguageRequest { Content = "contentb964039a", MimeType = "mime_type606a0ffc", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; DetectLanguageResponse expectedResponse = new DetectLanguageResponse { Languages = { new DetectedLanguage(), }, }; mockGrpcClient.Setup(x => x.DetectLanguageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DetectLanguageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); DetectLanguageResponse responseCallSettings = await client.DetectLanguageAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DetectLanguageResponse responseCancellationToken = await client.DetectLanguageAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DetectLanguage() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DetectLanguageRequest request = new DetectLanguageRequest { Content = "contentb964039a", MimeType = "mime_type606a0ffc", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; DetectLanguageResponse expectedResponse = new DetectLanguageResponse { Languages = { new DetectedLanguage(), }, }; mockGrpcClient.Setup(x => x.DetectLanguage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); DetectLanguageResponse response = client.DetectLanguage(request.Parent, request.Model, request.MimeType, request.Content); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DetectLanguageAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DetectLanguageRequest request = new DetectLanguageRequest { Content = "contentb964039a", MimeType = "mime_type606a0ffc", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; DetectLanguageResponse expectedResponse = new DetectLanguageResponse { Languages = { new DetectedLanguage(), }, }; mockGrpcClient.Setup(x => x.DetectLanguageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DetectLanguageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); DetectLanguageResponse responseCallSettings = await client.DetectLanguageAsync(request.Parent, request.Model, request.MimeType, request.Content, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DetectLanguageResponse responseCancellationToken = await client.DetectLanguageAsync(request.Parent, request.Model, request.MimeType, request.Content, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DetectLanguageResourceNames() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DetectLanguageRequest request = new DetectLanguageRequest { Content = "contentb964039a", MimeType = "mime_type606a0ffc", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; DetectLanguageResponse expectedResponse = new DetectLanguageResponse { Languages = { new DetectedLanguage(), }, }; mockGrpcClient.Setup(x => x.DetectLanguage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); DetectLanguageResponse response = client.DetectLanguage(request.ParentAsLocationName, request.Model, request.MimeType, request.Content); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DetectLanguageResourceNamesAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DetectLanguageRequest request = new DetectLanguageRequest { Content = "contentb964039a", MimeType = "mime_type606a0ffc", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; DetectLanguageResponse expectedResponse = new DetectLanguageResponse { Languages = { new DetectedLanguage(), }, }; mockGrpcClient.Setup(x => x.DetectLanguageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DetectLanguageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); DetectLanguageResponse responseCallSettings = await client.DetectLanguageAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.Content, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DetectLanguageResponse responseCancellationToken = await client.DetectLanguageAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.Content, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSupportedLanguagesRequestObject() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest { DisplayLanguageCode = "display_language_code67946a7b", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SupportedLanguages expectedResponse = new SupportedLanguages { Languages = { new SupportedLanguage(), }, }; mockGrpcClient.Setup(x => x.GetSupportedLanguages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); SupportedLanguages response = client.GetSupportedLanguages(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSupportedLanguagesRequestObjectAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest { DisplayLanguageCode = "display_language_code67946a7b", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SupportedLanguages expectedResponse = new SupportedLanguages { Languages = { new SupportedLanguage(), }, }; mockGrpcClient.Setup(x => x.GetSupportedLanguagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SupportedLanguages>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); SupportedLanguages responseCallSettings = await client.GetSupportedLanguagesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SupportedLanguages responseCancellationToken = await client.GetSupportedLanguagesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSupportedLanguages() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest { DisplayLanguageCode = "display_language_code67946a7b", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SupportedLanguages expectedResponse = new SupportedLanguages { Languages = { new SupportedLanguage(), }, }; mockGrpcClient.Setup(x => x.GetSupportedLanguages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); SupportedLanguages response = client.GetSupportedLanguages(request.Parent, request.Model, request.DisplayLanguageCode); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSupportedLanguagesAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest { DisplayLanguageCode = "display_language_code67946a7b", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SupportedLanguages expectedResponse = new SupportedLanguages { Languages = { new SupportedLanguage(), }, }; mockGrpcClient.Setup(x => x.GetSupportedLanguagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SupportedLanguages>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); SupportedLanguages responseCallSettings = await client.GetSupportedLanguagesAsync(request.Parent, request.Model, request.DisplayLanguageCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SupportedLanguages responseCancellationToken = await client.GetSupportedLanguagesAsync(request.Parent, request.Model, request.DisplayLanguageCode, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSupportedLanguagesResourceNames() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest { DisplayLanguageCode = "display_language_code67946a7b", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SupportedLanguages expectedResponse = new SupportedLanguages { Languages = { new SupportedLanguage(), }, }; mockGrpcClient.Setup(x => x.GetSupportedLanguages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); SupportedLanguages response = client.GetSupportedLanguages(request.ParentAsLocationName, request.Model, request.DisplayLanguageCode); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSupportedLanguagesResourceNamesAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest { DisplayLanguageCode = "display_language_code67946a7b", Model = "model635ef320", ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SupportedLanguages expectedResponse = new SupportedLanguages { Languages = { new SupportedLanguage(), }, }; mockGrpcClient.Setup(x => x.GetSupportedLanguagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SupportedLanguages>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); SupportedLanguages responseCallSettings = await client.GetSupportedLanguagesAsync(request.ParentAsLocationName, request.Model, request.DisplayLanguageCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SupportedLanguages responseCancellationToken = await client.GetSupportedLanguagesAsync(request.ParentAsLocationName, request.Model, request.DisplayLanguageCode, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TranslateDocumentRequestObject() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateDocumentRequest request = new TranslateDocumentRequest { Parent = "parent7858e4d0", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", DocumentInputConfig = new DocumentInputConfig(), DocumentOutputConfig = new DocumentOutputConfig(), Model = "model635ef320", GlossaryConfig = new TranslateTextGlossaryConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; TranslateDocumentResponse expectedResponse = new TranslateDocumentResponse { DocumentTranslation = new DocumentTranslation(), GlossaryDocumentTranslation = new DocumentTranslation(), Model = "model635ef320", GlossaryConfig = new TranslateTextGlossaryConfig(), }; mockGrpcClient.Setup(x => x.TranslateDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateDocumentResponse response = client.TranslateDocument(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TranslateDocumentRequestObjectAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TranslateDocumentRequest request = new TranslateDocumentRequest { Parent = "parent7858e4d0", SourceLanguageCode = "source_language_code14998292", TargetLanguageCode = "target_language_code6ec12c87", DocumentInputConfig = new DocumentInputConfig(), DocumentOutputConfig = new DocumentOutputConfig(), Model = "model635ef320", GlossaryConfig = new TranslateTextGlossaryConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; TranslateDocumentResponse expectedResponse = new TranslateDocumentResponse { DocumentTranslation = new DocumentTranslation(), GlossaryDocumentTranslation = new DocumentTranslation(), Model = "model635ef320", GlossaryConfig = new TranslateTextGlossaryConfig(), }; mockGrpcClient.Setup(x => x.TranslateDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateDocumentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); TranslateDocumentResponse responseCallSettings = await client.TranslateDocumentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TranslateDocumentResponse responseCancellationToken = await client.TranslateDocumentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGlossaryRequestObject() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlossaryRequest request = new GetGlossaryRequest { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), }; Glossary expectedResponse = new Glossary { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), LanguagePair = new Glossary.Types.LanguageCodePair(), LanguageCodesSet = new Glossary.Types.LanguageCodesSet(), InputConfig = new GlossaryInputConfig(), EntryCount = -1925390589, SubmitTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetGlossary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); Glossary response = client.GetGlossary(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGlossaryRequestObjectAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlossaryRequest request = new GetGlossaryRequest { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), }; Glossary expectedResponse = new Glossary { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), LanguagePair = new Glossary.Types.LanguageCodePair(), LanguageCodesSet = new Glossary.Types.LanguageCodesSet(), InputConfig = new GlossaryInputConfig(), EntryCount = -1925390589, SubmitTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetGlossaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Glossary>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); Glossary responseCallSettings = await client.GetGlossaryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Glossary responseCancellationToken = await client.GetGlossaryAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGlossary() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlossaryRequest request = new GetGlossaryRequest { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), }; Glossary expectedResponse = new Glossary { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), LanguagePair = new Glossary.Types.LanguageCodePair(), LanguageCodesSet = new Glossary.Types.LanguageCodesSet(), InputConfig = new GlossaryInputConfig(), EntryCount = -1925390589, SubmitTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetGlossary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); Glossary response = client.GetGlossary(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGlossaryAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlossaryRequest request = new GetGlossaryRequest { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), }; Glossary expectedResponse = new Glossary { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), LanguagePair = new Glossary.Types.LanguageCodePair(), LanguageCodesSet = new Glossary.Types.LanguageCodesSet(), InputConfig = new GlossaryInputConfig(), EntryCount = -1925390589, SubmitTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetGlossaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Glossary>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); Glossary responseCallSettings = await client.GetGlossaryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Glossary responseCancellationToken = await client.GetGlossaryAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGlossaryResourceNames() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlossaryRequest request = new GetGlossaryRequest { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), }; Glossary expectedResponse = new Glossary { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), LanguagePair = new Glossary.Types.LanguageCodePair(), LanguageCodesSet = new Glossary.Types.LanguageCodesSet(), InputConfig = new GlossaryInputConfig(), EntryCount = -1925390589, SubmitTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetGlossary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); Glossary response = client.GetGlossary(request.GlossaryName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGlossaryResourceNamesAsync() { moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlossaryRequest request = new GetGlossaryRequest { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), }; Glossary expectedResponse = new Glossary { GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"), LanguagePair = new Glossary.Types.LanguageCodePair(), LanguageCodesSet = new Glossary.Types.LanguageCodesSet(), InputConfig = new GlossaryInputConfig(), EntryCount = -1925390589, SubmitTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetGlossaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Glossary>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null); Glossary responseCallSettings = await client.GetGlossaryAsync(request.GlossaryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Glossary responseCancellationToken = await client.GetGlossaryAsync(request.GlossaryName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using UnityEngine; namespace Cinemachine { /// <summary> /// Describes a blend between 2 Cinemachine Virtual Cameras, and holds the /// current state of the blend. /// </summary> public class CinemachineBlend { /// <summary>First camera in the blend</summary> public ICinemachineCamera CamA { get; private set; } /// <summary>Second camera in the blend</summary> public ICinemachineCamera CamB { get; private set; } /// <summary>The curve that describes the way the blend transitions over time /// from the first camera to the second. X-axis is time in seconds over which /// the blend takes place and Y axis is blend weight (0..1)</summary> public AnimationCurve BlendCurve { get; private set; } /// <summary>The current time relative to the start of the blend</summary> public float TimeInBlend { get; set; } /// <summary>The current weight of the blend. This is an evaluation of the /// BlendCurve at the current time relative to the start of the blend. /// 0 means camA, 1 means camB.</summary> public float BlendWeight { get { return BlendCurve != null ? BlendCurve.Evaluate(TimeInBlend) : 0; } } /// <summary>Validity test for the blend. True if both cameras are defined, /// and there is a nontrivial blend curve.</summary> public bool IsValid { get { return (CamA != null || CamB != null) && BlendCurve != null && BlendCurve.keys.Length > 1; } } /// <summary>Duration in seconds of the blend. /// This is given read from the BlendCurve.</summary> public float Duration { get { return IsValid ? BlendCurve.keys[BlendCurve.keys.Length - 1].time : 0; } } /// <summary>True if the time relative to the start of the blend is greater /// than or equal to the blend duration</summary> public bool IsComplete { get { return TimeInBlend >= Duration; } } /// <summary>Text description of the blend, for debugging</summary> public string Description { get { string fromName = (CamA != null) ? CamA.Name : "(none)"; string toName = (CamB != null) ? CamB.Name : "(none)"; int percent = (int)(BlendWeight * 100f); return string.Format("{0} {1}% from {2}", toName, percent, fromName); } } /// <summary>Does the blend use a specific Cinemachine Virtual Camera?</summary> /// <param name="cam">The camera to test</param> /// <returns>True if the camera is involved in the blend</returns> public bool Uses(ICinemachineCamera cam) { if (cam == CamA || cam == CamB) return true; BlendSourceVirtualCamera b = CamA as BlendSourceVirtualCamera; if (b != null && b.Blend.Uses(cam)) return true; b = CamB as BlendSourceVirtualCamera; if (b != null && b.Blend.Uses(cam)) return true; return false; } /// <summary>Construct a blend</summary> /// <param name="a">First camera</param> /// <param name="b">Second camera</param> /// <param name="curve">Blend curve</param> /// <param name="t">Current time in blend, relative to the start of the blend</param> public CinemachineBlend( ICinemachineCamera a, ICinemachineCamera b, AnimationCurve curve, float t) { if (a == null || b == null) throw new ArgumentException("Blend cameras cannot be null"); CamA = a; CamB = b; BlendCurve = curve; TimeInBlend = t; } /// <summary>Make sure the source cameras get updated.</summary> /// <param name="worldUp">Default world up. Individual vcams may modify this</param> /// <param name="deltaTime">Time increment used for calculating time-based behaviours (e.g. damping)</param> public void UpdateCameraState(Vector3 worldUp, float deltaTime) { // Make sure both cameras have been updated (they are not necessarily // enabled, and only enabled top-level cameras get updated automatically // every frame) CinemachineCore.Instance.UpdateVirtualCamera(CamA, worldUp, deltaTime); CinemachineCore.Instance.UpdateVirtualCamera(CamB, worldUp, deltaTime); } /// <summary>Compute the blended CameraState for the current time in the blend.</summary> public CameraState State { get { return CameraState.Lerp(CamA.State, CamB.State, BlendWeight); } } } /// <summary>Definition of a Camera blend. This struct holds the information /// necessary to generate a suitable AnimationCurve for a Cinemachine Blend.</summary> [Serializable] [DocumentationSorting(10.2f, DocumentationSortingAttribute.Level.UserRef)] public struct CinemachineBlendDefinition { /// <summary>Supported predefined shapes for the blend curve.</summary> [DocumentationSorting(10.21f, DocumentationSortingAttribute.Level.UserRef)] public enum Style { /// <summary>Zero-length blend</summary> Cut, /// <summary>S-shaped curve, giving a gentle and smooth transition</summary> EaseInOut, /// <summary>Linear out of the outgoing shot, and easy into the incoming</summary> EaseIn, /// <summary>Easy out of the outgoing shot, and linear into the incoming</summary> EaseOut, /// <summary>Easy out of the outgoing, and hard into the incoming</summary> HardIn, /// <summary>Hard out of the outgoing, and easy into the incoming</summary> HardOut, /// <summary>Linear blend. Mechanical-looking.</summary> Linear }; /// <summary>The shape of the blend curve.</summary> [Tooltip("Shape of the blend curve")] public Style m_Style; /// <summary>The duration (in seconds) of the blend</summary> [Tooltip("Duration (in seconds) of the blend")] public float m_Time; /// <summary>Constructor</summary> /// <param name="style">The shape of the blend curve.</param> /// <param name="time">The duration (in seconds) of the blend</param> public CinemachineBlendDefinition(Style style, float time) { m_Style = style; m_Time = time; } /// <summary> /// An AnimationCurve specifying the interpolation duration and value /// for this camera blend. The time of the last key frame is assumed to the be the /// duration of the blend. Y-axis values must be in range [0,1] (internally clamped /// within Blender) and time must be in range of [0, +infinity) /// </summary> public AnimationCurve BlendCurve { get { float time = Mathf.Max(0, m_Time); switch (m_Style) { default: case Style.Cut: return new AnimationCurve(); case Style.EaseInOut: return AnimationCurve.EaseInOut(0f, 0f, time, 1f); case Style.EaseIn: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[1].inTangent = 0; curve.keys = keys; return curve; } case Style.EaseOut: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[0].outTangent = 0; curve.keys = keys; return curve; } case Style.HardIn: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[0].outTangent = 0; keys[1].inTangent = 1.5708f; // pi/2 = up curve.keys = keys; return curve; } case Style.HardOut: { AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); Keyframe[] keys = curve.keys; keys[0].outTangent = 1.5708f; // pi/2 = up keys[1].inTangent = 0; curve.keys = keys; return curve; } case Style.Linear: return AnimationCurve.Linear(0f, 0f, time, 1f); } } } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Conn.Params.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Conn.Params { /// <summary> /// <para>Allows for setting parameters relating to connection managers on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParamBean", AccessFlags = 33)] public partial class ConnManagerParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnManagerParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(J)V", AccessFlags = 1)] public virtual void SetTimeout(long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(I)V", AccessFlags = 1)] public virtual void SetMaxTotalConnections(int maxConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setConnectionsPerRoute /// </java-name> [Dot42.DexImport("setConnectionsPerRoute", "(Lorg/apache/http/conn/params/ConnPerRouteBean;)V", AccessFlags = 1)] public virtual void SetConnectionsPerRoute(global::Org.Apache.Http.Conn.Params.ConnPerRouteBean connPerRoute) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnManagerParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>This interface is intended for looking up maximum number of connections allowed for for a given route. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>651813 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRoute /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRoute", AccessFlags = 1537)] public partial interface IConnPerRoute /* scope: __dot42__ */ { /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1025)] int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Allows for setting parameters relating to connection routes on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParamBean", AccessFlags = 33)] public partial class ConnRouteParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnRouteParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::DEFAULT_PROXY </para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetDefaultProxy(global::Org.Apache.Http.HttpHost defaultProxy) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::LOCAL_ADDRESS </para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Ljava/net/InetAddress;)V", AccessFlags = 1)] public virtual void SetLocalAddress(global::Java.Net.InetAddress address) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::FORCED_ROUTE </para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 1)] public virtual void SetForcedRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnRouteParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnManagerPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the timeout in milliseconds used when retrieving an instance of org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager. </para><para>This parameter expects a value of type Long. </para> /// </summary> /// <java-name> /// TIMEOUT /// </java-name> [Dot42.DexImport("TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string TIMEOUT = "http.conn-manager.timeout"; /// <summary> /// <para>Defines the maximum number of connections per route. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type ConnPerRoute. </para> /// </summary> /// <java-name> /// MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("MAX_CONNECTIONS_PER_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route"; /// <summary> /// <para>Defines the maximum number of connections in total. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("MAX_TOTAL_CONNECTIONS", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total"; } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537)] public partial interface IConnManagerPNames /* scope: __dot42__ */ { } /// <summary> /// <para>This class maintains a map of HTTP routes to maximum number of connections allowed for those routes. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>652947 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRouteBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRouteBean", AccessFlags = 49)] public sealed partial class ConnPerRouteBean : global::Org.Apache.Http.Conn.Params.IConnPerRoute /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed per host </para> /// </summary> /// <java-name> /// DEFAULT_MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("DEFAULT_MAX_CONNECTIONS_PER_ROUTE", "I", AccessFlags = 25)] public const int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2; [Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)] public ConnPerRouteBean(int defaultMax) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnPerRouteBean() /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] public int GetDefaultMax() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setDefaultMaxPerRoute /// </java-name> [Dot42.DexImport("setDefaultMaxPerRoute", "(I)V", AccessFlags = 1)] public void SetDefaultMaxPerRoute(int max) /* MethodBuilder.Create */ { } /// <java-name> /// setMaxForRoute /// </java-name> [Dot42.DexImport("setMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;I)V", AccessFlags = 1)] public void SetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route, int max) /* MethodBuilder.Create */ { } /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1)] public int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setMaxForRoutes /// </java-name> [Dot42.DexImport("setMaxForRoutes", "(Ljava/util/Map;)V", AccessFlags = 1, Signature = "(Ljava/util/Map<Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Integer;>;)V")] public void SetMaxForRoutes(global::Java.Util.IMap<global::Org.Apache.Http.Conn.Routing.HttpRoute, int?> map) /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> public int DefaultMax { [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] get{ return GetDefaultMax(); } } } /// <summary> /// <para>This class represents a collection of HTTP protocol parameters applicable to client-side connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke</para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0</para><para>ConnManagerPNames </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParams", AccessFlags = 49)] public sealed partial class ConnManagerParams : global::Org.Apache.Http.Conn.Params.IConnManagerPNames /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed overall </para> /// </summary> /// <java-name> /// DEFAULT_MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("DEFAULT_MAX_TOTAL_CONNECTIONS", "I", AccessFlags = 25)] public const int DEFAULT_MAX_TOTAL_CONNECTIONS = 20; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnManagerParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds. </para> /// </returns> /// <java-name> /// getTimeout /// </java-name> [Dot42.DexImport("getTimeout", "(Lorg/apache/http/params/HttpParams;)J", AccessFlags = 9)] public static long GetTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(long); } /// <summary> /// <para>Sets the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(Lorg/apache/http/params/HttpParams;J)V", AccessFlags = 9)] public static void SetTimeout(global::Org.Apache.Http.Params.IHttpParams @params, long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("setMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/params/ConnPerRoute;)V", AccessFlags = 9)] public static void SetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Params.IConnPerRoute connPerRoute) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <returns> /// <para>lookup interface for maximum number of connections allowed per route.</para> /// </returns> /// <java-name> /// getMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("getMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/params/ConnPerRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Params.IConnPerRoute GetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Params.IConnPerRoute); } /// <summary> /// <para>Sets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params, int maxTotalConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <returns> /// <para>The maximum number of connections allowed.</para> /// </returns> /// <java-name> /// getMaxTotalConnections /// </java-name> [Dot42.DexImport("getMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } } /// <summary> /// <para>An adaptor for accessing route related parameters in HttpParams. See ConnRoutePNames for parameter name definitions.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParams", AccessFlags = 33)] public partial class ConnRouteParams : global::Org.Apache.Http.Conn.Params.IConnRoutePNames /* scope: __dot42__ */ { /// <summary> /// <para>A special value indicating "no host". This relies on a nonsense scheme name to avoid conflicts with actual hosts. Note that this is a <b>valid</b> host. </para> /// </summary> /// <java-name> /// NO_HOST /// </java-name> [Dot42.DexImport("NO_HOST", "Lorg/apache/http/HttpHost;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.HttpHost NO_HOST; /// <summary> /// <para>A special value indicating "no route". This is a route with NO_HOST as the target. </para> /// </summary> /// <java-name> /// NO_ROUTE /// </java-name> [Dot42.DexImport("NO_ROUTE", "Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.Conn.Routing.HttpRoute NO_ROUTE; /// <summary> /// <para>Disabled default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal ConnRouteParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the DEFAULT_PROXY parameter value. NO_HOST will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the default proxy set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getDefaultProxy /// </java-name> [Dot42.DexImport("getDefaultProxy", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/HttpHost;", AccessFlags = 9)] public static global::Org.Apache.Http.HttpHost GetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.HttpHost); } /// <summary> /// <para>Sets the DEFAULT_PROXY parameter value.</para><para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/HttpHost;)V", AccessFlags = 9)] public static void SetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.HttpHost proxy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the FORCED_ROUTE parameter value. NO_ROUTE will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the forced route set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getForcedRoute /// </java-name> [Dot42.DexImport("getForcedRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Routing.HttpRoute GetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Routing.HttpRoute); } /// <summary> /// <para>Sets the FORCED_ROUTE parameter value.</para><para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 9)] public static void SetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the LOCAL_ADDRESS parameter value. There is no special value that would automatically be mapped to <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4, :: for IPv6) to override a specific local address in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the local address set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getLocalAddress /// </java-name> [Dot42.DexImport("getLocalAddress", "(Lorg/apache/http/params/HttpParams;)Ljava/net/InetAddress;", AccessFlags = 9)] public static global::Java.Net.InetAddress GetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Java.Net.InetAddress); } /// <summary> /// <para>Sets the LOCAL_ADDRESS parameter value.</para><para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Lorg/apache/http/params/HttpParams;Ljava/net/InetAddress;)V", AccessFlags = 9)] public static void SetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params, global::Java.Net.InetAddress local) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnConnectionPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the maximum number of ignorable lines before we expect a HTTP response's status line. </para><para>With HTTP/1.1 persistent connections, the problem arises that broken scripts could return a wrong Content-Length (there are more bytes sent than specified). Unfortunately, in some cases, this cannot be detected after the bad response, but only before the next one. So HttpClient must be able to skip those surplus lines this way. </para><para>This parameter expects a value of type Integer. 0 disallows all garbage/empty lines before the status line. Use java.lang.Integer#MAX_VALUE for unlimited (default in lenient mode). </para> /// </summary> /// <java-name> /// MAX_STATUS_LINE_GARBAGE /// </java-name> [Dot42.DexImport("MAX_STATUS_LINE_GARBAGE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage"; } /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537)] public partial interface IConnConnectionPNames /* scope: __dot42__ */ { } /// <summary> /// <para>Allows for setting parameters relating to connections on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionParamBean", AccessFlags = 33)] public partial class ConnConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnConnectionPNames::MAX_STATUS_LINE_GARBAGE </para></para> /// </summary> /// <java-name> /// setMaxStatusLineGarbage /// </java-name> [Dot42.DexImport("setMaxStatusLineGarbage", "(I)V", AccessFlags = 1)] public virtual void SetMaxStatusLineGarbage(int maxStatusLineGarbage) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnRoutePNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Parameter for the default proxy. The default value will be used by some HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// DEFAULT_PROXY /// </java-name> [Dot42.DexImport("DEFAULT_PROXY", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_PROXY = "http.route.default-proxy"; /// <summary> /// <para>Parameter for the local address. On machines with multiple network interfaces, this parameter can be used to select the network interface from which the connection originates. It will be interpreted by the standard HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type java.net.InetAddress. </para> /// </summary> /// <java-name> /// LOCAL_ADDRESS /// </java-name> [Dot42.DexImport("LOCAL_ADDRESS", "Ljava/lang/String;", AccessFlags = 25)] public const string LOCAL_ADDRESS = "http.route.local-address"; /// <summary> /// <para>Parameter for an forced route. The forced route will be interpreted by the standard HttpRoutePlanner implementations. Instead of computing a route, the given forced route will be returned, even if it points to the wrong target host. </para><para>This parameter expects a value of type HttpRoute. </para> /// </summary> /// <java-name> /// FORCED_ROUTE /// </java-name> [Dot42.DexImport("FORCED_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string FORCED_ROUTE = "http.route.forced-route"; } /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537)] public partial interface IConnRoutePNames /* scope: __dot42__ */ { } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Security.Cryptography.RNG.Tests { public class RandomNumberGeneratorTests { [Fact] public static void DifferentSequential_10() { DifferentSequential(10); } [Fact] public static void DifferentSequential_256() { DifferentSequential(256); } [Fact] public static void DifferentSequential_65536() { DifferentSequential(65536); } [Fact] public static void DifferentParallel_10() { DifferentParallel(10); } [Fact] public static void DifferentParallel_256() { DifferentParallel(256); } [Fact] public static void DifferentParallel_65536() { DifferentParallel(65536); } [Fact] public static void NeutralParity() { byte[] random = new byte[2048]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(random); } AssertNeutralParity(random); } [Fact] public static void IdempotentDispose() { RandomNumberGenerator rng = RandomNumberGenerator.Create(); for (int i = 0; i < 10; i++) { rng.Dispose(); } } [Fact] public static void NullInput() { using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { Assert.Throws<ArgumentNullException>(() => rng.GetBytes(null)); } } [Fact] public static void ZeroLengthInput() { using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { // While this will do nothing, it's not something that throws. rng.GetBytes(Array.Empty<byte>()); } } [Fact] public static void ConcurrentAccess() { const int ParallelTasks = 3; const int PerTaskIterationCount = 20; const int RandomSize = 1024; Task[] tasks = new Task[ParallelTasks]; byte[][] taskArrays = new byte[ParallelTasks][]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) using (ManualResetEvent sync = new ManualResetEvent(false)) { for (int iTask = 0; iTask < ParallelTasks; iTask++) { taskArrays[iTask] = new byte[RandomSize]; byte[] taskLocal = taskArrays[iTask]; tasks[iTask] = Task.Run( () => { sync.WaitOne(); for (int i = 0; i < PerTaskIterationCount; i++) { rng.GetBytes(taskLocal); } }); } // Ready? Set() Go! sync.Set(); Task.WaitAll(tasks); } for (int i = 0; i < ParallelTasks; i++) { // The Real test would be to ensure independence of data, but that's difficult. // The other end of the spectrum is to test that they aren't all just new byte[RandomSize]. // Middle ground is to assert that each of the chunks has neutral(ish) bit parity. AssertNeutralParity(taskArrays[i]); } } private static void DifferentSequential(int arraySize) { // Ensure that the RNG doesn't produce a stable set of data. byte[] first = new byte[arraySize]; byte[] second = new byte[arraySize]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(first); rng.GetBytes(second); } // Random being random, there is a chance that it could produce the same sequence. // The smallest test case that we have is 10 bytes. // The probability that they are the same, given a Truly Random Number Generator is: // Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9) // = 1/256 * 1/256 * ... * 1/256 // = 1/(256^10) // = 1/1,208,925,819,614,629,174,706,176 Assert.NotEqual(first, second); } private static void DifferentParallel(int arraySize) { // Ensure that two RNGs don't produce the same data series (such as being implemented via new Random(1)). byte[] first = new byte[arraySize]; byte[] second = new byte[arraySize]; using (RandomNumberGenerator rng1 = RandomNumberGenerator.Create()) using (RandomNumberGenerator rng2 = RandomNumberGenerator.Create()) { rng1.GetBytes(first); rng2.GetBytes(second); } // Random being random, there is a chance that it could produce the same sequence. // The smallest test case that we have is 10 bytes. // The probability that they are the same, given a Truly Random Number Generator is: // Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9) // = 1/256 * 1/256 * ... * 1/256 // = 1/(256^10) // = 1/1,208,925,819,614,629,174,706,176 Assert.NotEqual(first, second); } private static void AssertNeutralParity(byte[] random) { int oneCount = 0; int zeroCount = 0; for (int i = 0; i < random.Length; i++) { for (int j = 0; j < 8; j++) { if (((random[i] >> j) & 1) == 1) { oneCount++; } else { zeroCount++; } } } int totalCount = zeroCount + oneCount; float bitDifference = (float)Math.Abs(zeroCount - oneCount) / totalCount; // Over the long run there should be about as many 1s as 0s. // This isn't a guarantee, just a statistical observation. // Allow a 7% tolerance band before considering it to have gotten out of hand. const double AllowedTolerance = 0.07; Assert.True(bitDifference < AllowedTolerance, "Expected bitDifference < " + AllowedTolerance + ", got " + bitDifference + "."); } } }
// ReSharper disable RedundantArgumentDefaultValue namespace Gu.State.Tests { using System.Collections.Generic; using System.Collections.ObjectModel; using NUnit.Framework; using static DirtyTrackerTypes; public static partial class DirtyTrackerTests { public static class ObservableCollectionOfComplexType { [TestCase(ReferenceHandling.Structural)] [TestCase(ReferenceHandling.References)] public static void CreateAndDispose(ReferenceHandling referenceHandling) { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType>(); var changes = new List<string>(); using (var tracker = Track.IsDirty(x, y, referenceHandling)) { tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); var expected = "ObservableCollection<ComplexType> [0] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item [1] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); CollectionAssert.IsEmpty(changes); } x.Add(new ComplexType("c", 3)); CollectionAssert.IsEmpty(changes); x[0].Value++; CollectionAssert.IsEmpty(changes); x[1].Value++; CollectionAssert.IsEmpty(changes); x[2].Value++; CollectionAssert.IsEmpty(changes); } [Test] public static void AddSameToBoth() { var x = new ObservableCollection<ComplexType>(); var y = new ObservableCollection<ComplexType>(); var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Add(new ComplexType("a", 1)); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Add(new ComplexType("a", 1)); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); x[0].Value++; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Value x: 2 y: 1", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[0].Value++; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void AddThenUpdate() { var x = new ObservableCollection<ComplexType>(); var y = new ObservableCollection<ComplexType>(); var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); x.Add(new ComplexType("a", 1)); y.Add(new ComplexType("a", 1)); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x[0].Value++; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Value x: 2 y: 1", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[0].Value++; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void AddDifferent() { var x = new ObservableCollection<ComplexType>(); var y = new ObservableCollection<ComplexType>(); var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Add(new ComplexType("a", 1)); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Add(new ComplexType("b", 2)); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: a y: b Value x: 1 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); x[0].Name = "b"; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Value x: 1 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); y[0].Value = 1; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [TestCase(0)] [TestCase(1)] [TestCase(2)] public static void InsertX(int index) { var x = new ObservableCollection<ComplexType> { new ComplexType(), new ComplexType(), new ComplexType() }; var y = new ObservableCollection<ComplexType> { new ComplexType(), new ComplexType(), new ComplexType() }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Insert(index, new ComplexType()); Assert.AreEqual(true, tracker.IsDirty); var expected = "ObservableCollection<ComplexType> [3] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [TestCase(0)] [TestCase(1)] [TestCase(2)] public static void InsertY(int index) { var x = new ObservableCollection<ComplexType> { new ComplexType(), new ComplexType(), new ComplexType() }; var y = new ObservableCollection<ComplexType> { new ComplexType(), new ComplexType(), new ComplexType() }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); y.Insert(index, new ComplexType()); Assert.AreEqual(true, tracker.IsDirty); var expected = "ObservableCollection<ComplexType> [3] x: missing item y: Gu.State.Tests.DirtyTrackerTypes+ComplexType"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [TestCase(0)] [TestCase(1)] [TestCase(2)] public static void InsertXThenYThenUpdate(int index) { var x = new ObservableCollection<ComplexType> { new ComplexType(), new ComplexType(), new ComplexType() }; var y = new ObservableCollection<ComplexType> { new ComplexType(), new ComplexType(), new ComplexType() }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); x.Insert(index, new ComplexType()); y.Insert(index, new ComplexType()); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x[index].Value++; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual($"ObservableCollection<ComplexType> [{index}] Value x: 1 y: 0", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[index].Value = x[index].Value; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void RemoveTheDifference() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [1] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.RemoveAt(1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void RemoveStillDirty1() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("c", 3) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: a y: c Value x: 1 y: 3 [1] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.RemoveAt(1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: a y: c Value x: 1 y: 3", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void RemoveStillDirty2() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 0), new ComplexType("b", 0), new ComplexType("c", 0) }; var y = new ObservableCollection<ComplexType> { new ComplexType("d", 0), new ComplexType("e", 0) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: a y: d [1] Name x: b y: e [2] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.RemoveAt(0); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: b y: d [1] Name x: c y: e", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void ClearBothWhenNotDirty() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Clear(); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] x: missing item y: Gu.State.Tests.DirtyTrackerTypes+ComplexType [1] x: missing item y: Gu.State.Tests.DirtyTrackerTypes+ComplexType", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Clear(); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void ClearBothWhenDirty() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("c", 2), new ComplexType("d", 4), new ComplexType("e", 5) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); var expected = "ObservableCollection<ComplexType> [0] Name x: a y: c Value x: 1 y: 2 [1] Name x: b y: d Value x: 2 y: 4 [2] x: missing item y: Gu.State.Tests.DirtyTrackerTypes+ComplexType"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); CollectionAssert.IsEmpty(changes); x.Clear(); Assert.AreEqual(true, tracker.IsDirty); expected = "ObservableCollection<ComplexType> [0] x: missing item y: Gu.State.Tests.DirtyTrackerTypes+ComplexType [1] x: missing item y: Gu.State.Tests.DirtyTrackerTypes+ComplexType [2] x: missing item y: Gu.State.Tests.DirtyTrackerTypes+ComplexType"; Assert.AreEqual(expected, tracker.Diff.ToString(string.Empty, " ")); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); y.Clear(); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void MoveX() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Move(0, 1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: b y: a Value x: 2 y: 1 [1] Name x: a y: b Value x: 1 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); x.Move(0, 1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void MoveXThenY() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Move(0, 1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: b y: a Value x: 2 y: 1 [1] Name x: a y: b Value x: 1 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Move(0, 1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void MoveXThenYThenUpdate() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); x.Move(0, 1); y.Move(0, 1); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x[0].Value++; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Value x: 3 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[0].Value = x[0].Value; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void Replace() { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x[0] = new ComplexType("c", 3); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Name x: c y: a Value x: 3 y: 1", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[0] = new ComplexType("c", 3); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [TestCase(0)] [TestCase(1)] public static void ReplaceThenUpdate(int index) { var x = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); x[index] = new ComplexType("c", 3); y[index] = new ComplexType("c", 3); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x[index].Value++; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual($"ObservableCollection<ComplexType> [{index}] Value x: 4 y: 3", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[index].Value = x[index].Value; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void TracksItems() { var x = new ObservableCollection<ComplexType>(); var y = new ObservableCollection<ComplexType>(); var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Add(new ComplexType("a", 1)); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] x: Gu.State.Tests.DirtyTrackerTypes+ComplexType y: missing item", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Add(new ComplexType("a", 1)); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); x[0].Value++; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<ComplexType> [0] Value x: 2 y: 1", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[0].Value++; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); var complexType = y[0]; y[0] = new ComplexType(complexType.Name, complexType.Value); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.AreEqual(expectedChanges, changes); complexType.Value++; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void DuplicateItemOneNotification() { var item = new ComplexType("a", 1); var x = new ObservableCollection<ComplexType> { item, item }; var y = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("a", 1) }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); item.Value++; Assert.AreEqual(true, tracker.IsDirty); var expected = "ObservableCollection<ComplexType> [0] Value x: 2 y: 1 [1] Value x: 2 y: 1"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); expectedChanges.AddRange(new[] { "Diff", "IsDirty", "Diff" }); // not sure how we want this CollectionAssert.AreEqual(expectedChanges, changes); } } } }
namespace IdSharp.Tagging.Harness.WinForms.UserControls { partial class ID3v2UserControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ID3v2UserControl)); this.txtFilename = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.imageBindingNavigator = new System.Windows.Forms.BindingNavigator(this.components); this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel(); this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox(); this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.label9 = new System.Windows.Forms.Label(); this.txtArtist = new System.Windows.Forms.TextBox(); this.txtTitle = new System.Windows.Forms.TextBox(); this.txtImageDescription = new System.Windows.Forms.TextBox(); this.txtAlbum = new System.Windows.Forms.TextBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.imageContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.miLoadImage = new System.Windows.Forms.ToolStripMenuItem(); this.miSaveImage = new System.Windows.Forms.ToolStripMenuItem(); this.txtYear = new System.Windows.Forms.TextBox(); this.cmbImageType = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtTrackNumber = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.cmbID3v2 = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.lblID3v2 = new System.Windows.Forms.Label(); this.cmbGenre = new System.Windows.Forms.ComboBox(); this.imageOpenFileDialog = new System.Windows.Forms.OpenFileDialog(); this.imageSaveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.txtPlayLength = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.txtBitrate = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.txtEncoderPreset = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.chkPodcast = new System.Windows.Forms.CheckBox(); this.txtPodcastFeedUrl = new System.Windows.Forms.TextBox(); this.label14 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.imageBindingNavigator)).BeginInit(); this.imageBindingNavigator.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.imageContextMenu.SuspendLayout(); this.SuspendLayout(); // // txtFilename // this.txtFilename.Location = new System.Drawing.Point(98, 9); this.txtFilename.Name = "txtFilename"; this.txtFilename.ReadOnly = true; this.txtFilename.Size = new System.Drawing.Size(300, 20); this.txtFilename.TabIndex = 101; this.txtFilename.TabStop = false; // // label10 // this.label10.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(407, 319); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(60, 13); this.label10.TabIndex = 126; this.label10.Text = "Description"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(10, 65); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(30, 13); this.label1.TabIndex = 106; this.label1.Text = "Artist"; // // imageBindingNavigator // this.imageBindingNavigator.AddNewItem = this.bindingNavigatorAddNewItem; this.imageBindingNavigator.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.imageBindingNavigator.CountItem = this.bindingNavigatorCountItem; this.imageBindingNavigator.DeleteItem = this.bindingNavigatorDeleteItem; this.imageBindingNavigator.Dock = System.Windows.Forms.DockStyle.None; this.imageBindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bindingNavigatorMoveFirstItem, this.bindingNavigatorMovePreviousItem, this.bindingNavigatorSeparator, this.bindingNavigatorPositionItem, this.bindingNavigatorCountItem, this.bindingNavigatorSeparator1, this.bindingNavigatorMoveNextItem, this.bindingNavigatorMoveLastItem, this.bindingNavigatorSeparator2, this.bindingNavigatorAddNewItem, this.bindingNavigatorDeleteItem}); this.imageBindingNavigator.Location = new System.Drawing.Point(410, 339); this.imageBindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem; this.imageBindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem; this.imageBindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem; this.imageBindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem; this.imageBindingNavigator.Name = "imageBindingNavigator"; this.imageBindingNavigator.PositionItem = this.bindingNavigatorPositionItem; this.imageBindingNavigator.Size = new System.Drawing.Size(255, 25); this.imageBindingNavigator.TabIndex = 124; this.imageBindingNavigator.Text = "bindingNavigator1"; // // bindingNavigatorAddNewItem // this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image"))); this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem"; this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorAddNewItem.Text = "Add new"; this.bindingNavigatorAddNewItem.Click += new System.EventHandler(this.bindingNavigatorAddNewItem_Click); // // bindingNavigatorCountItem // this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem"; this.bindingNavigatorCountItem.Size = new System.Drawing.Size(35, 22); this.bindingNavigatorCountItem.Text = "of {0}"; this.bindingNavigatorCountItem.ToolTipText = "Total number of items"; // // bindingNavigatorDeleteItem // this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image"))); this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem"; this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorDeleteItem.Text = "Delete"; this.bindingNavigatorDeleteItem.Click += new System.EventHandler(this.bindingNavigatorDeleteItem_Click); // // bindingNavigatorMoveFirstItem // this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image"))); this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem"; this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveFirstItem.Text = "Move first"; // // bindingNavigatorMovePreviousItem // this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image"))); this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem"; this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMovePreviousItem.Text = "Move previous"; // // bindingNavigatorSeparator // this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator"; this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorPositionItem // this.bindingNavigatorPositionItem.AccessibleName = "Position"; this.bindingNavigatorPositionItem.AutoSize = false; this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem"; this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 21); this.bindingNavigatorPositionItem.Text = "0"; this.bindingNavigatorPositionItem.ToolTipText = "Current position"; // // bindingNavigatorSeparator1 // this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1"; this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorMoveNextItem // this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image"))); this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem"; this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveNextItem.Text = "Move next"; // // bindingNavigatorMoveLastItem // this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image"))); this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem"; this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveLastItem.Text = "Move last"; // // bindingNavigatorSeparator2 // this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2"; this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25); // // label9 // this.label9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(407, 292); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(67, 13); this.label9.TabIndex = 125; this.label9.Text = "Picture Type"; // // txtArtist // this.txtArtist.Location = new System.Drawing.Point(98, 62); this.txtArtist.Name = "txtArtist"; this.txtArtist.Size = new System.Drawing.Size(300, 20); this.txtArtist.TabIndex = 104; // // txtTitle // this.txtTitle.Location = new System.Drawing.Point(98, 88); this.txtTitle.Name = "txtTitle"; this.txtTitle.Size = new System.Drawing.Size(300, 20); this.txtTitle.TabIndex = 105; // // txtImageDescription // this.txtImageDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtImageDescription.Enabled = false; this.txtImageDescription.Location = new System.Drawing.Point(484, 316); this.txtImageDescription.Name = "txtImageDescription"; this.txtImageDescription.Size = new System.Drawing.Size(210, 20); this.txtImageDescription.TabIndex = 117; this.txtImageDescription.Validated += new System.EventHandler(this.txtImageDescription_Validated); // // txtAlbum // this.txtAlbum.Location = new System.Drawing.Point(98, 114); this.txtAlbum.Name = "txtAlbum"; this.txtAlbum.Size = new System.Drawing.Size(300, 20); this.txtAlbum.TabIndex = 107; // // pictureBox1 // this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pictureBox1.ContextMenuStrip = this.imageContextMenu; this.pictureBox1.Location = new System.Drawing.Point(410, 9); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(284, 274); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pictureBox1.TabIndex = 123; this.pictureBox1.TabStop = false; // // imageContextMenu // this.imageContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miLoadImage, this.miSaveImage}); this.imageContextMenu.Name = "contextMenuStrip1"; this.imageContextMenu.Size = new System.Drawing.Size(101, 48); this.imageContextMenu.Opening += new System.ComponentModel.CancelEventHandler(this.imageContextMenu_Opening); // // miLoadImage // this.miLoadImage.Image = global::IdSharp.Tagging.Harness.WinForms.Properties.Resources.open_image16_h; this.miLoadImage.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.miLoadImage.Name = "miLoadImage"; this.miLoadImage.Size = new System.Drawing.Size(100, 22); this.miLoadImage.Text = "Load"; this.miLoadImage.Click += new System.EventHandler(this.miLoadImage_Click); // // miSaveImage // this.miSaveImage.Image = global::IdSharp.Tagging.Harness.WinForms.Properties.Resources.save16_h; this.miSaveImage.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.miSaveImage.Name = "miSaveImage"; this.miSaveImage.Size = new System.Drawing.Size(100, 22); this.miSaveImage.Text = "Save"; this.miSaveImage.Click += new System.EventHandler(this.miSaveImage_Click); // // txtYear // this.txtYear.Location = new System.Drawing.Point(98, 166); this.txtYear.Name = "txtYear"; this.txtYear.Size = new System.Drawing.Size(75, 20); this.txtYear.TabIndex = 114; // // cmbImageType // this.cmbImageType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cmbImageType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbImageType.Enabled = false; this.cmbImageType.FormattingEnabled = true; this.cmbImageType.Location = new System.Drawing.Point(484, 289); this.cmbImageType.Name = "cmbImageType"; this.cmbImageType.Size = new System.Drawing.Size(210, 21); this.cmbImageType.TabIndex = 116; this.cmbImageType.SelectedIndexChanged += new System.EventHandler(this.cmbImageType_SelectedIndexChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(10, 91); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(27, 13); this.label2.TabIndex = 108; this.label2.Text = "Title"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(10, 117); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(36, 13); this.label3.TabIndex = 109; this.label3.Text = "Album"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(10, 195); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(35, 13); this.label8.TabIndex = 122; this.label8.Text = "Track"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(10, 143); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(36, 13); this.label4.TabIndex = 110; this.label4.Text = "Genre"; // // txtTrackNumber // this.txtTrackNumber.Location = new System.Drawing.Point(98, 192); this.txtTrackNumber.Name = "txtTrackNumber"; this.txtTrackNumber.Size = new System.Drawing.Size(75, 20); this.txtTrackNumber.TabIndex = 115; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(10, 169); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(29, 13); this.label5.TabIndex = 112; this.label5.Text = "Year"; // // cmbID3v2 // this.cmbID3v2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbID3v2.FormattingEnabled = true; this.cmbID3v2.Items.AddRange(new object[] { "ID3v2.2", "ID3v2.3", "ID3v2.4"}); this.cmbID3v2.Location = new System.Drawing.Point(98, 35); this.cmbID3v2.Name = "cmbID3v2"; this.cmbID3v2.Size = new System.Drawing.Size(75, 21); this.cmbID3v2.TabIndex = 103; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(10, 12); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(52, 13); this.label6.TabIndex = 113; this.label6.Text = "File name"; // // lblID3v2 // this.lblID3v2.AutoSize = true; this.lblID3v2.Location = new System.Drawing.Point(10, 38); this.lblID3v2.Name = "lblID3v2"; this.lblID3v2.Size = new System.Drawing.Size(36, 13); this.lblID3v2.TabIndex = 121; this.lblID3v2.Text = "ID3v2"; // // cmbGenre // this.cmbGenre.FormattingEnabled = true; this.cmbGenre.Location = new System.Drawing.Point(98, 140); this.cmbGenre.Name = "cmbGenre"; this.cmbGenre.Size = new System.Drawing.Size(146, 21); this.cmbGenre.TabIndex = 111; // // imageOpenFileDialog // this.imageOpenFileDialog.Filter = "*.jpg, *.jpeg, *.png|*.jpg;*.jpeg;*.png"; // // txtPlayLength // this.txtPlayLength.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.txtPlayLength.Location = new System.Drawing.Point(98, 289); this.txtPlayLength.Name = "txtPlayLength"; this.txtPlayLength.ReadOnly = true; this.txtPlayLength.Size = new System.Drawing.Size(146, 20); this.txtPlayLength.TabIndex = 127; this.txtPlayLength.TabStop = false; // // label7 // this.label7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(10, 292); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(59, 13); this.label7.TabIndex = 128; this.label7.Text = "Play length"; // // txtBitrate // this.txtBitrate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.txtBitrate.Location = new System.Drawing.Point(98, 315); this.txtBitrate.Name = "txtBitrate"; this.txtBitrate.ReadOnly = true; this.txtBitrate.Size = new System.Drawing.Size(146, 20); this.txtBitrate.TabIndex = 129; this.txtBitrate.TabStop = false; // // label11 // this.label11.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(10, 318); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(37, 13); this.label11.TabIndex = 130; this.label11.Text = "Bitrate"; // // txtEncoderPreset // this.txtEncoderPreset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.txtEncoderPreset.Location = new System.Drawing.Point(98, 341); this.txtEncoderPreset.Name = "txtEncoderPreset"; this.txtEncoderPreset.ReadOnly = true; this.txtEncoderPreset.Size = new System.Drawing.Size(300, 20); this.txtEncoderPreset.TabIndex = 131; this.txtEncoderPreset.TabStop = false; // // label12 // this.label12.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(10, 344); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(82, 13); this.label12.TabIndex = 132; this.label12.Text = "Encoder/Preset"; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(10, 219); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(46, 13); this.label13.TabIndex = 122; this.label13.Text = "Podcast"; // // chkPodcast // this.chkPodcast.AutoSize = true; this.chkPodcast.Location = new System.Drawing.Point(98, 219); this.chkPodcast.Name = "chkPodcast"; this.chkPodcast.Size = new System.Drawing.Size(15, 14); this.chkPodcast.TabIndex = 133; this.chkPodcast.UseVisualStyleBackColor = true; // // txtFeedUrl // this.txtPodcastFeedUrl.Location = new System.Drawing.Point(98, 239); this.txtPodcastFeedUrl.Name = "txtFeedUrl"; this.txtPodcastFeedUrl.Size = new System.Drawing.Size(300, 20); this.txtPodcastFeedUrl.TabIndex = 134; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(10, 242); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(56, 13); this.label14.TabIndex = 135; this.label14.Text = "Feed URL"; // // ID3v2UserControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.txtPodcastFeedUrl); this.Controls.Add(this.label14); this.Controls.Add(this.txtEncoderPreset); this.Controls.Add(this.chkPodcast); this.Controls.Add(this.label12); this.Controls.Add(this.txtBitrate); this.Controls.Add(this.label11); this.Controls.Add(this.txtPlayLength); this.Controls.Add(this.label7); this.Controls.Add(this.txtFilename); this.Controls.Add(this.label10); this.Controls.Add(this.imageBindingNavigator); this.Controls.Add(this.label1); this.Controls.Add(this.label9); this.Controls.Add(this.txtImageDescription); this.Controls.Add(this.txtArtist); this.Controls.Add(this.txtTitle); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.txtAlbum); this.Controls.Add(this.cmbImageType); this.Controls.Add(this.txtYear); this.Controls.Add(this.label2); this.Controls.Add(this.label3); this.Controls.Add(this.label8); this.Controls.Add(this.label13); this.Controls.Add(this.label4); this.Controls.Add(this.txtTrackNumber); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.cmbID3v2); this.Controls.Add(this.cmbGenre); this.Controls.Add(this.lblID3v2); this.Name = "ID3v2UserControl"; this.Size = new System.Drawing.Size(704, 375); ((System.ComponentModel.ISupportInitialize)(this.imageBindingNavigator)).EndInit(); this.imageBindingNavigator.ResumeLayout(false); this.imageBindingNavigator.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.imageContextMenu.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtFilename; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label1; private System.Windows.Forms.BindingNavigator imageBindingNavigator; private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem; private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem; private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator; private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox txtArtist; private System.Windows.Forms.TextBox txtTitle; private System.Windows.Forms.TextBox txtImageDescription; private System.Windows.Forms.TextBox txtAlbum; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.TextBox txtYear; private System.Windows.Forms.ComboBox cmbImageType; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtTrackNumber; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cmbID3v2; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label lblID3v2; private System.Windows.Forms.ComboBox cmbGenre; private System.Windows.Forms.OpenFileDialog imageOpenFileDialog; private System.Windows.Forms.SaveFileDialog imageSaveFileDialog; private System.Windows.Forms.ContextMenuStrip imageContextMenu; private System.Windows.Forms.ToolStripMenuItem miLoadImage; private System.Windows.Forms.ToolStripMenuItem miSaveImage; private System.Windows.Forms.TextBox txtPlayLength; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtBitrate; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox txtEncoderPreset; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.CheckBox chkPodcast; private System.Windows.Forms.TextBox txtPodcastFeedUrl; private System.Windows.Forms.Label label14; } }
// *********************************************************************** // Copyright (c) 2012-2014 Charlie Poole, Rob Prouse // // 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. // *********************************************************************** #if PARALLEL using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace NUnit.Framework.Internal.Execution { /// <summary> /// ParallelWorkItemDispatcher handles execution of work items by /// queuing them for worker threads to process. /// </summary> public class ParallelWorkItemDispatcher : IWorkItemDispatcher { private static readonly Logger log = InternalTrace.GetLogger("Dispatcher"); private WorkItem _topLevelWorkItem; #region Constructor /// <summary> /// Construct a ParallelWorkItemDispatcher /// </summary> /// <param name="levelOfParallelism">Number of workers to use</param> public ParallelWorkItemDispatcher(int levelOfParallelism) { // Create Shifts ParallelShift = new WorkShift("Parallel"); NonParallelShift = new WorkShift("NonParallel"); NonParallelSTAShift = new WorkShift("NonParallelSTA"); foreach (var shift in Shifts) shift.EndOfShift += OnEndOfShift; // Assign queues to shifts ParallelShift.AddQueue(ParallelQueue); ParallelShift.AddQueue(ParallelSTAQueue); NonParallelShift.AddQueue(NonParallelQueue); NonParallelSTAShift.AddQueue(NonParallelSTAQueue); // Create workers and assign to shifts and queues // TODO: Avoid creating all the workers till needed for (int i = 1; i <= levelOfParallelism; i++) { string name = string.Format("Worker#" + i.ToString()); ParallelShift.Assign(new TestWorker(ParallelQueue, name)); } ParallelShift.Assign(new TestWorker(ParallelSTAQueue, "Worker#STA")); var worker = new TestWorker(NonParallelQueue, "Worker#STA_NP"); worker.Busy += OnStartNonParallelWorkItem; NonParallelShift.Assign(worker); worker = new TestWorker(NonParallelSTAQueue, "Worker#NP_STA"); worker.Busy += OnStartNonParallelWorkItem; NonParallelSTAShift.Assign(worker); } private void OnStartNonParallelWorkItem(TestWorker worker, WorkItem work) { // This captures the startup of TestFixtures and SetUpFixtures, // but not their teardown items, which are not composite items if (work is CompositeWorkItem && work.Test.TypeInfo != null) IsolateQueues(work); } #endregion #region Properties /// <summary> /// Enumerates all the shifts supported by the dispatcher /// </summary> public IEnumerable<WorkShift> Shifts { get { yield return ParallelShift; yield return NonParallelShift; yield return NonParallelSTAShift; } } /// <summary> /// Enumerates all the Queues supported by the dispatcher /// </summary> public IEnumerable<WorkItemQueue> Queues { get { yield return ParallelQueue; yield return ParallelSTAQueue; yield return NonParallelQueue; yield return NonParallelSTAQueue; } } // WorkShifts - Dispatcher processes tests in three non-overlapping shifts. // See comment in Workshift.cs for a more detailed explanation. private WorkShift ParallelShift { get; } private WorkShift NonParallelShift { get; } private WorkShift NonParallelSTAShift { get; } // WorkItemQueues private WorkItemQueue ParallelQueue { get; } = new WorkItemQueue("ParallelQueue", true, ApartmentState.MTA); private WorkItemQueue ParallelSTAQueue { get; } = new WorkItemQueue("ParallelSTAQueue", true, ApartmentState.STA); private WorkItemQueue NonParallelQueue { get; } = new WorkItemQueue("NonParallelQueue", false, ApartmentState.MTA); private WorkItemQueue NonParallelSTAQueue { get; } = new WorkItemQueue("NonParallelSTAQueue", false, ApartmentState.STA); #endregion #region IWorkItemDispatcher Members /// <summary> /// Start execution, setting the top level work, /// enqueuing it and starting a shift to execute it. /// </summary> public void Start(WorkItem topLevelWorkItem) { _topLevelWorkItem = topLevelWorkItem; var strategy = topLevelWorkItem.ParallelScope.HasFlag(ParallelScope.None) ? ParallelExecutionStrategy.NonParallel : ParallelExecutionStrategy.Parallel; Dispatch(topLevelWorkItem, strategy); StartNextShift(); } /// <summary> /// Dispatch a single work item for execution. The first /// work item dispatched is saved as the top-level /// work item and used when stopping the run. /// </summary> /// <param name="work">The item to dispatch</param> public void Dispatch(WorkItem work) { Dispatch(work, work.ExecutionStrategy); } // Separate method so it can be used by Start private void Dispatch(WorkItem work, ParallelExecutionStrategy strategy) { log.Debug("Using {0} strategy for {1}", strategy, work.Name); switch (strategy) { default: case ParallelExecutionStrategy.Direct: work.Execute(); break; case ParallelExecutionStrategy.Parallel: if (work.TargetApartment == ApartmentState.STA) ParallelSTAQueue.Enqueue(work); else ParallelQueue.Enqueue(work); break; case ParallelExecutionStrategy.NonParallel: if (work.TargetApartment == ApartmentState.STA) NonParallelSTAQueue.Enqueue(work); else NonParallelQueue.Enqueue(work); break; } } /// <summary> /// Cancel the ongoing run completely. /// If no run is in process, the call has no effect. /// </summary> public void CancelRun(bool force) { foreach (var shift in Shifts) shift.Cancel(force); } private object _queueLock = new object(); private int _isolationLevel = 0; /// <summary> /// Save the state of the queues and create a new isolated set /// </summary> internal void IsolateQueues(WorkItem work) { log.Info("Saving Queue State for {0}", work.Name); lock (_queueLock) { foreach (WorkItemQueue queue in Queues) queue.Save(); _isolationLevel++; } } /// <summary> /// Remove isolated queues and restore old ones /// </summary> private void RestoreQueues() { Guard.OperationValid(_isolationLevel > 0, $"Internal Error: Called {nameof(RestoreQueues)} with no saved queues."); Guard.OperationValid(Queues.All(q => q.IsEmpty), $"Internal Error: Called {nameof(RestoreQueues)} with non-empty queues."); // Keep lock until we can remove for both methods lock (_queueLock) { log.Info("Restoring Queue State"); foreach (WorkItemQueue queue in Queues) queue.Restore(); _isolationLevel--; } } #endregion #region Helper Methods private void OnEndOfShift(object sender, EventArgs ea) { // This shift ended, so see if there is work in any other // TODO: Temp fix - revisit later when object model is redesigned. if (StartNextShift()) return; if (_isolationLevel > 0) RestoreQueues(); // Shift has ended but all work may not yet be done while (_topLevelWorkItem.State != WorkItemState.Complete) { // This will fail if there is no work - all queues empty. // In that case, we just continue the loop until either // a shift is started or all the work is complete. if (StartNextShift()) return; } // All work is complete, so shutdown. foreach (var shift in Shifts) shift.ShutDown(); } private bool StartNextShift() { foreach (var shift in Shifts) { if (shift.HasWork) { shift.Start(); return true; } } return false; } #endregion } #region ParallelScopeHelper Class #if NET_2_0 || NET_3_5 static class ParallelScopeHelper { public static bool HasFlag(this ParallelScope scope, ParallelScope value) { return (scope & value) != 0; } } #endif #endregion } #endif
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.VisualStudio.Services.WebApi; using System.Xml; using Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Microsoft.VisualStudio.Services.Agent.Worker.Handlers { [ServiceLocator(Default = typeof(AzurePowerShellHandler))] public interface IAzurePowerShellHandler : IHandler { AzurePowerShellHandlerData Data { get; set; } } [ServiceLocator(Default = typeof(PowerShellHandler))] public interface IPowerShellHandler : IHandler { PowerShellHandlerData Data { get; set; } } public sealed class AzurePowerShellHandler : LegacyPowerShellHandler, IAzurePowerShellHandler { private const string _connectedServiceName = "ConnectedServiceName"; private const string _connectedServiceNameSelector = "ConnectedServiceNameSelector"; public AzurePowerShellHandlerData Data { get; set; } protected override void AddLegacyHostEnvironmentVariables(string scriptFile, string workingDirectory) { // Call the base implementation. base.AddLegacyHostEnvironmentVariables(scriptFile: scriptFile, workingDirectory: workingDirectory); // additionalStatement List<Tuple<String, List<Tuple<String, String>>>> additionalStatement = GetAdditionalCommandsForAzurePowerShell(Inputs); if (additionalStatement.Count > 0) { AddEnvironmentVariable("VSTSPSHOSTSTATEMENTS", JsonUtility.ToString(additionalStatement)); } } protected override string GetArgumentFormat() { ArgUtil.NotNull(Data, nameof(Data)); return Data.ArgumentFormat; } protected override string GetTarget() { ArgUtil.NotNull(Data, nameof(Data)); return Data.Target; } protected override string GetWorkingDirectory() { ArgUtil.NotNull(Data, nameof(Data)); return Data.WorkingDirectory; } private List<Tuple<String, List<Tuple<String, String>>>> GetAdditionalCommandsForAzurePowerShell(Dictionary<string, string> inputs) { List<Tuple<String, List<Tuple<String, String>>>> additionalCommands = new List<Tuple<string, List<Tuple<string, string>>>>(); string connectedServiceNameValue = GetConnectedService(inputs); // It's OK for StorageAccount to not exist (it won't for RunAzurePowerShell or AzureWebPowerShellDeployment) // If it is empty for AzureCloudPowerShellDeployment (the UI is set up to require it), the deployment script will // fail with a message as to the problem. string storageAccountParameter; string storageAccount = string.Empty; if (inputs.TryGetValue("StorageAccount", out storageAccountParameter)) { storageAccount = storageAccountParameter; } // Initialize our Azure Support (imports the module, sets up the Azure subscription) string path = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "vstshost"); string azurePSM1 = Path.Combine(path, "Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Azure\\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Azure.psm1"); Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - AddCommand(Import-Module)"); Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - AddParameter(Name={0})", azurePSM1); Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - AddParameter(Scope=Global)"); additionalCommands.Add(new Tuple<string, List<Tuple<string, string>>>("Import-Module", new List<Tuple<string, string>>() { new Tuple<string, string>("Name", azurePSM1), new Tuple<string, string>("Scope", "Global"), })); Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - AddCommand(Initialize-AzurePowerShellSupport)"); Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - AddParameter({0}={1})", _connectedServiceName, connectedServiceNameValue); Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - AddParameter(StorageAccount={0})", storageAccount); additionalCommands.Add(new Tuple<string, List<Tuple<string, string>>>("Initialize-AzurePowerShellSupport", new List<Tuple<string, string>>() { new Tuple<string, string>(_connectedServiceName, connectedServiceNameValue), new Tuple<string, string>("StorageAccount", storageAccount), })); return additionalCommands; } private string GetConnectedService(Dictionary<string, string> inputs) { string environment, connectedServiceSelectorValue; string connectedServiceName = _connectedServiceName; if (inputs.TryGetValue(_connectedServiceNameSelector, out connectedServiceSelectorValue)) { connectedServiceName = connectedServiceSelectorValue; Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - Found ConnectedServiceSelector value : {0}", connectedServiceName); } if (!inputs.TryGetValue(connectedServiceName, out environment)) { Trace.Verbose("AzurePowerShellHandler.UpdatePowerShellEnvironment - Could not find {0}, so looking for DeploymentEnvironmentName.", connectedServiceName); if (!inputs.TryGetValue("DeploymentEnvironmentName", out environment)) { throw new ArgumentNullException($"The required {connectedServiceName} parameter was not found by the AzurePowerShellRunner."); } } string connectedServiceNameValue = environment; if (String.IsNullOrEmpty(connectedServiceNameValue)) { throw new ArgumentNullException($"The required {connectedServiceName} parameter was either null or empty. Ensure you have provisioned a Deployment Environment using services tab in Admin UI."); } return connectedServiceNameValue; } } public sealed class PowerShellHandler : LegacyPowerShellHandler, IPowerShellHandler { public PowerShellHandlerData Data { get; set; } protected override string GetArgumentFormat() { ArgUtil.NotNull(Data, nameof(Data)); return Data.ArgumentFormat; } protected override string GetTarget() { ArgUtil.NotNull(Data, nameof(Data)); return Data.Target; } protected override string GetWorkingDirectory() { ArgUtil.NotNull(Data, nameof(Data)); return Data.WorkingDirectory; } } public abstract class LegacyPowerShellHandler : Handler { private Regex _argumentMatching = new Regex("([^\" ]*(\"[^\"]*\")[^\" ]*)|[^\" ]+", RegexOptions.Compiled); private string _appConfigFileName = "LegacyVSTSPowerShellHost.exe.config"; private string _appConfigRestoreFileName = "LegacyVSTSPowerShellHost.exe.config.restore"; protected abstract string GetArgumentFormat(); protected abstract string GetTarget(); protected abstract string GetWorkingDirectory(); public async Task RunAsync() { // Validate args. Trace.Entering(); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); ArgUtil.NotNull(Inputs, nameof(Inputs)); ArgUtil.Directory(TaskDirectory, nameof(TaskDirectory)); // Warn about legacy handler. ExecutionContext.Warning($"Task '{this.Task.Name}' ({this.Task.Version}) is using deprecated task execution handler. The task should use the supported task-lib: https://aka.ms/tasklib"); // Resolve the target script. string target = GetTarget(); ArgUtil.NotNullOrEmpty(target, nameof(target)); string scriptFile = Path.Combine(TaskDirectory, target); ArgUtil.File(scriptFile, nameof(scriptFile)); // Determine the working directory. string workingDirectory = GetWorkingDirectory(); if (String.IsNullOrEmpty(workingDirectory)) { workingDirectory = Path.GetDirectoryName(scriptFile); } else { if (!Directory.Exists(workingDirectory)) { Directory.CreateDirectory(workingDirectory); } } // Copy the OM binaries into the legacy host folder. ExecutionContext.Output(StringUtil.Loc("PrepareTaskExecutionHandler")); IOUtil.CopyDirectory( source: HostContext.GetDirectory(WellKnownDirectory.ServerOM), target: HostContext.GetDirectory(WellKnownDirectory.LegacyPSHost), cancellationToken: ExecutionContext.CancellationToken); Trace.Info("Finished copying files."); // Add the legacy ps host environment variables. AddLegacyHostEnvironmentVariables(scriptFile: scriptFile, workingDirectory: workingDirectory); AddPrependPathToEnvironment(); // Add proxy setting to LegacyVSTSPowerShellHost.exe.config var agentProxy = HostContext.GetService<IVstsAgentWebProxy>(); if (!string.IsNullOrEmpty(agentProxy.ProxyAddress)) { AddProxySetting(agentProxy); } // Invoke the process. using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += OnDataReceived; processInvoker.ErrorDataReceived += OnDataReceived; try { String vstsPSHostExe = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.LegacyPSHost), "LegacyVSTSPowerShellHost.exe"); Int32 exitCode = await processInvoker.ExecuteAsync(workingDirectory: workingDirectory, fileName: vstsPSHostExe, arguments: "", environment: Environment, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, redirectStandardIn: null, inheritConsoleHandler: !ExecutionContext.Variables.Retain_Default_Encoding, cancellationToken: ExecutionContext.CancellationToken); // the exit code from vstsPSHost.exe indicate how many error record we get during execution // -1 exit code means infrastructure failure of Host itself. // this is to match current handler's logic. if (exitCode > 0) { if (ExecutionContext.Result != null) { ExecutionContext.Debug($"Task result already set. Not failing due to error count ({exitCode})."); } else { // We fail task and add issue. ExecutionContext.Result = TaskResult.Failed; ExecutionContext.Error(StringUtil.Loc("PSScriptError", exitCode)); } } else if (exitCode < 0) { // We fail task and add issue. ExecutionContext.Result = TaskResult.Failed; ExecutionContext.Error(StringUtil.Loc("VSTSHostNonZeroReturn", exitCode)); } } finally { processInvoker.OutputDataReceived -= OnDataReceived; processInvoker.ErrorDataReceived -= OnDataReceived; } } } protected virtual void AddLegacyHostEnvironmentVariables(string scriptFile, string workingDirectory) { // scriptName AddEnvironmentVariable("VSTSPSHOSTSCRIPTNAME", scriptFile); // workingFolder AddEnvironmentVariable("VSTSPSHOSTWORKINGFOLDER", workingDirectory); // outputPreference AddEnvironmentVariable("VSTSPSHOSTOUTPUTPREFER", ExecutionContext.WriteDebug ? "Continue" : "SilentlyContinue"); // inputParameters if (Inputs.Count > 0) { AddEnvironmentVariable("VSTSPSHOSTINPUTPARAMETER", JsonUtility.ToString(Inputs)); } List<String> arguments = new List<string>(); Dictionary<String, String> argumentParameters = new Dictionary<String, String>(); string argumentFormat = GetArgumentFormat(); if (string.IsNullOrEmpty(argumentFormat)) { // treatInputsAsArguments AddEnvironmentVariable("VSTSPSHOSTINPUTISARG", "True"); } else { MatchCollection matches = _argumentMatching.Matches(argumentFormat); if (matches[0].Value.StartsWith("-")) { String currentKey = String.Empty; foreach (Match match in matches) { if (match.Value.StartsWith("-")) { currentKey = match.Value.Trim('-'); argumentParameters.Add(currentKey, String.Empty); } else if (!match.Value.StartsWith("-") && !String.IsNullOrEmpty(currentKey)) { argumentParameters[currentKey] = match.Value; currentKey = String.Empty; } else { throw new ArgumentException($"Found value {match.Value} with no corresponding named parameter"); } } } else { foreach (Match match in matches) { arguments.Add(match.Value); } } // arguments if (arguments.Count > 0) { AddEnvironmentVariable("VSTSPSHOSTARGS", JsonUtility.ToString(arguments)); } // argumentParameters if (argumentParameters.Count > 0) { AddEnvironmentVariable("VSTSPSHOSTARGPARAMETER", JsonUtility.ToString(argumentParameters)); } } // push all variable. foreach (var variable in ExecutionContext.Variables.Public.Concat(ExecutionContext.Variables.Private)) { AddEnvironmentVariable("VSTSPSHOSTVAR_" + variable.Key, variable.Value); } // push all public variable. foreach (var variable in ExecutionContext.Variables.Public) { AddEnvironmentVariable("VSTSPSHOSTPUBVAR_" + variable.Key, variable.Value); } // push all endpoints List<String> ids = new List<string>(); foreach (ServiceEndpoint endpoint in ExecutionContext.Endpoints) { string partialKey = null; if (string.Equals(endpoint.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase)) { partialKey = WellKnownServiceEndpointNames.SystemVssConnection.ToUpperInvariant(); AddEnvironmentVariable("VSTSPSHOSTSYSTEMENDPOINT_URL", endpoint.Url.ToString()); AddEnvironmentVariable("VSTSPSHOSTSYSTEMENDPOINT_AUTH", JsonUtility.ToString(endpoint.Authorization)); } else { if (endpoint.Id == Guid.Empty && endpoint.Data.ContainsKey("repositoryId")) { partialKey = endpoint.Data["repositoryId"].ToUpperInvariant(); } else { partialKey = endpoint.Id.ToString("D").ToUpperInvariant(); } ids.Add(partialKey); AddEnvironmentVariable("VSTSPSHOSTENDPOINT_URL_" + partialKey, endpoint.Url.ToString()); // We fixed endpoint.name to be the name of the endpoint in yaml, before endpoint.name=endpoint.id is a guid // However, for source endpoint, the endpoint.id is Guid.Empty and endpoint.name is already the name of the endpoint // The legacy PSHost use the Guid to retrive endpoint, the legacy PSHost assume `VSTSPSHOSTENDPOINT_NAME_` is the Guid. if (endpoint.Id == Guid.Empty && endpoint.Data.ContainsKey("repositoryId")) { AddEnvironmentVariable("VSTSPSHOSTENDPOINT_NAME_" + partialKey, endpoint.Name); } else { AddEnvironmentVariable("VSTSPSHOSTENDPOINT_NAME_" + partialKey, endpoint.Id.ToString()); } AddEnvironmentVariable("VSTSPSHOSTENDPOINT_TYPE_" + partialKey, endpoint.Type); AddEnvironmentVariable("VSTSPSHOSTENDPOINT_AUTH_" + partialKey, JsonUtility.ToString(endpoint.Authorization)); AddEnvironmentVariable("VSTSPSHOSTENDPOINT_DATA_" + partialKey, JsonUtility.ToString(endpoint.Data)); } } var defaultRepoName = ExecutionContext.Variables.Get(Constants.Variables.Build.RepoName); var defaultRepoType = ExecutionContext.Variables.Get(Constants.Variables.Build.RepoProvider); if (!string.IsNullOrEmpty(defaultRepoName)) { // TODO: use alias to find the trigger repo when we have the concept of triggering repo. var defaultRepo = ExecutionContext.Repositories.FirstOrDefault(x => String.Equals(x.Properties.Get<string>(RepositoryPropertyNames.Name), defaultRepoName, StringComparison.OrdinalIgnoreCase)); if (defaultRepo != null && !ids.Exists(x => string.Equals(x, defaultRepo.Id, StringComparison.OrdinalIgnoreCase))) { ids.Add(defaultRepo.Id); AddEnvironmentVariable("VSTSPSHOSTENDPOINT_URL_" + defaultRepo.Id, defaultRepo.Url.ToString()); AddEnvironmentVariable("VSTSPSHOSTENDPOINT_NAME_" + defaultRepo.Id, defaultRepoName); AddEnvironmentVariable("VSTSPSHOSTENDPOINT_TYPE_" + defaultRepo.Id, defaultRepoType); if (defaultRepo.Endpoint != null) { var endpoint = ExecutionContext.Endpoints.FirstOrDefault(x => x.Id == defaultRepo.Endpoint.Id); if (endpoint != null) { AddEnvironmentVariable("VSTSPSHOSTENDPOINT_AUTH_" + defaultRepo.Id, JsonUtility.ToString(endpoint.Authorization)); AddEnvironmentVariable("VSTSPSHOSTENDPOINT_DATA_" + defaultRepo.Id, JsonUtility.ToString(endpoint.Data)); } } } } if (ids.Count > 0) { AddEnvironmentVariable("VSTSPSHOSTENDPOINT_IDS", JsonUtility.ToString(ids)); } } private void AddProxySetting(IVstsAgentWebProxy agentProxy) { string appConfig = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.LegacyPSHost), _appConfigFileName); ArgUtil.File(appConfig, _appConfigFileName); string appConfigRestore = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.LegacyPSHost), _appConfigRestoreFileName); if (!File.Exists(appConfigRestore)) { Trace.Info("Take snapshot of current appconfig for restore modified appconfig."); File.Copy(appConfig, appConfigRestore); } else { // cleanup any appconfig changes from previous build. ExecutionContext.Debug("Restore default LegacyVSTSPowerShellHost.exe.config."); IOUtil.DeleteFile(appConfig); File.Copy(appConfigRestore, appConfig); } XmlDocument psHostAppConfig = new XmlDocument(); using (var appConfigStream = new FileStream(appConfig, FileMode.Open, FileAccess.Read)) { psHostAppConfig.Load(appConfigStream); } var configuration = psHostAppConfig.SelectSingleNode("configuration"); ArgUtil.NotNull(configuration, "configuration"); var exist_defaultProxy = psHostAppConfig.SelectSingleNode("configuration/system.net/defaultProxy"); if (exist_defaultProxy == null) { var system_net = psHostAppConfig.SelectSingleNode("configuration/system.net"); if (system_net == null) { Trace.Verbose("Create system.net section in appconfg."); system_net = psHostAppConfig.CreateElement("system.net"); } Trace.Verbose("Create defaultProxy section in appconfg."); var defaultProxy = psHostAppConfig.CreateElement("defaultProxy"); defaultProxy.SetAttribute("useDefaultCredentials", "true"); Trace.Verbose("Create proxy section in appconfg."); var proxy = psHostAppConfig.CreateElement("proxy"); proxy.SetAttribute("proxyaddress", agentProxy.ProxyAddress); proxy.SetAttribute("bypassonlocal", "true"); if (agentProxy.ProxyBypassList != null && agentProxy.ProxyBypassList.Count > 0) { Trace.Verbose("Create bypasslist section in appconfg."); var bypass = psHostAppConfig.CreateElement("bypasslist"); foreach (string proxyBypass in agentProxy.ProxyBypassList) { Trace.Verbose($"Create bypasslist.add section for {proxyBypass} in appconfg."); var add = psHostAppConfig.CreateElement("add"); add.SetAttribute("address", proxyBypass); bypass.AppendChild(add); } defaultProxy.AppendChild(bypass); } defaultProxy.AppendChild(proxy); system_net.AppendChild(defaultProxy); configuration.AppendChild(system_net); using (var appConfigStream = new FileStream(appConfig, FileMode.Open, FileAccess.ReadWrite)) { psHostAppConfig.Save(appConfigStream); } ExecutionContext.Debug("Add Proxy setting in LegacyVSTSPowerShellHost.exe.config file."); } else { //proxy setting exist. ExecutionContext.Debug("Proxy setting already exist in LegacyVSTSPowerShellHost.exe.config file."); } } private void OnDataReceived(object sender, ProcessDataReceivedEventArgs e) { // This does not need to be inside of a critical section. // The logging queues and command handlers are thread-safe. if (!CommandManager.TryProcessCommand(ExecutionContext, e.Data)) { ExecutionContext.Output(e.Data); } } } }
// <copyright file="Combinatorics.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2015 Math.NET // // 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. // </copyright> using System; using System.Collections.Generic; using System.Linq; using MathNet.Numerics.Properties; using MathNet.Numerics.Random; namespace MathNet.Numerics { /// <summary> /// Enumerative Combinatorics and Counting. /// </summary> public static class Combinatorics { /// <summary> /// Count the number of possible variations without repetition. /// The order matters and each object can be chosen only once. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param> /// <returns>Maximum number of distinct variations.</returns> public static double Variations(int n, int k) { if (k < 0 || n < 0 || k > n) { return 0; } return Math.Floor( 0.5 + Math.Exp( SpecialFunctions.FactorialLn(n) - SpecialFunctions.FactorialLn(n - k))); } /// <summary> /// Count the number of possible variations with repetition. /// The order matters and each object can be chosen more than once. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Each element is chosen 0, 1 or multiple times.</param> /// <returns>Maximum number of distinct variations with repetition.</returns> public static double VariationsWithRepetition(int n, int k) { if (k < 0 || n < 0) { return 0; } return Math.Pow(n, k); } /// <summary> /// Count the number of possible combinations without repetition. /// The order does not matter and each object can be chosen only once. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param> /// <returns>Maximum number of combinations.</returns> public static double Combinations(int n, int k) { return SpecialFunctions.Binomial(n, k); } /// <summary> /// Count the number of possible combinations with repetition. /// The order does not matter and an object can be chosen more than once. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Each element is chosen 0, 1 or multiple times.</param> /// <returns>Maximum number of combinations with repetition.</returns> public static double CombinationsWithRepetition(int n, int k) { if (k < 0 || n < 0 || (n == 0 && k > 0)) { return 0; } if (n == 0 && k == 0) { return 1; } return Math.Floor( 0.5 + Math.Exp( SpecialFunctions.FactorialLn(n + k - 1) - SpecialFunctions.FactorialLn(k) - SpecialFunctions.FactorialLn(n - 1))); } /// <summary> /// Count the number of possible permutations (without repetition). /// </summary> /// <param name="n">Number of (distinguishable) elements in the set.</param> /// <returns>Maximum number of permutations without repetition.</returns> public static double Permutations(int n) { return SpecialFunctions.Factorial(n); } /// <summary> /// Generate a random permutation, without repetition, by generating the index numbers 0 to N-1 and shuffle them randomly. /// Implemented using Fisher-Yates Shuffling. /// </summary> /// <returns>An array of length <c>N</c> that contains (in any order) the integers of the interval <c>[0, N)</c>.</returns> /// <param name="n">Number of (distinguishable) elements in the set.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> public static int[] GeneratePermutation(int n, System.Random randomSource = null) { if (n < 0) throw new ArgumentOutOfRangeException("n", Resources.ArgumentNotNegative); int[] indices = new int[n]; for (int i = 0; i < indices.Length; i++) { indices[i] = i; } SelectPermutationInplace(indices, randomSource); return indices; } /// <summary> /// Select a random permutation, without repetition, from a data array by reordering the provided array in-place. /// Implemented using Fisher-Yates Shuffling. The provided data array will be modified. /// </summary> /// <param name="data">The data array to be reordered. The array will be modified by this routine.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> public static void SelectPermutationInplace<T>(T[] data, System.Random randomSource = null) { var random = randomSource ?? SystemRandomSource.Default; // Fisher-Yates Shuffling for (int i = data.Length - 1; i > 0; i--) { int swapIndex = random.Next(i + 1); T swap = data[i]; data[i] = data[swapIndex]; data[swapIndex] = swap; } } /// <summary> /// Select a random permutation from a data sequence by returning the provided data in random order. /// Implemented using Fisher-Yates Shuffling. /// </summary> /// <param name="data">The data elements to be reordered.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> public static IEnumerable<T> SelectPermutation<T>(this IEnumerable<T> data, System.Random randomSource = null) { var random = randomSource ?? SystemRandomSource.Default; T[] array = data.ToArray(); // Fisher-Yates Shuffling for (int i = array.Length - 1; i >= 0; i--) { int k = random.Next(i + 1); yield return array[k]; array[k] = array[i]; } } /// <summary> /// Generate a random combination, without repetition, by randomly selecting some of N elements. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>Boolean mask array of length <c>N</c>, for each item true if it is selected.</returns> public static bool[] GenerateCombination(int n, System.Random randomSource = null) { if (n < 0) throw new ArgumentOutOfRangeException("n", Resources.ArgumentNotNegative); var random = randomSource ?? SystemRandomSource.Default; bool[] mask = new bool[n]; for (int i = 0; i < mask.Length; i++) { mask[i] = random.NextBoolean(); } return mask; } /// <summary> /// Generate a random combination, without repetition, by randomly selecting k of N elements. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>Boolean mask array of length <c>N</c>, for each item true if it is selected.</returns> public static bool[] GenerateCombination(int n, int k, System.Random randomSource = null) { if (n < 0) throw new ArgumentOutOfRangeException("n", Resources.ArgumentNotNegative); if (k < 0) throw new ArgumentOutOfRangeException("k", Resources.ArgumentNotNegative); if (k > n) throw new ArgumentOutOfRangeException("k", string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "k", "n")); var random = randomSource ?? SystemRandomSource.Default; bool[] mask = new bool[n]; if (k*3 < n) { // just pick and try int selectionCount = 0; while (selectionCount < k) { int index = random.Next(n); if (!mask[index]) { mask[index] = true; selectionCount++; } } return mask; } // based on permutation int[] permutation = GeneratePermutation(n, random); for (int i = 0; i < k; i++) { mask[permutation[i]] = true; } return mask; } /// <summary> /// Select a random combination, without repetition, from a data sequence by selecting k elements in original order. /// </summary> /// <param name="data">The data source to choose from.</param> /// <param name="elementsToChoose">Number of elements (k) to choose from the data set. Each element is chosen at most once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>The chosen combination, in the original order.</returns> public static IEnumerable<T> SelectCombination<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null) { T[] array = data as T[] ?? data.ToArray(); if (elementsToChoose < 0) throw new ArgumentOutOfRangeException("elementsToChoose", Resources.ArgumentNotNegative); if (elementsToChoose > array.Length) throw new ArgumentOutOfRangeException("elementsToChoose", string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "elementsToChoose", "data.Count")); bool[] mask = GenerateCombination(array.Length, elementsToChoose, randomSource); for (int i = 0; i < mask.Length; i++) { if (mask[i]) { yield return array[i]; } } } /// <summary> /// Generates a random combination, with repetition, by randomly selecting k of N elements. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Elements can be chosen more than once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>Integer mask array of length <c>N</c>, for each item the number of times it was selected.</returns> public static int[] GenerateCombinationWithRepetition(int n, int k, System.Random randomSource = null) { if (n < 0) throw new ArgumentOutOfRangeException("n", Resources.ArgumentNotNegative); if (k < 0) throw new ArgumentOutOfRangeException("k", Resources.ArgumentNotNegative); var random = randomSource ?? SystemRandomSource.Default; int[] mask = new int[n]; for (int i = 0; i < k; i++) { mask[random.Next(n)]++; } return mask; } /// <summary> /// Select a random combination, with repetition, from a data sequence by selecting k elements in original order. /// </summary> /// <param name="data">The data source to choose from.</param> /// <param name="elementsToChoose">Number of elements (k) to choose from the data set. Elements can be chosen more than once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>The chosen combination with repetition, in the original order.</returns> public static IEnumerable<T> SelectCombinationWithRepetition<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null) { if (elementsToChoose < 0) throw new ArgumentOutOfRangeException("elementsToChoose", Resources.ArgumentNotNegative); T[] array = data as T[] ?? data.ToArray(); int[] mask = GenerateCombinationWithRepetition(array.Length, elementsToChoose, randomSource); for (int i = 0; i < mask.Length; i++) { for (int j = 0; j < mask[i]; j++) { yield return array[i]; } } } /// <summary> /// Generate a random variation, without repetition, by randomly selecting k of n elements with order. /// Implemented using partial Fisher-Yates Shuffling. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>An array of length <c>K</c> that contains the indices of the selections as integers of the interval <c>[0, N)</c>.</returns> public static int[] GenerateVariation(int n, int k, System.Random randomSource = null) { if (n < 0) throw new ArgumentOutOfRangeException("n", Resources.ArgumentNotNegative); if (k < 0) throw new ArgumentOutOfRangeException("k", Resources.ArgumentNotNegative); if (k > n) throw new ArgumentOutOfRangeException("k", string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "k", "n")); var random = randomSource ?? SystemRandomSource.Default; int[] indices = new int[n]; for (int i = 0; i < indices.Length; i++) { indices[i] = i; } // Partial Fisher-Yates Shuffling int[] selection = new int[k]; for (int i = 0, j = indices.Length - 1; i < selection.Length; i++, j--) { int swapIndex = random.Next(j + 1); selection[i] = indices[swapIndex]; indices[swapIndex] = indices[j]; } return selection; } /// <summary> /// Select a random variation, without repetition, from a data sequence by randomly selecting k elements in random order. /// Implemented using partial Fisher-Yates Shuffling. /// </summary> /// <param name="data">The data source to choose from.</param> /// <param name="elementsToChoose">Number of elements (k) to choose from the set. Each element is chosen at most once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>The chosen variation, in random order.</returns> public static IEnumerable<T> SelectVariation<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null) { var random = randomSource ?? SystemRandomSource.Default; T[] array = data.ToArray(); if (elementsToChoose < 0) throw new ArgumentOutOfRangeException("elementsToChoose", Resources.ArgumentNotNegative); if (elementsToChoose > array.Length) throw new ArgumentOutOfRangeException("elementsToChoose", string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "elementsToChoose", "data.Count")); // Partial Fisher-Yates Shuffling for (int i = array.Length - 1; i >= array.Length - elementsToChoose; i--) { int swapIndex = random.Next(i + 1); yield return array[swapIndex]; array[swapIndex] = array[i]; } } /// <summary> /// Generate a random variation, with repetition, by randomly selecting k of n elements with order. /// </summary> /// <param name="n">Number of elements in the set.</param> /// <param name="k">Number of elements to choose from the set. Elements can be chosen more than once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>An array of length <c>K</c> that contains the indices of the selections as integers of the interval <c>[0, N)</c>.</returns> public static int[] GenerateVariationWithRepetition(int n, int k, System.Random randomSource = null) { if (n < 0) throw new ArgumentOutOfRangeException("n", Resources.ArgumentNotNegative); if (k < 0) throw new ArgumentOutOfRangeException("k", Resources.ArgumentNotNegative); var random = randomSource ?? SystemRandomSource.Default; int[] ret = new int[k]; random.NextInt32s(ret, 0, n); return ret; } /// <summary> /// Select a random variation, with repetition, from a data sequence by randomly selecting k elements in random order. /// </summary> /// <param name="data">The data source to choose from.</param> /// <param name="elementsToChoose">Number of elements (k) to choose from the data set. Elements can be chosen more than once.</param> /// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param> /// <returns>The chosen variation with repetition, in random order.</returns> public static IEnumerable<T> SelectVariationWithRepetition<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null) { if (elementsToChoose < 0) throw new ArgumentOutOfRangeException("elementsToChoose", Resources.ArgumentNotNegative); T[] array = data as T[] ?? data.ToArray(); int[] indices = GenerateVariationWithRepetition(array.Length, elementsToChoose, randomSource); for (int i = 0; i < indices.Length; i++) { yield return array[indices[i]]; } } } }
using System.Collections.Generic; using System.Compiler; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Microsoft.Zing { // Code added by Jiri Adamek to support native ZOM classes public class NativeZOM : Class { public NativeZOM() : base() { } } // END of added code [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum ZingNodeType { Range = 5000, Chan, Set, Array, Choose, // used as the NodeType in UnaryExpression In, // used as the NodeType in BinaryExpression (for set membership) Accept, Assert, Atomic, Async, Assume, AttributedStatement, Event, Send, Self, Select, JoinStatement, WaitPattern, ReceivePattern, TimeoutPattern, EventPattern, InvokePlugin, InvokeSched, Trace, Try, With, Yield, BasicBlock, } /* * New types */ [SuppressMessage("Microsoft.Maintainability", "CA1501:AvoidExcessiveInheritance")] public class Range : ConstrainedType { private Expression min; public Expression Min { get { return this.min; } set { this.min = value; } } private Expression max; public Expression Max { get { return this.max; } set { this.max = value; } } public Range() : base(SystemTypes.Int32, null) { this.NodeType = (NodeType)ZingNodeType.Range; this.Flags = TypeFlags.Public | TypeFlags.Sealed; } public Range(Expression min, Expression max) : base(SystemTypes.Int32, null) { this.NodeType = (NodeType)ZingNodeType.Range; this.Flags = TypeFlags.Public | TypeFlags.Sealed; this.Min = min; this.Max = max; } public override bool IsPrimitiveComparable { get { return true; } } } [SuppressMessage("Microsoft.Maintainability", "CA1501:AvoidExcessiveInheritance")] public class Chan : TypeAlias { public Chan() { this.NodeType = (NodeType)ZingNodeType.Chan; } public Chan(TypeNode channelType) : this() { this.ChannelType = channelType; } public TypeNode ChannelType { // We use aliasedType here rather than AliasedType because the getter // for AliasedType has some logic that we don't want for the case // where aliasedType is null. get { return this.aliasedType; } set { this.aliasedType = value; } } public override bool IsPrimitiveComparable { get { return true; } } } [SuppressMessage("Microsoft.Maintainability", "CA1501:AvoidExcessiveInheritance")] public class Set : TypeAlias { public Set() { this.NodeType = (NodeType)ZingNodeType.Set; } public Set(TypeNode setType) : this() { this.SetType = setType; } public TypeNode SetType { // We use aliasedType here rather than AliasedType because the getter // for AliasedType has some logic that we don't want for the case // where aliasedType is null. get { return this.aliasedType; } set { this.aliasedType = value; } } public override bool IsPrimitiveComparable { get { return true; } } } [SuppressMessage("Microsoft.Maintainability", "CA1501:AvoidExcessiveInheritance")] public class ZArray : ArrayTypeExpression { internal TypeNode domainType; // if size is given as a type public TypeNode DomainType { get { return this.domainType; } set { this.domainType = value; } } public bool IsDynamic { get { return this.Sizes == null; } } public ZArray() { this.NodeType = (NodeType)ZingNodeType.Array; this.domainType = SystemTypes.Int32; this.Rank = 1; this.LowerBounds = new int[] { 0 }; } public ZArray(TypeNode elementType, int[] sizes) : this() { this.ElementType = elementType; this.Sizes = sizes; } public override bool IsPrimitiveComparable { get { return true; } } } public class ZMethod : Method { private bool isAtomic; public bool Atomic { get { return this.isAtomic; } set { this.isAtomic = value; } } private bool isActivated; public bool Activated { get { return this.isActivated; } set { this.isActivated = value; } } private List<Field> localVars = new List<Field>(); public List<Field> LocalVars { get { return this.localVars; } } // For use by the duplicator internal void ResetLocals() { localVars = new List<Field>(); } public ZMethod() { } public ZMethod(TypeNode declaringType, AttributeList attributes, Identifier name, ParameterList parameters, TypeNode returnType, Block body) : base(declaringType, attributes, name, parameters, returnType, body) { } public ZMethod(TypeNode declaringType, bool atomic, bool activated, Identifier name, ParameterList parameters, TypeNode returnType, Block body) : base(declaringType, null, name, parameters, returnType, body) { this.isActivated = activated; this.isAtomic = atomic; if (activated) this.Flags |= MethodFlags.Static; } } /* * New statements */ public class AtomicBlock : Block { public AtomicBlock() { this.NodeType = (NodeType)ZingNodeType.Atomic; } public AtomicBlock(StatementList statements) : base(statements) { this.NodeType = (NodeType)ZingNodeType.Atomic; } public AtomicBlock(StatementList statements, SourceContext sourceContext) : base(statements, sourceContext) { this.NodeType = (NodeType)ZingNodeType.Atomic; } } public class AssertStatement : Statement { internal Expression booleanExpr; public Expression Expression { get { return this.booleanExpr; } set { this.booleanExpr = value; } } private string comment; public string Comment { get { return this.comment; } set { this.comment = value; } } public AssertStatement() : base((NodeType)ZingNodeType.Assert) { } public AssertStatement(Expression booleanExpr, string comment) : this() { this.booleanExpr = booleanExpr; this.Comment = comment; } public AssertStatement(Expression booleanExpr, string comment, SourceContext sourceContext) : base((NodeType)ZingNodeType.Assert) { this.booleanExpr = booleanExpr; this.Comment = comment; this.SourceContext = sourceContext; } } public class AcceptStatement : Statement { internal Expression booleanExpr; public Expression Expression { get { return this.booleanExpr; } set { this.booleanExpr = value; } } public AcceptStatement() : base((NodeType)ZingNodeType.Accept) { } public AcceptStatement(Expression booleanExpr) : this() { this.booleanExpr = booleanExpr; } public AcceptStatement(Expression booleanExpr, SourceContext sourceContext) : base((NodeType)ZingNodeType.Accept) { this.booleanExpr = booleanExpr; this.SourceContext = sourceContext; } } public class EventStatement : Statement { internal Expression channelNumber; public Expression ChannelNumber { get { return this.channelNumber; } set { this.channelNumber = value; } } internal Expression messageType; public Expression MessageType { get { return this.messageType; } set { this.messageType = value; } } internal Expression direction; public Expression Direction { get { return this.direction; } set { this.direction = value; } } public EventStatement() : base((NodeType)ZingNodeType.Event) { } public EventStatement(Expression channelNumber, Expression messageType, Expression direction) : this() { this.channelNumber = channelNumber; this.messageType = messageType; this.direction = direction; } public EventStatement(Expression messageType, Expression direction) : this(new Literal(0, SystemTypes.Int32), messageType, direction) { } public EventStatement(Expression messageType, Expression direction, SourceContext sourceContext) : this(messageType, direction) { this.SourceContext = sourceContext; } public EventStatement(Expression channelNumber, Expression messageType, Expression direction, SourceContext sourceContext) : this(channelNumber, messageType, direction) { this.SourceContext = sourceContext; } } public class AssumeStatement : Statement { internal Expression booleanExpr; public Expression Expression { get { return this.booleanExpr; } set { this.booleanExpr = value; } } public AssumeStatement() : base((NodeType)ZingNodeType.Assume) { } public AssumeStatement(Expression booleanExpr) : this() { this.booleanExpr = booleanExpr; } public AssumeStatement(Expression booleanExpr, SourceContext sourceContext) : this(booleanExpr) { this.SourceContext = sourceContext; } } public class YieldStatement : Statement { public YieldStatement() : base((NodeType)ZingNodeType.Yield) { } public YieldStatement(SourceContext sourceContext) : this() { this.SourceContext = sourceContext; } } public class SelfExpression : Expression { public SelfExpression() : base((NodeType)ZingNodeType.Self) { this.NodeType = (NodeType)ZingNodeType.Self; this.Type = SystemTypes.Int32; } public SelfExpression(SourceContext sourceContext) : this() { this.SourceContext = sourceContext; } } public class AttributedStatement : Statement { private AttributeList attributes; public AttributeList Attributes { get { return this.attributes; } set { this.attributes = value; } } private Statement statement; public Statement Statement { get { return this.statement; } set { this.statement = value; } } public AttributedStatement() : base((NodeType)ZingNodeType.AttributedStatement) { } public AttributedStatement(AttributeList attributes) : this() { this.Attributes = attributes; } public AttributedStatement(AttributeList attributes, Statement statement) : this() { this.Attributes = attributes; this.Statement = statement; } public AttributedStatement(AttributeNode attr, Statement statement) : this() { this.Attributes = new AttributeList(1); this.Attributes.Add(attr); this.Statement = statement; } } public class TraceStatement : Statement { private ExpressionList operands; public ExpressionList Operands { get { return this.operands; } set { this.operands = value; } } public TraceStatement() : base((NodeType)ZingNodeType.Trace) { } public TraceStatement(ExpressionList operands) : this() { this.operands = operands; } public TraceStatement(ExpressionList operands, SourceContext sourceContext) : this(operands) { this.SourceContext = sourceContext; } } public class InvokePluginStatement : Statement { private ExpressionList operands; public ExpressionList Operands { get { return this.operands; } set { this.operands = value; } } public InvokePluginStatement() : base((NodeType)ZingNodeType.InvokePlugin) { } public InvokePluginStatement(ExpressionList operands) : this() { this.operands = operands; } public InvokePluginStatement(ExpressionList operands, SourceContext sourceContext) : this(operands) { this.SourceContext = sourceContext; } } public class InvokeSchedulerStatement : Statement { private ExpressionList operands; public ExpressionList Operands { get { return this.operands; } set { this.operands = value; } } public InvokeSchedulerStatement() : base((NodeType)ZingNodeType.InvokeSched) { } public InvokeSchedulerStatement(ExpressionList operands) : this() { this.operands = operands; } public InvokeSchedulerStatement(ExpressionList operands, SourceContext sourceContext) : this(operands) { this.SourceContext = sourceContext; } } public class AsyncMethodCall : ExpressionStatement { public AsyncMethodCall() { this.NodeType = (NodeType)ZingNodeType.Async; } public AsyncMethodCall(Expression callee, ExpressionList arguments) : this() { this.Expression = new MethodCall(callee, arguments); } public AsyncMethodCall(Expression callee, ExpressionList arguments, SourceContext sourceContext) : this(callee, arguments) { this.SourceContext = sourceContext; this.Expression.SourceContext = sourceContext; } public Expression Callee { get { Debug.Assert(this.Expression is MethodCall); return ((MethodCall)this.Expression).Callee; } set { Debug.Assert(this.Expression is MethodCall); ((MethodCall)this.Expression).Callee = value; } } public ExpressionList Operands { get { Debug.Assert(this.Expression is MethodCall); return ((MethodCall)this.Expression).Operands; } set { Debug.Assert(this.Expression is MethodCall); ((MethodCall)this.Expression).Operands = value; } } } public class SendStatement : Statement { internal Expression channel; public Expression Channel { get { return this.channel; } set { this.channel = value; } } internal Expression data; public Expression Data { get { return this.data; } set { this.data = value; } } public SendStatement() : base((NodeType)ZingNodeType.Send) { } public SendStatement(Expression channel, Expression data) : this() { this.channel = channel; this.data = data; } public SendStatement(Expression channel, Expression data, SourceContext sourceContext) : this(channel, data) { this.SourceContext = sourceContext; } } public class Select : Statement { internal bool validEndState; public bool ValidEndState { get { return this.validEndState; } set { this.validEndState = value; } } internal bool deterministicSelection; public bool DeterministicSelection { get { return this.deterministicSelection; } set { this.deterministicSelection = value; } } internal bool visible; public bool Visible { get { return this.visible; } set { this.visible = value; } } internal JoinStatementList joinStatementList; public JoinStatementList JoinStatements { get { return this.joinStatementList; } set { this.joinStatementList = value; } } public Select() : base((NodeType)ZingNodeType.Select) { } public Select(bool endState, bool deterministic, JoinStatementList joinStatementList) : this(endState, deterministic, false, joinStatementList) { } public Select(bool endState, bool deterministic, JoinStatementList joinStatementList, SourceContext sourceContext) : this(endState, deterministic, joinStatementList) { this.SourceContext = sourceContext; } public Select(bool endState, bool deterministic, bool visible, JoinStatementList joinStatementList) : this() { this.validEndState = endState; this.deterministicSelection = deterministic; this.visible = visible; this.joinStatementList = joinStatementList; } public Select(bool endState, bool deterministic, bool visible, JoinStatementList joinStatementList, SourceContext sourceContext) : this(endState, deterministic, visible, joinStatementList) { this.SourceContext = sourceContext; } } public class JoinStatement : Statement { internal AttributeList attributes; public AttributeList Attributes { get { return this.attributes; } set { this.attributes = value; } } internal Statement statement; public Statement Statement { get { return this.statement; } set { this.statement = value; } } internal JoinPatternList joinPatternList; public JoinPatternList JoinPatterns { get { return this.joinPatternList; } set { this.joinPatternList = value; } } public JoinStatement() : base((NodeType)ZingNodeType.JoinStatement) { } public JoinStatement(JoinPatternList joinPatternList, Statement statement) : this() { this.joinPatternList = joinPatternList; this.statement = statement; } public JoinStatement(JoinPatternList joinPatternList, Statement statement, SourceContext sourceContext) : this(joinPatternList, statement) { this.SourceContext = sourceContext; } internal bool visible; // propagated from the select statement by the looker } abstract public class JoinPattern : Node { protected JoinPattern(ZingNodeType nodeType) : base((NodeType)nodeType) { } } public class TimeoutPattern : JoinPattern { public TimeoutPattern() : base(ZingNodeType.TimeoutPattern) { } } public class WaitPattern : JoinPattern { internal Expression expression; public Expression Expression { get { return this.expression; } set { this.expression = value; } } public WaitPattern() : base(ZingNodeType.WaitPattern) { } public WaitPattern(Expression expression) : this() { this.expression = expression; } } public class ReceivePattern : JoinPattern { internal Expression channel; public Expression Channel { get { return this.channel; } set { this.channel = value; } } internal Expression data; public Expression Data { get { return this.data; } set { this.data = value; } } public ReceivePattern() : base(ZingNodeType.ReceivePattern) { } public ReceivePattern(Expression channel, Expression data) : this() { this.channel = channel; this.data = data; } } public class EventPattern : JoinPattern { internal Expression channelNumber; public Expression ChannelNumber { get { return this.channelNumber; } set { this.channelNumber = value; } } internal Expression messageType; public Expression MessageType { get { return this.messageType; } set { this.messageType = value; } } internal Expression direction; public Expression Direction { get { return this.direction; } set { this.direction = value; } } public EventPattern() : base(ZingNodeType.EventPattern) { } public EventPattern(Expression messageType, Expression direction) : this(new Literal(0, SystemTypes.Int32), messageType, direction) { } public EventPattern(Expression channelNumber, Expression messageType, Expression direction) : this() { this.channelNumber = channelNumber; this.messageType = messageType; this.direction = direction; } } public class ZTry : Statement { private WithList catchers; public WithList Catchers { get { return this.catchers; } set { this.catchers = value; } } private Block body; public Block Body { get { return this.body; } set { this.body = value; } } public ZTry() : base((NodeType)ZingNodeType.Try) { } public ZTry(Block body, WithList catchers) : this() { this.body = body; this.catchers = catchers; } } public class With : Statement { internal Block Block; public Block Body { get { return this.Block; } set { this.Block = value; } } private Identifier name; public Identifier Name { get { return this.name; } set { this.name = value; } } public With() : base((NodeType)ZingNodeType.With) { } public With(Identifier name, Block block) : this() { this.Block = block; this.Name = name; } } public sealed class JoinStatementList { private JoinStatement[] elements = new JoinStatement[16]; private int length; public JoinStatementList() { this.elements = new JoinStatement[16]; } public JoinStatementList(int capacity) { this.elements = new JoinStatement[capacity]; } public JoinStatementList(params JoinStatement[] elements) { if (elements == null) elements = new JoinStatement[0]; this.elements = elements; this.length = elements.Length; } public void Add(JoinStatement element) { int n = this.elements.Length; int i = this.length++; if (i == n) { int m = n * 2; if (m < 16) m = 16; JoinStatement[] newElements = new JoinStatement[m]; for (int j = 0; j < n; j++) newElements[j] = elements[j]; this.elements = newElements; } this.elements[i] = element; } public JoinStatementList Clone() { int n = this.length; JoinStatementList result = new JoinStatementList(n); result.length = n; JoinStatement[] newElements = result.elements; for (int i = 0; i < n; i++) newElements[i] = this.elements[i]; return result; } public int Length { get { return this.length; } } public JoinStatement this[int index] { get { return this.elements[index]; } set { this.elements[index] = value; } } } public sealed class JoinPatternList { private JoinPattern[] elements = new JoinPattern[16]; private int length; public JoinPatternList() { this.elements = new JoinPattern[16]; } public JoinPatternList(int capacity) { this.elements = new JoinPattern[capacity]; } public JoinPatternList(params JoinPattern[] elements) { if (elements == null) elements = new JoinPattern[0]; this.elements = elements; this.length = elements.Length; } public void Add(JoinPattern element) { int n = this.elements.Length; int i = this.length++; if (i == n) { int m = n * 2; if (m < 16) m = 16; JoinPattern[] newElements = new JoinPattern[m]; for (int j = 0; j < n; j++) newElements[j] = elements[j]; this.elements = newElements; } this.elements[i] = element; } public JoinPatternList Clone() { int n = this.length; JoinPatternList result = new JoinPatternList(n); result.length = n; JoinPattern[] newElements = result.elements; for (int i = 0; i < n; i++) newElements[i] = this.elements[i]; return result; } public int Length { get { return this.length; } } public JoinPattern this[int index] { get { return this.elements[index]; } set { this.elements[index] = value; } } } public sealed class WithList { private With[] elements = new With[16]; private int length; public WithList() { this.elements = new With[16]; } public WithList(int capacity) { this.elements = new With[capacity]; } public WithList(params With[] elements) { if (elements == null) elements = new With[0]; this.elements = elements; this.length = elements.Length; } public void Add(With element) { int n = this.elements.Length; int i = this.length++; if (i == n) { int m = n * 2; if (m < 16) m = 16; With[] newElements = new With[m]; for (int j = 0; j < n; j++) newElements[j] = elements[j]; this.elements = newElements; } this.elements[i] = element; } public WithList Clone() { int n = this.length; WithList result = new WithList(n); result.length = n; With[] newElements = result.elements; for (int i = 0; i < n; i++) newElements[i] = this.elements[i]; return result; } public int Length { get { return this.length; } } public With this[int index] { get { return this.elements[index]; } set { this.elements[index] = value; } } } internal class BasicBlock : Statement { internal Statement Statement; internal Scope Scope; // If the block corresponds to the start of a select statement, this gives us a // reference to the select statement itself. internal Select selectStmt; internal Expression ConditionalExpression; internal BasicBlock ConditionalTarget; internal BasicBlock UnconditionalTarget; internal AttributeList Attributes; // for attributed statements internal BasicBlock handlerTarget; internal int RelativeAtomicLevel; internal bool IsAtomicEntry; internal bool MiddleOfTransition; internal bool Yields; // EndsAtomicBlock was used for 2 purposes: // 1) Transition Delimiter // 2) Transaction Delimiter // We use MiddleOfTransition for the 1st purpose // and {Enter,Exit}AtomicScope for the 2nd purpose // Precise list of places EndAtomicBlock used as // Transition Delimiter: // 1) when target of a branch points to a null block (VisitBlock) // 2) ditto (VisitBranch) // 3) raiseBlock (visitThrow) // 4) defaultHandler, catchTester, setHandler (VisitZtry) // 5) incrBlock, derefBlock, initBlock (VisitForEach) // 6) jsTester, jsReceivers (VisitSelect) // 7) choiceHelper, selectBlock // 8) callBlock // internal bool EndsAtomicBlock; internal bool IsEntryPoint; internal bool SecondOfTwo; internal bool PropagatesException; internal bool SkipNormalizer; internal int Id; internal BasicBlock(Statement statement, Expression conditionalExpression, BasicBlock conditionalTarget , BasicBlock unconditionalTarget) : base((NodeType)ZingNodeType.BasicBlock) { this.Id = -1; this.Statement = statement; ConditionalExpression = conditionalExpression; ConditionalTarget = conditionalTarget; UnconditionalTarget = unconditionalTarget; } internal BasicBlock(Statement statement) : this(statement, null, null, null) { } internal BasicBlock(Statement statement, BasicBlock unconditionalTarget) : this(statement, null, null, unconditionalTarget) { } internal bool IsReturn { get { return ConditionalTarget == null && UnconditionalTarget == null && !PropagatesException; } } internal string Name { get { if (IsEntryPoint) return "Enter"; else return "B" + Id.ToString(CultureInfo.InvariantCulture); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using AxiomCoders.PdfTemplateEditor.EditorStuff; using AxiomCoders.PdfTemplateEditor.Common; namespace AxiomCoders.PdfTemplateEditor.EditorItems { /// <summary> /// show ruler /// </summary> public class Ruler: EditorItemViewer { public enum RulerPosition { TOP, LEFT, GUIDE } /// <summary> /// Position of this ruler /// </summary> private RulerPosition position; /// <summary> /// Measure unit used for ruler /// </summary> private MeasureUnits measureUnit = MeasureUnits.inch; public AxiomCoders.PdfTemplateEditor.Common.MeasureUnits MeasureUnit { get { switch (AppOptions.Instance.Unit) { case 0: measureUnit = MeasureUnits.inch; break; case 1: measureUnit = MeasureUnits.mm; break; case 2: measureUnit = MeasureUnits.cm; break; case 3: measureUnit = MeasureUnits.pixel; break; } return measureUnit; } set { measureUnit = value; } } /// <summary> /// Report page that is shown and attached to this ruler /// </summary> private ReportPage reportPage; /// <summary> /// Constructor /// </summary> /// <param name="position"></param> public Ruler(RulerPosition position, ReportPage reportPage) { this.position = position; this.reportPage = reportPage; } /// <summary> /// Draw top ruler /// </summary> /// <param name="gc"></param> private void DrawTop(Graphics gc, Rectangle clipRect) { float pixelsPerUnit = UnitsManager.Instance.ConvertUnit(1, this.MeasureUnit, MeasureUnits.pixel); pixelsPerUnit *= reportPage.ZoomLevel / 100.0f; float shortLineInterval = 0; float increaseValue = 1; Font font = new Font(FontFamily.GenericSansSerif, 8); float value = 0; float smallMarks = 5; // short lines float smallMarksDistance = 10; // in pixels while (true) { shortLineInterval = (pixelsPerUnit*(float)increaseValue) / (float)smallMarks; if (shortLineInterval < smallMarksDistance) { increaseValue++; } else if (shortLineInterval > smallMarksDistance*2) { increaseValue /= 2; } else { break; } } // draw from 0 to right int tick = 0; for (float i = (int)reportPage.LastDrawMatrix.Elements[4]; i < clipRect.Width; i += shortLineInterval) { if (tick % smallMarks == 0) { gc.DrawLine(Pens.Black, + (int)i, clipRect.Height, (int)i, clipRect.Height - 20); gc.DrawString(value.ToString(), font, Brushes.Black, (int)i + 3, 5); value += increaseValue; } else { gc.DrawLine(Pens.Black, (int)i, clipRect.Height, (int)i, clipRect.Height - 5); } tick++; } // draw from 0 to left tick = 0; value = 0; for(float i = (int)reportPage.LastDrawMatrix.Elements[4]; i > 0; i -= shortLineInterval) { if(tick % smallMarks == 0) { gc.DrawLine(Pens.Black, (int)i, clipRect.Height, (int)i, clipRect.Height - 20); gc.DrawString(value.ToString(), font, Brushes.Black, (int)i + 3, 5); value -= increaseValue; } else { gc.DrawLine(Pens.Black, (int)i, clipRect.Height, (int)i, clipRect.Height - 5); } tick++; } } /// <summary> /// Draw left ruler /// </summary> /// <param name="gc"></param> /// <param name="clipRect"></param> private void DrawLeft(Graphics gc, Rectangle clipRect) { float pixels = UnitsManager.Instance.ConvertUnit(1, this.MeasureUnit, MeasureUnits.pixel); pixels *= reportPage.ZoomLevel / 100.0f; float shortLineInterval = 0; float increaseValue = 1; Font font = new Font(FontFamily.GenericSansSerif, 8); float value = 0; float smallMarks = 5; // short lines float smallMarksDistance = 10; // in pixels while (true) { shortLineInterval = (pixels * (float)increaseValue) / (float)smallMarks; if (shortLineInterval < smallMarksDistance) { increaseValue++; } else if (shortLineInterval > smallMarksDistance * 2) { increaseValue /= 2; } else { break; } } // from 0 to bottom int tick = 0; for(float i = (int)reportPage.LastDrawMatrix.Elements[5]; i < clipRect.Height; i += shortLineInterval) { if (tick % smallMarks == 0) { gc.DrawLine(Pens.Black, 0, (int)i, clipRect.Width, (int)i); gc.DrawString(value.ToString(), font, Brushes.Black, 3, (int)i + 3); value += increaseValue; } else { gc.DrawLine(Pens.Black, clipRect.Width-5, (int)i, clipRect.Width, (int)i); } tick++; } // from 0 to top tick = 0; value = 0; for(float i = (int)reportPage.LastDrawMatrix.Elements[5]; i > 0; i -= shortLineInterval) { if (tick % smallMarks == 0) { gc.DrawLine(Pens.Black, 0, (int)i, clipRect.Width, (int)i); gc.DrawString(value.ToString(), font, Brushes.Black, 3, (int)i + 3); value -= increaseValue; } else { gc.DrawLine(Pens.Black, clipRect.Width - 5, (int)i, clipRect.Width, (int)i); } tick++; } } private void DrawGuide(Graphics gc, Rectangle clipRect) { } #region EditorItemViewer Members public void Draw(int offsetX, int offsetY, int parentX, int parentY, float zoomLevel, Graphics gc, Rectangle clipRect) { switch (position) { case RulerPosition.TOP: DrawTop(gc, clipRect); break; case RulerPosition.LEFT: DrawLeft(gc, clipRect); break; case RulerPosition.GUIDE: DrawGuide(gc, clipRect); break; } } #endregion } }
// // MetadataServiceJob.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Net; using System.Collections.Generic; using Hyena; using Banshee.Base; using Banshee.Kernel; using Banshee.Collection; using Banshee.Streaming; using Banshee.Networking; using Banshee.ServiceStack; namespace Banshee.Metadata { public class MetadataServiceJob : IMetadataLookupJob { private MetadataService service; private bool cancelled; private IBasicTrackInfo track; private List<StreamTag> tags = new List<StreamTag>(); private IMetadataLookupJob current_job; protected bool InternetConnected { get { return ServiceManager.Get<Network> ().Connected; } } protected MetadataServiceJob() { } public MetadataServiceJob(MetadataService service, IBasicTrackInfo track) { this.service = service; this.track = track; } public virtual void Cancel () { cancelled = true; lock (this) { if (current_job != null) { current_job.Cancel (); } } } public virtual void Run() { foreach(IMetadataProvider provider in service.Providers) { if (cancelled) break;; try { lock (this) { current_job = provider.CreateJob(track); } current_job.Run(); if (cancelled) break;; foreach(StreamTag tag in current_job.ResultTags) { AddTag(tag); } lock (this) { current_job = null; } } catch (System.Threading.ThreadAbortException) { throw; } catch(Exception e) { Hyena.Log.Exception (e); } } service.OnHaveResult (this); } public virtual IBasicTrackInfo Track { get { return track; } protected set { track = value; } } public virtual IList<StreamTag> ResultTags { get { return tags; } } protected void AddTag(StreamTag tag) { tags.Add(tag); } protected HttpWebResponse GetHttpStream(Uri uri) { return GetHttpStream(uri, null); } protected HttpWebResponse GetHttpStream(Uri uri, string [] ignoreMimeTypes) { if(!InternetConnected) { throw new NetworkUnavailableException(); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri); request.UserAgent = Banshee.Web.Browser.UserAgent; request.Timeout = 10 * 1000; request.KeepAlive = false; request.AllowAutoRedirect = true; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if(ignoreMimeTypes != null) { string [] content_types = response.Headers.GetValues("Content-Type"); if(content_types != null) { foreach(string content_type in content_types) { for(int i = 0; i < ignoreMimeTypes.Length; i++) { if(content_type == ignoreMimeTypes[i]) { return null; } } } } } return response; } protected bool SaveHttpStream(Uri uri, string path) { return SaveHttpStream(uri, path, null); } protected bool SaveHttpStream(Uri uri, string path, string [] ignoreMimeTypes) { HttpWebResponse response = GetHttpStream(uri, ignoreMimeTypes); Stream from_stream = response == null ? null : response.GetResponseStream (); if(from_stream == null) { if (response != null) { response.Close (); } return false; } SaveAtomically (path, from_stream); from_stream.Close (); return true; } protected bool SaveHttpStreamCover (Uri uri, string albumArtistId, string [] ignoreMimeTypes) { return SaveHttpStream (uri, CoverArtSpec.GetPath (albumArtistId), ignoreMimeTypes); } protected void SaveAtomically (string path, Stream from_stream) { if (String.IsNullOrEmpty (path) || from_stream == null || !from_stream.CanRead) { return; } SafeUri path_uri = new SafeUri (path); if (Banshee.IO.File.Exists (path_uri)) { return; } // Save the file to a temporary path while downloading/copying, // so that nobody sees it and thinks it's ready for use before it is SafeUri tmp_uri = new SafeUri (String.Format ("{0}.part", path)); try { Banshee.IO.StreamAssist.Save (from_stream, Banshee.IO.File.OpenWrite (tmp_uri, true)); Banshee.IO.File.Move (tmp_uri, path_uri); } catch (Exception e) { Hyena.Log.Exception (e); } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using PdfSharp.Drawing; namespace PdfSharp.Pdf.Advanced { /// <summary> /// Contains all external PDF files from which PdfFormXObjects are imported into the current document. /// </summary> internal sealed class PdfFormXObjectTable : PdfResourceTable { // The name PdfFormXObjectTable is technically not correct, because in contrast to PdfFontTable // or PdfImageTable this class holds no PdfFormXObject objects. Actually it holds instances of // the class ImportedObjectTable, one for each external document. The PdfFormXObject instances // are not cached, because they hold a transformation matrix that make them unique. If the user // wants to use a particual page of a PdfFormXObject more than once, he must reuse the object // before he changes the PageNumber or the transformation matrix. In other words this class // caches the indirect objects of an external form, not the form itself. /// <summary> /// Initializes a new instance of this class, which is a singleton for each document. /// </summary> public PdfFormXObjectTable(PdfDocument document) : base(document) { } /// <summary> /// Gets a PdfFormXObject from an XPdfForm. Because the returned objects must be unique, always /// a new instance of PdfFormXObject is created if none exists for the specified form. /// </summary> public PdfFormXObject GetForm(XForm form) { // If the form already has a PdfFormXObject, return it. if (form._pdfForm != null) { Debug.Assert(form.IsTemplate, "An XPdfForm must not have a PdfFormXObject."); if (ReferenceEquals(form._pdfForm.Owner, Owner)) return form._pdfForm; //throw new InvalidOperationException("Because of a current limitation of PDFsharp an XPdfForm object can be used only within one single PdfDocument."); // Dispose PdfFromXObject when document has changed form._pdfForm = null; } XPdfForm pdfForm = form as XPdfForm; if (pdfForm != null) { // Is the external PDF file from which is imported already known for the current document? Selector selector = new Selector(form); PdfImportedObjectTable importedObjectTable; if (!_forms.TryGetValue(selector, out importedObjectTable)) { // No: Get the external document from the form and create ImportedObjectTable. PdfDocument doc = pdfForm.ExternalDocument; importedObjectTable = new PdfImportedObjectTable(Owner, doc); _forms[selector] = importedObjectTable; } PdfFormXObject xObject = importedObjectTable.GetXObject(pdfForm.PageNumber); if (xObject == null) { xObject = new PdfFormXObject(Owner, importedObjectTable, pdfForm); importedObjectTable.SetXObject(pdfForm.PageNumber, xObject); } return xObject; } Debug.Assert(form.GetType() == typeof(XForm)); form._pdfForm = new PdfFormXObject(Owner, form); return form._pdfForm; } /// <summary> /// Gets the imported object table. /// </summary> public PdfImportedObjectTable GetImportedObjectTable(PdfPage page) { // Is the external PDF file from which is imported already known for the current document? Selector selector = new Selector(page); PdfImportedObjectTable importedObjectTable; if (!_forms.TryGetValue(selector, out importedObjectTable)) { importedObjectTable = new PdfImportedObjectTable(Owner, page.Owner); _forms[selector] = importedObjectTable; } return importedObjectTable; } /// <summary> /// Gets the imported object table. /// </summary> public PdfImportedObjectTable GetImportedObjectTable(PdfDocument document) { if (document == null) throw new ArgumentNullException("document"); // Is the external PDF file from which is imported already known for the current document? Selector selector = new Selector(document); PdfImportedObjectTable importedObjectTable; if (!_forms.TryGetValue(selector, out importedObjectTable)) { // Create new table for document. importedObjectTable = new PdfImportedObjectTable(Owner, document); _forms[selector] = importedObjectTable; } return importedObjectTable; } public void DetachDocument(PdfDocument.DocumentHandle handle) { if (handle.IsAlive) { foreach (Selector selector in _forms.Keys) { PdfImportedObjectTable table = _forms[selector]; if (table.ExternalDocument != null && table.ExternalDocument.Handle == handle) { _forms.Remove(selector); break; } } } // Clean table bool itemRemoved = true; while (itemRemoved) { itemRemoved = false; foreach (Selector selector in _forms.Keys) { PdfImportedObjectTable table = _forms[selector]; if (table.ExternalDocument == null) { _forms.Remove(selector); itemRemoved = true; break; } } } } /// <summary> /// Map from Selector to PdfImportedObjectTable. /// </summary> readonly Dictionary<Selector, PdfImportedObjectTable> _forms = new Dictionary<Selector, PdfImportedObjectTable>(); /// <summary> /// A collection of information that uniquely identifies a particular ImportedObjectTable. /// </summary> public class Selector { /// <summary> /// Initializes a new instance of FormSelector from an XPdfForm. /// </summary> public Selector(XForm form) { // HACK: just use full path to identify _path = form._path.ToLowerInvariant(); } /// <summary> /// Initializes a new instance of FormSelector from a PdfPage. /// </summary> public Selector(PdfPage page) { PdfDocument owner = page.Owner; _path = "*" + owner.Guid.ToString("B"); _path = _path.ToLowerInvariant(); } public Selector(PdfDocument document) { _path = "*" + document.Guid.ToString("B"); _path = _path.ToLowerInvariant(); } public string Path { get { return _path; } set { _path = value; } } string _path; public override bool Equals(object obj) { Selector selector = obj as Selector; if (obj == null) return false; return _path == selector._path; ; } public override int GetHashCode() { return _path.GetHashCode(); } } } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Text; using System.Net; using Alachisoft.NCache.SocketServer; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Serialization; using Alachisoft.NCache.Common; using Alachisoft.NCache.Web.Util; using Alachisoft.NCache.SocketServer.Statistics; using System.Collections.Generic; using System.Collections; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common.Monitoring; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common.Logger; using Runtime = Alachisoft.NCache.Runtime; namespace Alachisoft.NCache.SocketServer { /// <summary> /// An object of this class is called when Ncache service starts and stops /// </summary> public sealed class SocketServer: CacheRenderer { int _serverPort; int _sendBuffer; int _recieveBuffer; public const int DEFAULT_SOCK_SERVER_PORT = 9800; public const int DEFAULT_MANAGEMENT_PORT = 8250; public const int DEFAULT_SOCK_BUFFER_SIZE = 32768; //Size is specified in bytes (.net stream if grow more then 1.9GB will give memory exception that's why //we send multiple responses each containing objects of specified size. // 1 GB = 1 * 1024 * 1024 * 1024 = 1073741824 // 1 GB = 1 * MB * KB * Bytes = 1073741824 // If not specified in Service config then we will consider 1GB packeting public static long CHUNK_SIZE_FOR_OBJECT = 1073741824; static Logs _logger = new Logs(); static bool _enableCacheServerCounters = true; PerfStatsCollector _perfStatsColl = null; static LoggingInfo _serverLoggingInfo = new LoggingInfo(); /// <summary> /// The garbage collection timer class. /// </summary> GarbageCollectionTimer gcTimer; ConnectionManager _conManager; LoggerNames _loggerName; /// <summary> /// Initializes the socket server with the given port. /// </summary> /// <param name="port"></param> /// <param name="sendBufferSize"></param> /// <param name="recieveBufferSize"></param> public SocketServer(int port, int sendBufferSize, int recieveBufferSize) { _serverPort = port; _sendBuffer = sendBufferSize; _recieveBuffer = recieveBufferSize; if (System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.ResponseDataSize") != null) { CHUNK_SIZE_FOR_OBJECT = Convert.ToInt64(System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.ResponseDataSize")); CHUNK_SIZE_FOR_OBJECT = CHUNK_SIZE_FOR_OBJECT < 0 ? 1024 : CHUNK_SIZE_FOR_OBJECT;//If less then zero is specified switch to default else pick the specified value CHUNK_SIZE_FOR_OBJECT = CHUNK_SIZE_FOR_OBJECT * 1024 * 1024; //Convert size from MB's to bytes } } /// <summary> /// Gets the socket server port. /// </summary> public int ServerPort { get { return _serverPort; } set { _serverPort = value < 0 ? DEFAULT_SOCK_SERVER_PORT : value; } } /// <summary> /// Gets the send buffer size of connected client socket. /// </summary> public int SendBufferSize { get { return _sendBuffer; } set { _sendBuffer = value < 0 ? DEFAULT_SOCK_BUFFER_SIZE : value; } } public static Logs Logger { get { return _logger; } } /// <summary> /// Gets the receive buffer size of connected client socket. /// </summary> public int ReceiveBufferSize { get { return _recieveBuffer; } set { _recieveBuffer = value < 0 ? DEFAULT_SOCK_BUFFER_SIZE : value; } } /// <summary> /// Gets a value indicating whether Cache Server counters are enabled or not. /// </summary> public static bool IsServerCounterEnabled { get { return _enableCacheServerCounters; } set { _enableCacheServerCounters = value; } } /// <summary> /// Starts the socket server.It registers some types with compact Framework, /// enables simple logs as well as DetailedLogs, then it checks Ncache licence information. /// starts connection manager and perfmon counters. /// </summary> /// <param name="bindIP" ></param> /// public void Start(IPAddress bindIP, LoggerNames loggerName, string perfStatColInstanceName, CommandManagerType cmdMgrType) { if (loggerName == null) _loggerName = LoggerNames.SocketServerLogs; else _loggerName = loggerName; InitializeLogging(); _perfStatsColl = new PerfStatsCollector("NCache Server", _serverPort); _conManager = new ConnectionManager(_perfStatsColl); _conManager.Start(bindIP, _serverPort, _sendBuffer, _recieveBuffer, _logger, cmdMgrType); //We initialize PerfstatsCollector only for SocketServer's instance for client. //Management socket server has just DUMMY stats collector. if(cmdMgrType == CommandManagerType.NCacheClient) _perfStatsColl.InitializePerfCounters(); } /// <summary> /// Initialize logging by reading setting from application configuration file /// </summary> public void InitializeLogging() { bool enable_logs = false; bool detailed_logs = false; try { if (System.Configuration.ConfigurationSettings.AppSettings.Get("EnableLogs") != null) { enable_logs = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["EnableLogs"]); } if (System.Configuration.ConfigurationSettings.AppSettings.Get("EnableDetailedLogs") != null) { detailed_logs = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["EnableDetailedLogs"]); } this.InitializeLogging(enable_logs, detailed_logs); } catch (Exception) { throw; } } /// <summary> /// Initialize logging /// </summary> /// <param name="enable">Enable error logging only</param> /// <param name="detailed">Enable detailed logging</param> public void InitializeLogging(bool errorOnly, bool detailed) { try { if (errorOnly || detailed) { Logs localLogger=new Logs(); localLogger.NCacheLog = new NCacheLogger(); localLogger.NCacheLog.Initialize(LoggerNames.SocketServerLogs); if (detailed) { localLogger.NCacheLog.SetLevel("all"); localLogger.IsErrorLogsEnabled = true; } else { localLogger.NCacheLog.SetLevel("info"); } localLogger.NCacheLog.Info("SocketServer.Start", "server started successfully"); ///Set logging status if (errorOnly) _serverLoggingInfo.SetStatus(LoggingInfo.LoggingType.Error, LoggingInfo.LogsStatus.Enable); if (detailed) _serverLoggingInfo.SetStatus(LoggingInfo.LoggingType.Detailed, (detailed ? LoggingInfo.LogsStatus.Enable : LoggingInfo.LogsStatus.Disable)); localLogger.IsDetailedLogsEnabled = detailed; localLogger.IsErrorLogsEnabled = errorOnly; _logger= localLogger; } else { if (_logger.NCacheLog != null) { _logger.NCacheLog.Flush(); _logger.NCacheLog.SetLevel("OFF"); } } } catch (Exception) { throw; } } /// <summary> /// Stops the socket server. Stops connection manager. /// </summary> public void Stop() { if (_conManager != null) { _conManager.Stop(); } } public void StopListening() { if (_conManager != null) _conManager.StopListening(); } ~SocketServer() { if (_conManager != null) { _conManager.Stop(); _conManager = null; } if (_perfStatsColl != null) { _perfStatsColl.Dispose(); _perfStatsColl = null; } } /// <summary> /// Gets Server Port. /// </summary> public override int Port { get { return ServerPort; } } /// <summary> /// Converts server IpAddress string to IPAddress instance and return that. /// </summary> public override IPAddress IPAddress { get { try { return IPAddress.Parse(ConnectionManager.ServerIpAddress); } catch (Exception ex) { return null; } } } /// <summary> /// Get current logging status for specified type /// </summary> /// <param name="subsystem"></param> /// <param name="type"></param> /// <returns></returns> public override LoggingInfo.LogsStatus GetLoggingStatus(LoggingInfo.LoggingSubsystem subsystem, LoggingInfo.LoggingType type) { switch (subsystem) { case LoggingInfo.LoggingSubsystem.Server: lock (_serverLoggingInfo) { return _serverLoggingInfo.GetStatus(type); } case LoggingInfo.LoggingSubsystem.Client: return ConnectionManager.GetClientLoggingInfo(type); default: return LoggingInfo.LogsStatus.Disable; } } /// <summary> /// Set and apply logging status /// </summary> /// <param name="subsystem"></param> /// <param name="type"></param> /// <param name="status"></param> public override void SetLoggingStatus(LoggingInfo.LoggingSubsystem subsystem, LoggingInfo.LoggingType type, LoggingInfo.LogsStatus status) { if (subsystem == LoggingInfo.LoggingSubsystem.Client) { bool updateClient = false; switch (type) { case LoggingInfo.LoggingType.Error: case LoggingInfo.LoggingType.Detailed: updateClient = ConnectionManager.SetClientLoggingInfo(type, status); break; case (LoggingInfo.LoggingType.Error | LoggingInfo.LoggingType.Detailed): bool updateErrorLogs = ConnectionManager.SetClientLoggingInfo(LoggingInfo.LoggingType.Error, status); bool updateDetailedLogs = ConnectionManager.SetClientLoggingInfo(LoggingInfo.LoggingType.Detailed, status); updateClient = (updateErrorLogs || updateDetailedLogs); break; } if (updateClient) ConnectionManager.UpdateClients(); } else if (subsystem == LoggingInfo.LoggingSubsystem.Server) { switch (status) { case LoggingInfo.LogsStatus.Disable: ///If error logs are disabled, then disable both if (type == LoggingInfo.LoggingType.Error || type == (LoggingInfo.LoggingType.Error | LoggingInfo.LoggingType.Detailed)) { this.InitializeLogging(false, false); } else if (type == LoggingInfo.LoggingType.Detailed) { this.InitializeLogging(Logger.IsErrorLogsEnabled, false); } break; case LoggingInfo.LogsStatus.Enable: bool error = Logger.IsErrorLogsEnabled; bool detailed = Logger.IsDetailedLogsEnabled; if (type == LoggingInfo.LoggingType.Error) { error = true; detailed = false; } else if (type == LoggingInfo.LoggingType.Detailed | type == (LoggingInfo.LoggingType.Error | LoggingInfo.LoggingType.Detailed)) { error = true; detailed = true; } this.InitializeLogging(error, detailed); break; } } } /// <summary> /// Start the gc timer to collect GEN#2 after specified intervals. /// </summary> /// <param name="dueTime">Time to wait (in minutes) before first collection.</param> /// <param name="period">Time between two consective GEN#2 collections.</param> public void StartGCTimer(int dueTime, int period) { try { } catch (Exception e) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error( "SocketServer.StartGCTimer", e.ToString()); } } //CLIENTSTATS : Add method in CacheRenderer as virtual } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ // NOTE: define this if you want to test the output on US machine and ASCII // characters //#define TEST_MULTICELL_ON_SINGLE_CELL_LOCALE using System.Collections.Specialized; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Host; using Dbg = System.Management.Automation.Diagnostics; // interfaces for host interaction namespace Microsoft.PowerShell.Commands.Internal.Format { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE /// <summary> /// test class to provide easily overridable behavior for testing on US machines /// using US data. /// NOTE: the class just forces any uppercase letter [A-Z] to be prepended /// with an underscore (e.g. "A" becomes "_A", but "a" stays the same) /// </summary> internal class DisplayCellsTest : DisplayCells { internal override int Length(string str, int offset) { int len = 0; for (int k = offset; k < str.Length; k++) { len += this.Length(str[k]); } return len; } internal override int Length(char character) { if (character >= 'A' && character <= 'Z') return 2; return 1; } internal override int GetHeadSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, true); } internal override int GetTailSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, false); } internal string GenerateTestString(string str) { StringBuilder sb = new StringBuilder(); for (int k = 0; k < str.Length; k++) { char ch = str[k]; if (this.Length(ch) == 2) { sb.Append('_'); } sb.Append(ch); } return sb.ToString(); } } #endif /// <summary> /// Tear off class /// </summary> internal class DisplayCellsPSHost : DisplayCells { internal DisplayCellsPSHost(PSHostRawUserInterface rawUserInterface) { _rawUserInterface = rawUserInterface; } internal override int Length(string str, int offset) { Dbg.Assert(offset >= 0, "offset >= 0"); Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length"); try { return _rawUserInterface.LengthInBufferCells(str, offset); } catch (HostException) { //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } return string.IsNullOrEmpty(str) ? 0 : str.Length - offset; } internal override int Length(string str) { try { return _rawUserInterface.LengthInBufferCells(str); } catch (HostException) { //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } return string.IsNullOrEmpty(str) ? 0 : str.Length; } internal override int Length(char character) { try { return _rawUserInterface.LengthInBufferCells(character); } catch (HostException) { //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } return 1; } internal override int GetHeadSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, true); } internal override int GetTailSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, false); } private PSHostRawUserInterface _rawUserInterface; } /// <summary> /// Implementation of the LineOutput interface on top of Console and RawConsole /// </summary> internal sealed class ConsoleLineOutput : LineOutput { #region tracer [TraceSource("ConsoleLineOutput", "ConsoleLineOutput")] internal static PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); #endregion tracer #region LineOutput implementation /// <summary> /// the # of columns is just the width of the screen buffer (not the /// width of the window) /// </summary> /// <value></value> internal override int ColumnNumber { get { CheckStopProcessing(); PSHostRawUserInterface raw = _console.RawUI; // IMPORTANT NOTE: we subtract one because // we want to make sure the console's last column // is never considered written. This causes the writing // logic to always call WriteLine(), making sure a CR // is inserted. try { return _forceNewLine ? raw.BufferSize.Width - 1 : raw.BufferSize.Width; } catch (HostException) { //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } return _forceNewLine ? _fallbackRawConsoleColumnNumber - 1 : _fallbackRawConsoleColumnNumber; } } /// <summary> /// the # of rows is the # of rows visible in the window (and not the # of /// rows in the screen buffer) /// </summary> /// <value></value> internal override int RowNumber { get { CheckStopProcessing(); PSHostRawUserInterface raw = _console.RawUI; try { return raw.WindowSize.Height; } catch (HostException) { //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } return _fallbackRawConsoleRowNumber; } } /// <summary> /// write a line to the output device /// </summary> /// <param name="s">line to write</param> internal override void WriteLine(string s) { CheckStopProcessing(); // delegate the action to the helper, // that will properly break the string into // screen lines _writeLineHelper.WriteLine(s, this.ColumnNumber); } internal override DisplayCells DisplayCells { get { CheckStopProcessing(); if (_displayCellsPSHost != null) { return _displayCellsPSHost; } // fall back if we do not have a Msh host specific instance return _displayCellsPSHost; } } #endregion /// <summary> /// constructor for the ConsoleLineOutput /// </summary> /// <param name="hostConsole">PSHostUserInterface to wrap</param> /// <param name="paging">true if we require prompting for page breaks</param> /// <param name="errorContext">error context to throw exceptions</param> internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext) { if (hostConsole == null) throw PSTraceSource.NewArgumentNullException("hostConsole"); if (errorContext == null) throw PSTraceSource.NewArgumentNullException("errorContext"); _console = hostConsole; _errorContext = errorContext; if (paging) { tracer.WriteLine("paging is needed"); // if we need to do paging, instantiate a prompt handler // that will take care of the screen interaction string promptString = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt); _prompt = new PromptHandler(promptString, this); } PSHostRawUserInterface raw = _console.RawUI; if (raw != null) { tracer.WriteLine("there is a valid raw interface"); #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE // create a test instance with fake behavior this._displayCellsPSHost = new DisplayCellsTest(); #else // set only if we have a valid raw interface _displayCellsPSHost = new DisplayCellsPSHost(raw); #endif } // instantiate the helper to do the line processing when ILineOutput.WriteXXX() is called WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine); WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite); if (_forceNewLine) { _writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, null, this.DisplayCells); } else { _writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, w, this.DisplayCells); } } /// <summary> /// callback to be called when ILineOutput.WriteLine() is called by WriteLineHelper /// </summary> /// <param name="s">string to write</param> private void OnWriteLine(string s) { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); #endif // Do any default transcription. _console.TranscribeResult(s); switch (this.WriteStream) { case WriteStreamType.Error: _console.WriteErrorLine(s); break; case WriteStreamType.Warning: _console.WriteWarningLine(s); break; case WriteStreamType.Verbose: _console.WriteVerboseLine(s); break; case WriteStreamType.Debug: _console.WriteDebugLine(s); break; default: // If the host is in "transcribe only" // mode (due to an implicitly added call to Out-Default -Transcribe), // then don't call the actual host API. if (!_console.TranscribeOnly) { _console.WriteLine(s); } break; } LineWrittenEvent(); } /// <summary> /// callback to be called when ILineOutput.Write() is called by WriteLineHelper /// This is called when the WriteLineHelper needs to write a line whose length /// is the same as the width of the screen buffer /// </summary> /// <param name="s">string to write</param> private void OnWrite(string s) { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); #endif switch (this.WriteStream) { case WriteStreamType.Error: _console.WriteErrorLine(s); break; case WriteStreamType.Warning: _console.WriteWarningLine(s); break; case WriteStreamType.Verbose: _console.WriteVerboseLine(s); break; case WriteStreamType.Debug: _console.WriteDebugLine(s); break; default: _console.Write(s); break; } LineWrittenEvent(); } /// <summary> /// called when a line was written to console /// </summary> private void LineWrittenEvent() { // check to avoid reeentrancy from the prompt handler // writing during the PropmtUser() call if (_disableLineWrittenEvent) return; // if there is no promting, we are done if (_prompt == null) return; // increment the count of lines written to the screen _linesWritten++; // check if we need to put out a prompt if (this.NeedToPrompt) { // put out the prompt _disableLineWrittenEvent = true; PromptHandler.PromptResponse response = _prompt.PromptUser(_console); _disableLineWrittenEvent = false; switch (response) { case PromptHandler.PromptResponse.NextPage: { // reset the counter, since we are starting a new page _linesWritten = 0; } break; case PromptHandler.PromptResponse.NextLine: { // roll back the counter by one, since we allow one more line _linesWritten--; } break; case PromptHandler.PromptResponse.Quit: // 1021203-2005/05/09-JonN // HaltCommandException will cause the command // to stop, but not be reported as an error. throw new HaltCommandException(); } } } /// <summary> /// check if we need to put out a prompt /// </summary> /// <value>true if we need to promp</value> private bool NeedToPrompt { get { // NOTE: we recompute all the time to take into account screen resizing int rawRowNumber = this.RowNumber; if (rawRowNumber <= 0) { // something is wrong, there is no real estate, we suppress prompting return false; } // the prompt will occupy some lines, so we need to subtract them form the total // screen line count int computedPromptLines = _prompt.ComputePromptLines(this.DisplayCells, this.ColumnNumber); int availableLines = this.RowNumber - computedPromptLines; if (availableLines <= 0) { tracer.WriteLine("No available Lines; suppress prompting"); // something is wrong, there is no real estate, we suppress prompting return false; } return _linesWritten >= availableLines; } } #region Private Members /// <summary> /// object to manage prompting /// </summary> private class PromptHandler { /// <summary> /// prompt handler with the given prompt /// </summary> /// <param name="s">prompt string to be used</param> /// <param name="cmdlet">the Cmdlet using this prompt handler</param> internal PromptHandler(string s, ConsoleLineOutput cmdlet) { if (string.IsNullOrEmpty(s)) throw PSTraceSource.NewArgumentNullException("s"); _promptString = s; _callingCmdlet = cmdlet; } /// <summary> /// detemine how many rows the prompt should take. /// </summary> /// <param name="cols">current number of colums on the screen</param> /// <param name="displayCells">string manipupation helper</param> /// <returns></returns> internal int ComputePromptLines(DisplayCells displayCells, int cols) { // split the prompt string into lines _actualPrompt = StringManipulationHelper.GenerateLines(displayCells, _promptString, cols, cols); return _actualPrompt.Count; } /// <summary> /// options returned by the PromptUser() call /// </summary> internal enum PromptResponse { NextPage, NextLine, Quit } /// <summary> /// do the actual prompting /// </summary> /// <param name="console">PSHostUserInterface instance to prompt to</param> internal PromptResponse PromptUser(PSHostUserInterface console) { // NOTE: assume the values passed to ComputePromptLines are still valid // write out the prompt line(s). The last one will not have a new line // at the end because we leave the prompt at the end of the line for (int k = 0; k < _actualPrompt.Count; k++) { if (k < (_actualPrompt.Count - 1)) console.WriteLine(_actualPrompt[k]); // intermediate line(s) else console.Write(_actualPrompt[k]); // last line } while (true) { _callingCmdlet.CheckStopProcessing(); KeyInfo ki = console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho); char key = ki.Character; if (key == 'q' || key == 'Q') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return PromptResponse.Quit; } else if (key == ' ') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return PromptResponse.NextPage; } else if (key == '\r') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return PromptResponse.NextLine; } } } /// <summary> /// cached string(s) valid during a sequence of ComputePromptLines()/PromptUser() /// </summary> private StringCollection _actualPrompt; /// <summary> /// prompt string as passed at initialization /// </summary> private string _promptString; /// <summary> /// The cmdlet that uses this prompt helper /// </summary> private ConsoleLineOutput _callingCmdlet = null; } /// <summary> /// flag to force new lines in CMD.EXE by limiting the /// usable width to N-1 (e.g. 80-1) and forcing a call /// to WriteLine() /// </summary> private bool _forceNewLine = true; /// <summary> /// use this if IRawConsole is null; /// </summary> private int _fallbackRawConsoleColumnNumber = 80; /// <summary> /// use this if IRawConsole is null; /// </summary> private int _fallbackRawConsoleRowNumber = 40; private WriteLineHelper _writeLineHelper; /// <summary> /// handler to prompt the user for page breaks /// if this handler is not null, we have promting /// </summary> private PromptHandler _prompt = null; /// <summary> /// conter for the # of lines written when prompting is on /// </summary> private long _linesWritten = 0; /// <summary> /// flag to avoid renetrancy on promting /// </summary> private bool _disableLineWrittenEvent = false; /// <summary> /// refecence to the PSHostUserInterface interface we use /// </summary> private PSHostUserInterface _console = null; /// <summary> /// Msh host specific string manipulation helper /// </summary> private DisplayCells _displayCellsPSHost; /// <summary> /// reference to error context to throw Msh exceptions /// </summary> private TerminatingErrorContext _errorContext = null; #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Net; using System.Text.RegularExpressions; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API.Requests.Responses; using osuTK; using osuTK.Graphics; using APIUser = osu.Game.Online.API.Requests.Responses.APIUser; namespace osu.Game.Overlays.Changelog { public class ChangelogEntry : FillFlowContainer { private readonly APIChangelogEntry entry; [Resolved] private OsuColour colours { get; set; } [Resolved] private OverlayColourProvider colourProvider { get; set; } private FontUsage fontLarge; private FontUsage fontMedium; public ChangelogEntry(APIChangelogEntry entry) { this.entry = entry; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Direction = FillDirection.Vertical; } [BackgroundDependencyLoader] private void load() { fontLarge = OsuFont.GetFont(size: 16); fontMedium = OsuFont.GetFont(size: 12); Children = new[] { createTitle(), createMessage() }; } private Drawable createTitle() { var entryColour = entry.Major ? colours.YellowLight : Color4.White; LinkFlowContainer title; var titleContainer = new Container { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Margin = new MarginPadding { Vertical = 5 }, Children = new Drawable[] { new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreRight, Size = new Vector2(10), Icon = getIconForChangelogEntry(entry.Type), Colour = entryColour.Opacity(0.5f), Margin = new MarginPadding { Right = 5 }, }, title = new LinkFlowContainer { Direction = FillDirection.Full, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, TextAnchor = Anchor.BottomLeft, } } }; title.AddText(entry.Title, t => { t.Font = fontLarge; t.Colour = entryColour; }); if (!string.IsNullOrEmpty(entry.Repository)) addRepositoryReference(title, entryColour); if (entry.GithubUser != null) addGithubAuthorReference(title, entryColour); return titleContainer; } private void addRepositoryReference(LinkFlowContainer title, Color4 entryColour) { title.AddText(" (", t => { t.Font = fontLarge; t.Colour = entryColour; }); title.AddLink($"{entry.Repository.Replace("ppy/", "")}#{entry.GithubPullRequestId}", entry.GithubUrl, t => { t.Font = fontLarge; t.Colour = entryColour; }); title.AddText(")", t => { t.Font = fontLarge; t.Colour = entryColour; }); } private void addGithubAuthorReference(LinkFlowContainer title, Color4 entryColour) { title.AddText("by ", t => { t.Font = fontMedium; t.Colour = entryColour; t.Padding = new MarginPadding { Left = 10 }; }); if (entry.GithubUser.UserId != null) { title.AddUserLink(new APIUser { Username = entry.GithubUser.OsuUsername, Id = entry.GithubUser.UserId.Value }, t => { t.Font = fontMedium; t.Colour = entryColour; }); } else if (entry.GithubUser.GithubUrl != null) { title.AddLink(entry.GithubUser.DisplayName, entry.GithubUser.GithubUrl, t => { t.Font = fontMedium; t.Colour = entryColour; }); } else { title.AddText(entry.GithubUser.DisplayName, t => { t.Font = fontMedium; t.Colour = entryColour; }); } } private Drawable createMessage() { if (string.IsNullOrEmpty(entry.MessageHtml)) return Empty(); var message = new TextFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, }; // todo: use markdown parsing once API returns markdown message.AddText(WebUtility.HtmlDecode(Regex.Replace(entry.MessageHtml, @"<(.|\n)*?>", string.Empty)), t => { t.Font = fontMedium; t.Colour = colourProvider.Foreground1; }); return message; } private static IconUsage getIconForChangelogEntry(ChangelogEntryType entryType) { // compare: https://github.com/ppy/osu-web/blob/master/resources/assets/coffee/react/_components/changelog-entry.coffee#L8-L11 switch (entryType) { case ChangelogEntryType.Add: return FontAwesome.Solid.Plus; case ChangelogEntryType.Fix: return FontAwesome.Solid.Check; case ChangelogEntryType.Misc: return FontAwesome.Regular.Circle; default: throw new ArgumentOutOfRangeException(nameof(entryType), $"Unrecognised entry type {entryType}"); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Generic; using System.Xml; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Host; using System.Globalization; using System.Text; #if CORECLR // Use stubs for SystemException using Microsoft.PowerShell.CoreClr.Stubs; #endif /* SUMMARY: this file contains a general purpose, reusable framework for loading XML files, and do data validation. It provides the capability of: * logging errors, warnings and traces to a file or in memory * managing the XML dom traversal using an add hoc stack frame management scheme * validating common error condotions (e.g. missing node or unknown node) */ namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// base exception to be used for all the exceptions that this framework will generate /// </summary> internal abstract class TypeInfoDataBaseLoaderException : SystemException { } /// <summary> /// exception thrown by the loader when the maximum number of errors is exceeded /// </summary> internal class TooManyErrorsException : TypeInfoDataBaseLoaderException { /// <summary> /// error count that triggered the exception /// </summary> internal int errorCount; } /// <summary> /// entry logged by the loader and made available to external consumers /// </summary> internal class XmlLoaderLoggerEntry { internal enum EntryType { Error, Trace }; /// <summary> /// type of information being logged /// </summary> internal EntryType entryType; /// <summary> /// path of the file the info refers to /// </summary> internal string filePath = null; /// <summary> /// XPath location inside the file /// </summary> internal string xPath = null; /// <summary> /// message to be displayed to the user /// </summary> internal string message = null; /// <summary> /// indicate whether we fail to load the file due to the security reason /// </summary> internal bool failToLoadFile = false; } /// <summary> /// logger object used by the loader (class XmlLoaderBase) to write log entries. /// It logs to a memory buffer and (optionally) to a text file /// </summary> internal class XmlLoaderLogger : IDisposable { #region tracer //PSS/end-user tracer [TraceSource("FormatFileLoading", "Loading format files")] private static PSTraceSource s_formatFileLoadingtracer = PSTraceSource.GetTracer("FormatFileLoading", "Loading format files", false); #endregion tracer /// <summary> /// log an entry /// </summary> /// <param name="entry">entry to log</param> internal void LogEntry(XmlLoaderLoggerEntry entry) { if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) _hasErrors = true; if (_saveInMemory) _entries.Add(entry); if ((s_formatFileLoadingtracer.Options | PSTraceSourceOptions.WriteLine) != 0) WriteToTracer(entry); } private void WriteToTracer(XmlLoaderLoggerEntry entry) { if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) { s_formatFileLoadingtracer.WriteLine("ERROR:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message); } else if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Trace) { s_formatFileLoadingtracer.WriteLine("TRACE:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message); } } /// <summary> /// IDisposable implementation /// </summary> /// <remarks>This method calls GC.SuppressFinalize</remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { } } internal List<XmlLoaderLoggerEntry> LogEntries { get { return _entries; } } internal bool HasErrors { get { return _hasErrors; } } /// <summary> /// if true, log entries to memory /// </summary> private bool _saveInMemory = true; /// <summary> /// list of entries logged if saveInMemory is true /// </summary> private List<XmlLoaderLoggerEntry> _entries = new List<XmlLoaderLoggerEntry>(); /// <summary> /// true if we ever logged an error /// </summary> private bool _hasErrors = false; } /// <summary> /// base class providing XML loading basic functionality (stack management and logging facilities) /// NOTE: you need to implement to load an actual XML document and traverse it as see fit /// </summary> internal abstract class XmlLoaderBase : IDisposable { #region tracer [TraceSource("XmlLoaderBase", "XmlLoaderBase")] private static PSTraceSource s_tracer = PSTraceSource.GetTracer("XmlLoaderBase", "XmlLoaderBase"); #endregion tracer /// <summary> /// class representing a stack frame for the XML document tree traversal /// </summary> private sealed class XmlLoaderStackFrame : IDisposable { internal XmlLoaderStackFrame(XmlLoaderBase loader, XmlNode n, int index) { _loader = loader; this.node = n; this.index = index; } /// <summary> /// IDisposable implementation /// </summary> public void Dispose() { if (_loader != null) { _loader.RemoveStackFrame(); _loader = null; } } /// <summary> /// back pointer to the loader, used to pop a stack frame /// </summary> private XmlLoaderBase _loader; /// <summary> /// node the stack frame refers to /// </summary> internal XmlNode node; /// <summary> /// node index for enumerations, valid only if != -1 /// NOTE: this allows to express the XPath construct "foo[0]" /// </summary> internal int index = -1; } /// <summary> /// IDisposable implementation /// </summary> /// <remarks>This method calls GC.SuppressFinalize</remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_logger != null) { _logger.Dispose(); _logger = null; } } } /// <summary> /// get the list of logg entries /// </summary> /// <value>list of entries logged during a load</value> internal List<XmlLoaderLoggerEntry> LogEntries { get { return _logger.LogEntries; } } /// <summary> /// check if there were errors /// </summary> /// <value>true of the log entry list has errors</value> internal bool HasErrors { get { return _logger.HasErrors; } } /// <summary> /// to be called when starting a stack frame. /// The returned IDisposable should be used in a using(){...} block /// </summary> /// <param name="n">node to push on the stack</param> /// <returns>object to dispose when exiting the frame</returns> protected IDisposable StackFrame(XmlNode n) { return StackFrame(n, -1); } /// <summary> /// to be called when starting a stack frame. /// The returned IDisposable should be used in a using(){...} block /// </summary> /// <param name="n">node to push on the stack</param> /// <param name="index">index of the node of the same name in a collection</param> /// <returns>object to dispose when exiting the frame</returns> protected IDisposable StackFrame(XmlNode n, int index) { XmlLoaderStackFrame sf = new XmlLoaderStackFrame(this, n, index); _executionStack.Push(sf); if (_logStackActivity) WriteStackLocation("Enter"); return sf; } /// <summary> /// called by the Dispose code of the XmlLoaderStackFrame object /// to pop a frame off the stack /// </summary> private void RemoveStackFrame() { if (_logStackActivity) WriteStackLocation("Exit"); _executionStack.Pop(); } protected void ProcessUnknownNode(XmlNode n) { if (IsFilteredOutNode(n)) return; ReportIllegalXmlNode(n); } protected void ProcessUnknownAttribute(XmlAttribute a) { ReportIllegalXmlAttribute(a); } protected static bool IsFilteredOutNode(XmlNode n) { return (n is XmlComment || n is XmlWhitespace); } protected bool VerifyNodeHasNoChildren(XmlNode n) { if (n.ChildNodes.Count == 0) return true; if (n.ChildNodes.Count == 1) { if (n.ChildNodes[0] is XmlText) return true; } //Error at XPath {0} in file {1}: Node {2} cannot have children. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoChildrenAllowed, ComputeCurrentXPath(), FilePath, n.Name)); return false; } internal string GetMandatoryInnerText(XmlNode n) { if (String.IsNullOrEmpty(n.InnerText)) { this.ReportEmptyNode(n); return null; } return n.InnerText; } internal string GetMandatoryAttributeValue(XmlAttribute a) { if (String.IsNullOrEmpty(a.Value)) { this.ReportEmptyAttribute(a); return null; } return a.Value; } /// <summary> /// helper to compare node names, e.g. "foo" in <foo/> /// it uses case sensitive, culture invariant compare. /// This is because XML tags are case sensitive. /// </summary> /// <param name="n">XmlNode whose name is to compare</param> /// <param name="s">string to compare the node name to</param> /// <param name="allowAttributes">if true, accept the presence of attributes on the node</param> /// <returns>true if there is a match</returns> private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) { bool match = false; if (String.Equals(n.Name, s, StringComparison.Ordinal)) { // we have a case sensitive match match = true; } else if (String.Equals(n.Name, s, StringComparison.OrdinalIgnoreCase)) { // try a case insensitive match // we differ only in case: flag this as an ERROR for the time being // and accept the comparison string fmtString = "XML tag differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, n.Name, s)); match = true; } if (match && !allowAttributes) { XmlElement e = n as XmlElement; if (e != null && e.Attributes.Count > 0) { //Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes. ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name)); } } return match; } internal bool MatchNodeNameWithAttributes(XmlNode n, string s) { return MatchNodeNameHelper(n, s, true); } internal bool MatchNodeName(XmlNode n, string s) { return MatchNodeNameHelper(n, s, false); } internal bool MatchAttributeName(XmlAttribute a, string s) { if (String.Equals(a.Name, s, StringComparison.Ordinal)) { // we have a case sensitive match return true; } else if (String.Equals(a.Name, s, StringComparison.OrdinalIgnoreCase)) { // try a case insensitive match // we differ only in case: flag this as an ERROR for the time being // and accept the comparison string fmtString = "XML attribute differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, a.Name, s)); return true; } return false; } internal void ProcessDuplicateNode(XmlNode n) { //Error at XPath {0} in file {1}: Duplicated node. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.DuplicatedNode, ComputeCurrentXPath(), FilePath), XmlLoaderLoggerEntry.EntryType.Error); } internal void ProcessDuplicateAlternateNode(string node1, string node2) { //Error at XPath {0} in file {1}: {2} and {3} are mutually exclusive. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MutuallyExclusiveNode, ComputeCurrentXPath(), FilePath, node1, node2), XmlLoaderLoggerEntry.EntryType.Error); } internal void ProcessDuplicateAlternateNode(XmlNode n, string node1, string node2) { //Error at XPath {0} in file {1}: {2}, {3} and {4} are mutually exclusive. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.ThreeMutuallyExclusiveNode, ComputeCurrentXPath(), FilePath, n.Name, node1, node2), XmlLoaderLoggerEntry.EntryType.Error); } private void ReportIllegalXmlNode(XmlNode n) { //UnknownNode=Error at XPath {0} in file {1}: {2} is an unknown node. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.UnknownNode, ComputeCurrentXPath(), FilePath, n.Name), XmlLoaderLoggerEntry.EntryType.Error); } private void ReportIllegalXmlAttribute(XmlAttribute a) { //Error at XPath {0} in file {1}: {2} is an unknown attribute. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.UnknownAttribute, ComputeCurrentXPath(), FilePath, a.Name), XmlLoaderLoggerEntry.EntryType.Error); } protected void ReportMissingAttribute(string name) { //Error at XPath {0} in file {1}: {2} is a missing attribute. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingAttribute, ComputeCurrentXPath(), FilePath, name), XmlLoaderLoggerEntry.EntryType.Error); } protected void ReportMissingNode(string name) { //Error at XPath {0} in file {1}: Missing Node {2}. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, name), XmlLoaderLoggerEntry.EntryType.Error); } protected void ReportMissingNodes(string[] names) { //Error at XPath {0} in file {1}: Missing Node from {2}. string namesString = string.Join(", ", names); ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNodeFromList, ComputeCurrentXPath(), FilePath, namesString), XmlLoaderLoggerEntry.EntryType.Error); } protected void ReportEmptyNode(XmlNode n) { //Error at XPath {0} in file {1}: {2} is an empty node. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.EmptyNode, ComputeCurrentXPath(), FilePath, n.Name), XmlLoaderLoggerEntry.EntryType.Error); } protected void ReportEmptyAttribute(XmlAttribute a) { //EmptyAttribute=Error at XPath {0} in file {1}: {2} is an empty attribute. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.EmptyAttribute, ComputeCurrentXPath(), FilePath, a.Name), XmlLoaderLoggerEntry.EntryType.Error); } /// <summary> /// For tracing purposes only, don't add to log /// </summary> /// <param name="message"> /// trace message, non-localized string is OK. /// </param> protected void ReportTrace(string message) { ReportLogEntryHelper(message, XmlLoaderLoggerEntry.EntryType.Trace); } protected void ReportError(string message) { ReportLogEntryHelper(message, XmlLoaderLoggerEntry.EntryType.Error); } private void ReportLogEntryHelper(string message, XmlLoaderLoggerEntry.EntryType entryType, bool failToLoadFile = false) { string currentPath = ComputeCurrentXPath(); XmlLoaderLoggerEntry entry = new XmlLoaderLoggerEntry(); entry.entryType = entryType; entry.filePath = this.FilePath; entry.xPath = currentPath; entry.message = message; if (failToLoadFile) { System.Management.Automation.Diagnostics.Assert(entryType == XmlLoaderLoggerEntry.EntryType.Error, "the entry type should be 'error' when a file cannot be loaded"); entry.failToLoadFile = true; } _logger.LogEntry(entry); if (entryType == XmlLoaderLoggerEntry.EntryType.Error) { _currentErrorCount++; if (_currentErrorCount >= _maxNumberOfErrors) { // we have to log a last error and then bail if (_maxNumberOfErrors > 1) { XmlLoaderLoggerEntry lastEntry = new XmlLoaderLoggerEntry(); lastEntry.entryType = XmlLoaderLoggerEntry.EntryType.Error; lastEntry.filePath = this.FilePath; lastEntry.xPath = currentPath; lastEntry.message = StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyErrors, FilePath); _logger.LogEntry(lastEntry); _currentErrorCount++; } // NOTE: this exception is an internal one, and it is caught // internally by the calling code. TooManyErrorsException e = new TooManyErrorsException(); e.errorCount = _currentErrorCount; throw e; } } } /// <summary> /// Report error when loading formatting data from object model /// </summary> /// <param name="message"></param> /// <param name="typeName"></param> protected void ReportErrorForLoadingFromObjectModel(string message, string typeName) { XmlLoaderLoggerEntry entry = new XmlLoaderLoggerEntry(); entry.entryType = XmlLoaderLoggerEntry.EntryType.Error; entry.message = message; _logger.LogEntry(entry); _currentErrorCount++; if (_currentErrorCount >= _maxNumberOfErrors) { // we have to log a last error and then bail if (_maxNumberOfErrors > 1) { XmlLoaderLoggerEntry lastEntry = new XmlLoaderLoggerEntry(); lastEntry.entryType = XmlLoaderLoggerEntry.EntryType.Error; lastEntry.message = StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyErrorsInFormattingData, typeName); _logger.LogEntry(lastEntry); _currentErrorCount++; } // NOTE: this exception is an internal one, and it is caught // internally by the calling code. TooManyErrorsException e = new TooManyErrorsException(); e.errorCount = _currentErrorCount; throw e; } } private void WriteStackLocation(string label) { ReportTrace(label); } protected string ComputeCurrentXPath() { StringBuilder path = new StringBuilder(); foreach (XmlLoaderStackFrame sf in _executionStack) { path.Insert(0, "/"); if (sf.index != -1) { path.Insert(1, string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", sf.node.Name, sf.index + 1)); } else { path.Insert(1, sf.node.Name); } } return path.Length > 0 ? path.ToString() : null; } #region helpers for loading XML documents protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager authorizationManager, PSHost host, out bool isFullyTrusted) { // get file contents ExternalScriptInfo ps1xmlInfo = new ExternalScriptInfo(FilePath, FilePath); string fileContents = ps1xmlInfo.ScriptContents; isFullyTrusted = false; if (ps1xmlInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) { isFullyTrusted = true; } if (authorizationManager != null) { try { authorizationManager.ShouldRunInternal(ps1xmlInfo, CommandOrigin.Internal, host); } catch (PSSecurityException reason) { string errorMessage = StringUtil.Format(TypesXmlStrings.ValidationException, string.Empty /* TODO/FIXME snapin */, FilePath, reason.Message); ReportLogEntryHelper(errorMessage, XmlLoaderLoggerEntry.EntryType.Error, failToLoadFile: true); return null; } } // load file into XML document try { XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( fileContents, true, /* preserve whitespace, comments, etc. */ null); /* default maxCharacters */ this.ReportTrace("XmlDocument loaded OK"); return doc; } catch (XmlException e) { this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, FilePath, e.Message)); this.ReportTrace("XmlDocument discarded"); return null; } catch (Exception e) // will rethrow { CommandProcessor.CheckForSevereException(e); throw; } } #endregion /// <summary> /// file system path for the file we are loading from /// </summary> /// protected string FilePath { get { return _loadingInfo.filePath; } } protected void SetDatabaseLoadingInfo(XmlFileLoadInfo info) { _loadingInfo.fileDirectory = info.fileDirectory; _loadingInfo.filePath = info.filePath; } protected void SetLoadingInfoIsFullyTrusted(bool isFullyTrusted) { _loadingInfo.isFullyTrusted = isFullyTrusted; } protected void SetLoadingInfoIsProductCode(bool isProductCode) { _loadingInfo.isProductCode = isProductCode; } private DatabaseLoadingInfo _loadingInfo = new DatabaseLoadingInfo(); protected DatabaseLoadingInfo LoadingInfo { get { DatabaseLoadingInfo info = new DatabaseLoadingInfo(); info.filePath = _loadingInfo.filePath; info.fileDirectory = _loadingInfo.fileDirectory; info.isFullyTrusted = _loadingInfo.isFullyTrusted; info.isProductCode = _loadingInfo.isProductCode; return info; } } protected MshExpressionFactory expressionFactory; protected DisplayResourceManagerCache displayResourceManagerCache; internal bool VerifyStringResources { get; } = true; private int _maxNumberOfErrors = 30; private int _currentErrorCount = 0; private bool _logStackActivity = false; private Stack<XmlLoaderStackFrame> _executionStack = new Stack<XmlLoaderStackFrame>(); private XmlLoaderLogger _logger = new XmlLoaderLogger(); } }
namespace Azure.Messaging.EventHubs { public partial class EventData { public EventData(System.ReadOnlyMemory<byte> eventBody) { } protected EventData(System.ReadOnlyMemory<byte> eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { } public System.ReadOnlyMemory<byte> Body { get { throw null; } } public System.IO.Stream BodyAsStream { get { throw null; } } public System.DateTimeOffset EnqueuedTime { get { throw null; } } public long Offset { get { throw null; } } public string PartitionKey { get { throw null; } } public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public long SequenceNumber { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, object> SystemProperties { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnection : System.IAsyncDisposable { protected EventHubConnection() { } public EventHubConnection(string connectionString) { } public EventHubConnection(string connectionString, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public EventHubConnection(string connectionString, string eventHubName) { } public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { } public EventHubConnection(string connectionString, string eventHubName, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnectionOptions { public EventHubConnectionOptions() { } public System.Net.IWebProxy Proxy { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsTransportType TransportType { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProperties { protected internal EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { } public System.DateTimeOffset CreatedOn { get { throw null; } } public string Name { get { throw null; } } public string[] PartitionIds { get { throw null; } } } public partial class EventHubsException : System.Exception { public EventHubsException(bool isTransient, string eventHubName) { } public EventHubsException(bool isTransient, string eventHubName, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason, System.Exception innerException) { } public EventHubsException(bool isTransient, string eventHubName, string message, System.Exception innerException) { } public EventHubsException(string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public string EventHubName { get { throw null; } } public bool IsTransient { get { throw null; } } public override string Message { get { throw null; } } public Azure.Messaging.EventHubs.EventHubsException.FailureReason Reason { get { throw null; } } public override string ToString() { throw null; } public enum FailureReason { GeneralError = 0, ClientClosed = 1, ConsumerDisconnected = 2, ResourceNotFound = 3, MessageSizeExceeded = 4, QuotaExceeded = 5, ServiceBusy = 6, ServiceTimeout = 7, ServiceCommunicationProblem = 8, } } public enum EventHubsRetryMode { Fixed = 0, Exponential = 1, } public partial class EventHubsRetryOptions { public EventHubsRetryOptions() { } public Azure.Messaging.EventHubs.EventHubsRetryPolicy CustomRetryPolicy { get { throw null; } set { } } public System.TimeSpan Delay { get { throw null; } set { } } public System.TimeSpan MaximumDelay { get { throw null; } set { } } public int MaximumRetries { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryMode Mode { get { throw null; } set { } } public System.TimeSpan TryTimeout { get { throw null; } set { } } } public abstract partial class EventHubsRetryPolicy { protected EventHubsRetryPolicy() { } public abstract System.TimeSpan? CalculateRetryDelay(System.Exception lastException, int attemptCount); public abstract System.TimeSpan CalculateTryTimeout(int attemptCount); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public enum EventHubsTransportType { AmqpTcp = 0, AmqpWebSockets = 1, } public partial class PartitionProperties { protected internal PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { } public long BeginningSequenceNumber { get { throw null; } } public string EventHubName { get { throw null; } } public string Id { get { throw null; } } public bool IsEmpty { get { throw null; } } public long LastEnqueuedOffset { get { throw null; } } public long LastEnqueuedSequenceNumber { get { throw null; } } public System.DateTimeOffset LastEnqueuedTime { get { throw null; } } } } namespace Azure.Messaging.EventHubs.Consumer { public partial class EventHubConsumerClient : System.IAsyncDisposable { public const string DefaultConsumerGroupName = "$Default"; protected EventHubConsumerClient() { } public EventHubConsumerClient(string consumerGroup, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString) { } public EventHubConsumerClient(string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName) { } public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(bool startReadingAtEarliestEvent, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions = null, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConsumerClientOptions { public EventHubConsumerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EventPosition : System.IEquatable<Azure.Messaging.EventHubs.Consumer.EventPosition> { private object _dummy; private int _dummyPrimitive; public static Azure.Messaging.EventHubs.Consumer.EventPosition Earliest { get { throw null; } } public static Azure.Messaging.EventHubs.Consumer.EventPosition Latest { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.EventPosition other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromEnqueuedTime(System.DateTimeOffset enqueuedTime) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromOffset(long offset, bool isInclusive = true) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromSequenceNumber(long sequenceNumber, bool isInclusive = true) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LastEnqueuedEventProperties : System.IEquatable<Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties> { public LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; } public System.DateTimeOffset? EnqueuedTime { get { throw null; } } public System.DateTimeOffset? LastReceivedTime { get { throw null; } } public long? Offset { get { throw null; } } public long? SequenceNumber { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionContext { protected internal PartitionContext(string partitionId) { } public string PartitionId { get { throw null; } } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct PartitionEvent { private object _dummy; private int _dummyPrimitive; public PartitionEvent(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data) { throw null; } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } } public partial class ReadEventOptions { public ReadEventOptions() { } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Primitives { public partial class EventProcessorCheckpoint { public EventProcessorCheckpoint() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition StartingPosition { get { throw null; } set { } } } public partial class EventProcessorOptions { public EventProcessorOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public System.TimeSpan LoadBalancingUpdateInterval { get { throw null; } set { } } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public System.TimeSpan PartitionOwnershipExpirationInterval { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventProcessorPartition { public EventProcessorPartition() { } public string PartitionId { get { throw null; } protected internal set { } } } public partial class EventProcessorPartitionOwnership { public EventProcessorPartitionOwnership() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public System.DateTimeOffset LastModifiedTime { get { throw null; } set { } } public string OwnerIdentifier { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public string Version { get { throw null; } set { } } } public abstract partial class EventProcessor<TPartition> where TPartition : Azure.Messaging.EventHubs.Primitives.EventProcessorPartition, new() { protected EventProcessor() { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string Identifier { get { throw null; } } public bool IsRunning { get { throw null; } protected set { } } protected Azure.Messaging.EventHubs.EventHubsRetryPolicy RetryPolicy { get { throw null; } } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ClaimOwnershipAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership> desiredOwnership, System.Threading.CancellationToken cancellationToken); protected internal virtual Azure.Messaging.EventHubs.EventHubConnection CreateConnection() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint>> ListCheckpointsAsync(System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ListOwnershipAsync(System.Threading.CancellationToken cancellationToken); protected virtual System.Threading.Tasks.Task OnInitializingPartitionAsync(TPartition partition, System.Threading.CancellationToken cancellationToken) { throw null; } protected virtual System.Threading.Tasks.Task OnPartitionProcessingStoppedAsync(TPartition partition, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken) { throw null; } protected abstract System.Threading.Tasks.Task OnProcessingErrorAsync(System.Exception exception, TPartition partition, string operationDescription, System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task OnProcessingEventBatchAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> events, TPartition partition, System.Threading.CancellationToken cancellationToken); protected virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties(string partitionId) { throw null; } public virtual void StartProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StartProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual void StopProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StopProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiver : System.IAsyncDisposable { protected PartitionReceiver() { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition InitialPosition { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public string PartitionId { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.TimeSpan maximumWaitTime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiverOptions { public PartitionReceiverOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public System.TimeSpan? DefaultMaximumReceiveWaitTime { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Processor { public partial class PartitionClosingEventArgs { public PartitionClosingEventArgs(string partitionId, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public string PartitionId { get { throw null; } } public Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason Reason { get { throw null; } } } public partial class PartitionInitializingEventArgs { public PartitionInitializingEventArgs(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition defaultStartingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessErrorEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessErrorEventArgs(string partitionId, string operation, System.Exception exception, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public System.Exception Exception { get { throw null; } } public string Operation { get { throw null; } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessEventArgs(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task> updateCheckpointImplementation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public bool HasEvent { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } public System.Threading.Tasks.Task UpdateCheckpointAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public enum ProcessingStoppedReason { Shutdown = 0, OwnershipLost = 1, } } namespace Azure.Messaging.EventHubs.Producer { public partial class CreateBatchOptions : Azure.Messaging.EventHubs.Producer.SendEventOptions { public CreateBatchOptions() { } public long? MaximumSizeInBytes { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public sealed partial class EventDataBatch : System.IDisposable { internal EventDataBatch() { } public int Count { get { throw null; } } public long MaximumSizeInBytes { get { throw null; } } public long SizeInBytes { get { throw null; } } public void Dispose() { } public bool TryAdd(Azure.Messaging.EventHubs.EventData eventData) { throw null; } } public partial class EventHubProducerClient : System.IAsyncDisposable { protected EventHubProducerClient() { } public EventHubProducerClient(Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString) { } public EventHubProducerClient(string connectionString, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public EventHubProducerClient(string connectionString, string eventHubName) { } public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString, string eventHubName, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(Azure.Messaging.EventHubs.Producer.CreateBatchOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(Azure.Messaging.EventHubs.Producer.EventDataBatch eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, Azure.Messaging.EventHubs.Producer.SendEventOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProducerClientOptions { public EventHubProducerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class SendEventOptions { public SendEventOptions() { } public string PartitionId { get { throw null; } set { } } public string PartitionKey { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Microsoft.Extensions.Azure { public static partial class EventHubClientBuilderExtensions { public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClientWithNamespace<TBuilder>(this TBuilder builder, string consumerGroup, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClientWithNamespace<TBuilder>(this TBuilder builder, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Client; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the CandidatesLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in CandidatesLogicBase by making a partial class of CandidatesLogic // and overriding the base methods. namespace VotingInfo.Database.Logic.Client { public partial class CandidatesLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldCandidateId ) { return (new CandidatesLogic()).Exists(fldCandidateId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { return (new CandidatesLogic()).Exists(fldCandidateId , connection, transaction); } /// <summary> /// Run Candidates_Search, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="fldSourceUrl">Value for SourceUrl</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SearchNow(string fldCandidateName , string fldSourceUrl ) { var driver = new CandidatesLogic(); driver.Search(fldCandidateName , fldSourceUrl ); return driver.Results; } /// <summary> /// Run Candidates_Search, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="fldSourceUrl">Value for SourceUrl</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SearchNow(string fldCandidateName , string fldSourceUrl , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidatesLogic(); driver.Search(fldCandidateName , fldSourceUrl , connection, transaction); return driver.Results; } /// <summary> /// Run Candidates_SelectAll, and return results as a list of CandidatesRow. /// </summary> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectAllNow() { var driver = new CandidatesLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run Candidates_SelectAll, and return results as a list of CandidatesRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new CandidatesLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_CandidateId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_CandidateIdNow(int fldCandidateId ) { var driver = new CandidatesLogic(); driver.SelectBy_CandidateId(fldCandidateId ); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_CandidateId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_CandidateIdNow(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidatesLogic(); driver.SelectBy_CandidateId(fldCandidateId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_ContentInspectionId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId ) { var driver = new CandidatesLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId ); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_ContentInspectionId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidatesLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_OrganizationId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_OrganizationIdNow(int fldOrganizationId ) { var driver = new CandidatesLogic(); driver.SelectBy_OrganizationId(fldOrganizationId ); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_OrganizationId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_OrganizationIdNow(int fldOrganizationId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidatesLogic(); driver.SelectBy_OrganizationId(fldOrganizationId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_ProposedByUserId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldProposedByUserId">Value for ProposedByUserId</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_ProposedByUserIdNow(int fldProposedByUserId ) { var driver = new CandidatesLogic(); driver.SelectBy_ProposedByUserId(fldProposedByUserId ); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_ProposedByUserId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldProposedByUserId">Value for ProposedByUserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_ProposedByUserIdNow(int fldProposedByUserId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidatesLogic(); driver.SelectBy_ProposedByUserId(fldProposedByUserId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_ConfirmedByUserId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_ConfirmedByUserIdNow(int fldConfirmedByUserId ) { var driver = new CandidatesLogic(); driver.SelectBy_ConfirmedByUserId(fldConfirmedByUserId ); return driver.Results; } /// <summary> /// Run Candidates_SelectBy_ConfirmedByUserId, and return results as a list of CandidatesRow. /// </summary> /// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidatesRow.</returns> public static List<CandidatesContract> SelectBy_ConfirmedByUserIdNow(int fldConfirmedByUserId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidatesLogic(); driver.SelectBy_ConfirmedByUserId(fldConfirmedByUserId , connection, transaction); return driver.Results; } /// <summary> /// Read all Candidates rows from the provided reader into the list structure of CandidatesRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated CandidatesRows or an empty CandidatesRows if there are no results.</returns> public static List<CandidatesContract> ReadAllNow(SqlDataReader reader) { var driver = new CandidatesLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a Candidates /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A Candidates or null if there are no results.</returns> public static CandidatesContract ReadOneNow(SqlDataReader reader) { var driver = new CandidatesLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } } }
namespace System.Reflection.Metadata.ILReader { public partial class ILReaderImpl { internal static unsafe Instruction[] DecodingPass(BlobReader reader, FirstPassInfo info, IILBodyReaderAllocator allocator) { var count = info.InstructionsCount; var array = allocator.AllocateInstructionsArray(count); var jumps = info.GetJumpsOrUnreachable(); var nextJumpIndex = 1; var nextJump = jumps[0]; fixed (Instruction* instructions = array) for (var index = 0; index < count; index++) { while (reader.Offset == nextJump.Target) // decode jumps { instructions[nextJump.Source].myOperand = index; //jumps[nextJumpIndex - 1] = new InstructionJump(index, nextJump.Source); nextJump = (nextJumpIndex < jumps.Count) ? jumps[nextJumpIndex] : InstructionJump.Unreachable; nextJumpIndex += 1; } switch (reader.ReadByte()) { case 0x00: // nop instructions[index].myCode = Opcode.Nop; continue; case 0x01: // break instructions[index].myCode = Opcode.Break; continue; case 0x02: // ldarg.0 instructions[index].myCode = Opcode.Ldarg; instructions[index].myOperand = 0; continue; case 0x03: // ldarg.1 instructions[index].myCode = Opcode.Ldarg; instructions[index].myOperand = 1; continue; case 0x04: // ldarg.2 instructions[index].myCode = Opcode.Ldarg; instructions[index].myOperand = 2; continue; case 0x05: // ldarg.3 instructions[index].myCode = Opcode.Ldarg; instructions[index].myOperand = 3; continue; case 0x06: // ldloc.0 instructions[index].myCode = Opcode.Ldloc; instructions[index].myOperand = 0; continue; case 0x07: // ldloc.1 instructions[index].myCode = Opcode.Ldloc; instructions[index].myOperand = 1; continue; case 0x08: // ldloc.2 instructions[index].myCode = Opcode.Ldloc; instructions[index].myOperand = 2; continue; case 0x09: // ldloc.3 instructions[index].myCode = Opcode.Ldloc; instructions[index].myOperand = 3; continue; case 0x0A: // stloc.0 instructions[index].myCode = Opcode.Stloc; instructions[index].myOperand = 0; continue; case 0x0B: // stloc.1 instructions[index].myCode = Opcode.Stloc; instructions[index].myOperand = 1; continue; case 0x0C: // stloc.2 instructions[index].myCode = Opcode.Stloc; instructions[index].myOperand = 2; continue; case 0x0D: // stloc.3 instructions[index].myCode = Opcode.Stloc; instructions[index].myOperand = 3; continue; case 0x0E: // ldarg.s instructions[index].myCode = Opcode.Ldarg; instructions[index].myOperand = reader.ReadByte(); continue; case 0x0F: // ldarga.s instructions[index].myCode = Opcode.Ldarga; instructions[index].myOperand = reader.ReadByte(); continue; case 0x10: // starg.s instructions[index].myCode = Opcode.Starg; instructions[index].myOperand = reader.ReadByte(); continue; case 0x11: // ldloc.s instructions[index].myCode = Opcode.Ldloc; instructions[index].myOperand = reader.ReadByte(); continue; case 0x12: // ldloca.s instructions[index].myCode = Opcode.Ldloca; instructions[index].myOperand = reader.ReadByte(); continue; case 0x13: // stloc.s instructions[index].myCode = Opcode.Stloc; instructions[index].myOperand = reader.ReadByte(); continue; case 0x14: // ldnull instructions[index].myCode = Opcode.Ldnull; continue; case 0x15: // ldc.i4.m1 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = -1; continue; case 0x16: // ldc.i4.0 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 0; continue; case 0x17: // ldc.i4.1 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 1; continue; case 0x18: // ldc.i4.2 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 2; continue; case 0x19: // ldc.i4.3 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 3; continue; case 0x1A: // ldc.i4.4 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 4; continue; case 0x1B: // ldc.i4.5 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 5; continue; case 0x1C: // ldc.i4.6 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 6; continue; case 0x1D: // ldc.i4.7 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 7; continue; case 0x1E: // ldc.i4.8 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = 8; continue; case 0x1F: // ldc.i4.s instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = reader.ReadByte(); continue; case 0x20: // ldc.i4 instructions[index].myCode = Opcode.LdcI4; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x21: // ldc.i8 instructions[index].myCode = Opcode.LdcI8; //instructions[index].myOperand = reader.ReadInt64(); reader.ReadInt64(); continue; case 0x22: // ldc.r4 instructions[index].myCode = Opcode.LdcR4; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x23: // ldc.r8 instructions[index].myCode = Opcode.LdcR8; // todo: bring back? // instructions[index].myOperand = reader.ReadInt64(); reader.ReadInt64(); continue; case 0x25: // dup instructions[index].myCode = Opcode.Dup; continue; case 0x26: // pop instructions[index].myCode = Opcode.Pop; continue; case 0x27: // jmp instructions[index].myCode = Opcode.Jmp; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x28: // call instructions[index].myCode = Opcode.Call; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x29: // calli instructions[index].myCode = Opcode.Calli; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x2A: // ret instructions[index].myCode = Opcode.Ret; continue; case 0x2B: // br.s instructions[index].myCode = Opcode.Br; reader.ReadSByte(); continue; case 0x2C: // brfalse.s instructions[index].myCode = Opcode.Brfalse; reader.ReadSByte(); continue; case 0x2D: // brtrue.s instructions[index].myCode = Opcode.Brtrue; reader.ReadSByte(); continue; case 0x2E: // beq.s instructions[index].myCode = Opcode.Beq; reader.ReadSByte(); continue; case 0x2F: // bge.s instructions[index].myCode = Opcode.Bge; reader.ReadSByte(); continue; case 0x30: // bgt.s instructions[index].myCode = Opcode.Bgt; reader.ReadSByte(); continue; case 0x31: // ble.s instructions[index].myCode = Opcode.Ble; reader.ReadSByte(); continue; case 0x32: // blt.s instructions[index].myCode = Opcode.Blt; reader.ReadSByte(); continue; case 0x33: // bne.un.s instructions[index].myCode = Opcode.BneUn; reader.ReadSByte(); continue; case 0x34: // bge.un.s instructions[index].myCode = Opcode.BgeUn; reader.ReadSByte(); continue; case 0x35: // bgt.un.s instructions[index].myCode = Opcode.BgtUn; reader.ReadSByte(); continue; case 0x36: // ble.un.s instructions[index].myCode = Opcode.BleUn; reader.ReadSByte(); continue; case 0x37: // blt.un.s instructions[index].myCode = Opcode.BltUn; reader.ReadSByte(); continue; case 0x38: // br instructions[index].myCode = Opcode.Br; reader.ReadInt32(); continue; case 0x39: // brfalse instructions[index].myCode = Opcode.Brfalse; reader.ReadInt32(); continue; case 0x3A: // brtrue instructions[index].myCode = Opcode.Brtrue; reader.ReadInt32(); continue; case 0x3B: // beq instructions[index].myCode = Opcode.Beq; reader.ReadInt32(); continue; case 0x3C: // bge instructions[index].myCode = Opcode.Bge; reader.ReadInt32(); continue; case 0x3D: // bgt instructions[index].myCode = Opcode.Bgt; reader.ReadInt32(); continue; case 0x3E: // ble instructions[index].myCode = Opcode.Ble; reader.ReadInt32(); continue; case 0x3F: // blt instructions[index].myCode = Opcode.Blt; reader.ReadInt32(); continue; case 0x40: // bne.un instructions[index].myCode = Opcode.BneUn; reader.ReadInt32(); continue; case 0x41: // bge.un instructions[index].myCode = Opcode.BgeUn; reader.ReadInt32(); continue; case 0x42: // bgt.un instructions[index].myCode = Opcode.BgtUn; reader.ReadInt32(); continue; case 0x43: // ble.un instructions[index].myCode = Opcode.BleUn; reader.ReadInt32(); continue; case 0x44: // blt.un instructions[index].myCode = Opcode.BltUn; reader.ReadInt32(); continue; case 0x45: // switch instructions[index].myCode = Opcode.Switch; var casesCount = reader.ReadInt32(); for (; casesCount > 0; casesCount--) reader.ReadInt32(); continue; case 0x46: // ldind.i1 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 1; continue; case 0x47: // ldind.u1 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 5; continue; case 0x48: // ldind.i2 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 2; continue; case 0x49: // ldind.u2 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 6; continue; case 0x4A: // ldind.i4 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 3; continue; case 0x4B: // ldind.u4 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 7; continue; case 0x4C: // ldind.i8 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 4; continue; case 0x4D: // ldind.i instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 0; continue; case 0x4E: // ldind.r4 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 9; continue; case 0x4F: // ldind.r8 instructions[index].myCode = Opcode.Ldind; instructions[index].myOperand = 10; continue; case 0x50: // ldind.ref instructions[index].myCode = Opcode.LdindRef; continue; case 0x51: // stind.ref instructions[index].myCode = Opcode.StindRef; continue; case 0x52: // stind.i1 instructions[index].myCode = Opcode.Stind; instructions[index].myOperand = 1; continue; case 0x53: // stind.i2 instructions[index].myCode = Opcode.Stind; instructions[index].myOperand = 2; continue; case 0x54: // stind.i4 instructions[index].myCode = Opcode.Stind; instructions[index].myOperand = 3; continue; case 0x55: // stind.i8 instructions[index].myCode = Opcode.Stind; instructions[index].myOperand = 4; continue; case 0x56: // stind.r4 instructions[index].myCode = Opcode.Stind; instructions[index].myOperand = 9; continue; case 0x57: // stind.r8 instructions[index].myCode = Opcode.Stind; instructions[index].myOperand = 10; continue; case 0x58: // add instructions[index].myCode = Opcode.Add; continue; case 0x59: // sub instructions[index].myCode = Opcode.Sub; continue; case 0x5A: // mul instructions[index].myCode = Opcode.Mul; continue; case 0x5B: // div instructions[index].myCode = Opcode.Div; continue; case 0x5C: // div.un instructions[index].myCode = Opcode.DivUn; continue; case 0x5D: // rem instructions[index].myCode = Opcode.Rem; continue; case 0x5E: // rem.un instructions[index].myCode = Opcode.RemUn; continue; case 0x5F: // and instructions[index].myCode = Opcode.And; continue; case 0x60: // or instructions[index].myCode = Opcode.Or; continue; case 0x61: // xor instructions[index].myCode = Opcode.Xor; continue; case 0x62: // shl instructions[index].myCode = Opcode.Shl; continue; case 0x63: // shr instructions[index].myCode = Opcode.Shr; continue; case 0x64: // shr.un instructions[index].myCode = Opcode.ShrUn; continue; case 0x65: // neg instructions[index].myCode = Opcode.Neg; continue; case 0x66: // not instructions[index].myCode = Opcode.Not; continue; case 0x67: // conv.i1 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 1; continue; case 0x68: // conv.i2 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 2; continue; case 0x69: // conv.i4 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 3; continue; case 0x6A: // conv.i8 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 4; continue; case 0x6B: // conv.r4 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 9; continue; case 0x6C: // conv.r8 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 10; continue; case 0x6D: // conv.u4 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 7; continue; case 0x6E: // conv.u8 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 8; continue; case 0x6F: // callvirt instructions[index].myCode = Opcode.Callvirt; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x70: // cpobj instructions[index].myCode = Opcode.Cpobj; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x71: // ldobj instructions[index].myCode = Opcode.Ldobj; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x72: // ldstr instructions[index].myCode = Opcode.Ldstr; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x73: // newobj instructions[index].myCode = Opcode.Newobj; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x74: // castclass instructions[index].myCode = Opcode.Castclass; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x75: // isinst instructions[index].myCode = Opcode.Isinst; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x76: // conv.r.un instructions[index].myCode = Opcode.ConvUn; instructions[index].myOperand = 9; continue; case 0x79: // unbox instructions[index].myCode = Opcode.Unbox; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x7A: // throw instructions[index].myCode = Opcode.Throw; continue; case 0x7B: // ldfld instructions[index].myCode = Opcode.Ldfld; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x7C: // ldflda instructions[index].myCode = Opcode.Ldflda; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x7D: // stfld instructions[index].myCode = Opcode.Stfld; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x7E: // ldsfld instructions[index].myCode = Opcode.Ldsfld; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x7F: // ldsflda instructions[index].myCode = Opcode.Ldsflda; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x80: // stsfld instructions[index].myCode = Opcode.Stsfld; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x81: // stobj instructions[index].myCode = Opcode.Stobj; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x82: // conv.ovf.i1.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 1; continue; case 0x83: // conv.ovf.i2.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 2; continue; case 0x84: // conv.ovf.i4.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 3; continue; case 0x85: // conv.ovf.i8.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 4; continue; case 0x86: // conv.ovf.u1.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 5; continue; case 0x87: // conv.ovf.u2.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 6; continue; case 0x88: // conv.ovf.u4.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 7; continue; case 0x89: // conv.ovf.u8.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 8; continue; case 0x8A: // conv.ovf.i.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 0; continue; case 0x8B: // conv.ovf.u.un instructions[index].myCode = Opcode.ConvOvfUn; instructions[index].myOperand = 11; continue; case 0x8C: // box instructions[index].myCode = Opcode.Box; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x8D: // newarr instructions[index].myCode = Opcode.Newarr; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x8E: // ldlen instructions[index].myCode = Opcode.Ldlen; continue; case 0x8F: // ldelema instructions[index].myCode = Opcode.Ldelema; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x90: // ldelem.i1 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 1; continue; case 0x91: // ldelem.u1 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 5; continue; case 0x92: // ldelem.i2 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 2; continue; case 0x93: // ldelem.u2 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 6; continue; case 0x94: // ldelem.i4 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 3; continue; case 0x95: // ldelem.u4 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 7; continue; case 0x96: // ldelem.i8 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 4; continue; case 0x97: // ldelem.i instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 0; continue; case 0x98: // ldelem.r4 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 9; continue; case 0x99: // ldelem.r8 instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = 10; continue; case 0x9A: // ldelem.ref instructions[index].myCode = Opcode.LdelemRef; continue; case 0x9B: // stelem.i instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = 0; continue; case 0x9C: // stelem.i1 instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = 1; continue; case 0x9D: // stelem.i2 instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = 2; continue; case 0x9E: // stelem.i4 instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = 3; continue; case 0x9F: // stelem.i8 instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = 4; continue; case 0xA0: // stelem.r4 instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = 9; continue; case 0xA1: // stelem.r8 instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = 10; continue; case 0xA2: // stelem.ref instructions[index].myCode = Opcode.StelemRef; continue; case 0xA3: // ldelem instructions[index].myCode = Opcode.Ldelem; instructions[index].myOperand = reader.ReadInt32(); continue; case 0xA4: // stelem instructions[index].myCode = Opcode.Stelem; instructions[index].myOperand = reader.ReadInt32(); continue; case 0xA5: // unbox.any instructions[index].myCode = Opcode.UnboxAny; instructions[index].myOperand = reader.ReadInt32(); continue; case 0xB3: // conv.ovf.i1 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 1; continue; case 0xB4: // conv.ovf.u1 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 5; continue; case 0xB5: // conv.ovf.i2 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 2; continue; case 0xB6: // conv.ovf.u2 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 6; continue; case 0xB7: // conv.ovf.i4 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 3; continue; case 0xB8: // conv.ovf.u4 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 7; continue; case 0xB9: // conv.ovf.i8 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 4; continue; case 0xBA: // conv.ovf.u8 instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 8; continue; case 0xC2: // refanyval instructions[index].myCode = Opcode.Refanyval; instructions[index].myOperand = reader.ReadInt32(); continue; case 0xC3: // ckfinite instructions[index].myCode = Opcode.Ckfinite; continue; case 0xC6: // mkrefany instructions[index].myCode = Opcode.Mkrefany; instructions[index].myOperand = reader.ReadInt32(); continue; case 0xD0: // ldtoken instructions[index].myCode = Opcode.Ldtoken; instructions[index].myOperand = reader.ReadInt32(); continue; case 0xD1: // conv.u2 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 6; continue; case 0xD2: // conv.u1 instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 5; continue; case 0xD3: // conv.i instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 0; continue; case 0xD4: // conv.ovf.i instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 0; continue; case 0xD5: // conv.ovf.u instructions[index].myCode = Opcode.ConvOvf; instructions[index].myOperand = 11; continue; case 0xD6: // add.ovf instructions[index].myCode = Opcode.AddOvf; continue; case 0xD7: // add.ovf.un instructions[index].myCode = Opcode.AddOvfUn; continue; case 0xD8: // mul.ovf instructions[index].myCode = Opcode.MulOvf; continue; case 0xD9: // mul.ovf.un instructions[index].myCode = Opcode.MulOvfUn; continue; case 0xDA: // sub.ovf instructions[index].myCode = Opcode.SubOvf; continue; case 0xDB: // sub.ovf.un instructions[index].myCode = Opcode.SubOvfUn; continue; case 0xDC: // endfinally instructions[index].myCode = Opcode.Endfinally; continue; case 0xDD: // leave instructions[index].myCode = Opcode.Leave; reader.ReadInt32(); continue; case 0xDE: // leave.s instructions[index].myCode = Opcode.Leave; reader.ReadSByte(); continue; case 0xDF: // stind.i instructions[index].myCode = Opcode.Stind; instructions[index].myOperand = 0; continue; case 0xE0: // conv.u instructions[index].myCode = Opcode.Conv; instructions[index].myOperand = 11; continue; case 0xF8: // prefix7 instructions[index].myCode = Opcode.Prefix7; continue; case 0xF9: // prefix6 instructions[index].myCode = Opcode.Prefix6; continue; case 0xFA: // prefix5 instructions[index].myCode = Opcode.Prefix5; continue; case 0xFB: // prefix4 instructions[index].myCode = Opcode.Prefix4; continue; case 0xFC: // prefix3 instructions[index].myCode = Opcode.Prefix3; continue; case 0xFD: // prefix2 instructions[index].myCode = Opcode.Prefix2; continue; case 0xFF: // prefixref instructions[index].myCode = Opcode.Prefixref; continue; case 0xFE: switch (reader.ReadByte()) { case 0x00: // arglist instructions[index].myCode = Opcode.Arglist; continue; case 0x01: // ceq instructions[index].myCode = Opcode.Ceq; continue; case 0x02: // cgt instructions[index].myCode = Opcode.Cgt; continue; case 0x03: // cgt.un instructions[index].myCode = Opcode.CgtUn; continue; case 0x04: // clt instructions[index].myCode = Opcode.Clt; continue; case 0x05: // clt.un instructions[index].myCode = Opcode.CltUn; continue; case 0x06: // ldftn instructions[index].myCode = Opcode.Ldftn; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x07: // ldvirtftn instructions[index].myCode = Opcode.Ldvirtftn; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x09: // ldarg instructions[index].myCode = Opcode.Ldarg; instructions[index].myOperand = reader.ReadInt16(); continue; case 0x0A: // ldarga instructions[index].myCode = Opcode.Ldarga; instructions[index].myOperand = reader.ReadInt16(); continue; case 0x0B: // starg instructions[index].myCode = Opcode.Starg; instructions[index].myOperand = reader.ReadInt16(); continue; case 0x0C: // ldloc instructions[index].myCode = Opcode.Ldloc; instructions[index].myOperand = reader.ReadInt16(); continue; case 0x0D: // ldloca instructions[index].myCode = Opcode.Ldloca; instructions[index].myOperand = reader.ReadInt16(); continue; case 0x0E: // stloc instructions[index].myCode = Opcode.Stloc; instructions[index].myOperand = reader.ReadInt16(); continue; case 0x0F: // localloc instructions[index].myCode = Opcode.Localloc; continue; case 0x11: // endfilter instructions[index].myCode = Opcode.Endfilter; continue; case 0x12: // unaligned. instructions[index].myCode = Opcode.Unaligned; instructions[index].myOperand = reader.ReadByte(); continue; case 0x13: // volatile. instructions[index].myCode = Opcode.Volatile; continue; case 0x14: // tail. instructions[index].myCode = Opcode.Tail; continue; case 0x15: // initobj instructions[index].myCode = Opcode.Initobj; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x16: // constrained. instructions[index].myCode = Opcode.Constrained; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x17: // cpblk instructions[index].myCode = Opcode.Cpblk; continue; case 0x18: // initblk instructions[index].myCode = Opcode.Initblk; continue; case 0x1A: // rethrow instructions[index].myCode = Opcode.Rethrow; continue; case 0x1C: // sizeof instructions[index].myCode = Opcode.Sizeof; instructions[index].myOperand = reader.ReadInt32(); continue; case 0x1D: // refanytype instructions[index].myCode = Opcode.Refanytype; continue; case 0x1E: // readonly. instructions[index].myCode = Opcode.Readonly; continue; default: continue; } default: continue; } } return array; } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UMA.AssetBundles; namespace UMA.CharacterSystem { public class DynamicAssetLoader : MonoBehaviour { static DynamicAssetLoader _instance; public bool makePersistent; [Space] [Tooltip("Set the server URL that assetbundles can be loaded from. Used in a live build and when the LocalAssetServer is turned off. Requires trailing slash but NO platform name")] public string remoteServerURL = ""; [Tooltip("Use the JSON version of the assetBundleIndex rather than the assetBundleVersion.")] public bool useJsonIndex = false; [Tooltip("Set the server URL for the AssetBundleIndex json data. You can use this to make a server request that could generate an index on the fly for example. Used in a live build and when the LocalAssetServer is turned off. TIP use [PLATFORM] to use the current platform name in the URL")] public string remoteServerIndexURL = ""; [Space] //EncryptedAssetBundles public bool useEncryptedBundles = false; public string bundleEncryptionPassword = ""; [Space] [Tooltip("A list of assetbundles to preload when the game starts. After these have completed loading any GameObject in the gameObjectsToActivate field will be activated.")] public List<string> assetBundlesToPreLoad = new List<string>(); [Tooltip("GameObjects that will be activated after the list of assetBundlesToPreLoad has finished downloading.")] public List<GameObject> gameObjectsToActivate = new List<GameObject>(); [Tooltip("GameObjects that will be activated after Initialization completes.")] public List<GameObject> gameObjectsToActivateOnInit = new List<GameObject>(); [Space] public GameObject loadingMessageObject; public Text loadingMessageText; public string loadingMessage = ""; [HideInInspector] [System.NonSerialized] public float percentDone = 0f; [HideInInspector] [System.NonSerialized] public bool assetBundlesDownloading; [HideInInspector] [System.NonSerialized] public bool canCheckDownloadingBundles; bool isInitializing = false; [HideInInspector] public bool isInitialized = false; [Space] [System.NonSerialized] [ReadOnly] public DownloadingAssetsList downloadingAssets = new DownloadingAssetsList(); //For SimulationMode in the editor - equivalent of AssetBundleManager.m_downloadedBundles //should persist betweem scene loads but not between plays #if UNITY_EDITOR List<string> simulatedDownloadedBundles = new List<string>(); #endif public static DynamicAssetLoader Instance { get { if (_instance == null) { _instance = FindInstance(); } return _instance; } set { _instance = value; } } #region BASE METHODS /*void OnEnable() { if (_instance == null) _instance = this; if (!isInitialized) { StartCoroutine(Initialize()); } }*/ void Awake() { if (!isInitialized && Application.isPlaying) StartCoroutine(StartCO()); } void Start() { if (!isInitializing && !isInitialized) StartCoroutine(StartCO()); } IEnumerator StartCO() { bool destroyingThis = false; if (_instance == null) { _instance = this; if (makePersistent) { DontDestroyOnLoad(this.gameObject); } if (!isInitialized) { yield return StartCoroutine(Initialize()); } } else if (_instance != this) { //copy some values over and then destroy this if (_instance.makePersistent) { Debug.Log("[DynamicAssetLoader] _instance was NOT this one and was persistent"); _instance.assetBundlesToPreLoad.Clear(); _instance.assetBundlesToPreLoad.AddRange(this.assetBundlesToPreLoad); _instance.gameObjectsToActivate.Clear(); _instance.gameObjectsToActivate.AddRange(this.gameObjectsToActivate); _instance.remoteServerIndexURL = this.remoteServerIndexURL; UMAUtils.DestroySceneObject(this.gameObject); destroyingThis = true; } else { _instance = this; } } else if (_instance == this)//sometimes things have called Instance before Start has actually happenned on this { if (makePersistent) { DontDestroyOnLoad(this.gameObject); } if (!isInitialized) { yield return StartCoroutine(Initialize()); } } //Load any preload asset bundles if there are any if (!destroyingThis) if (assetBundlesToPreLoad.Count > 0) { List<string> bundlesToSend = new List<string>(assetBundlesToPreLoad.Count); bundlesToSend.AddRange(assetBundlesToPreLoad); StartCoroutine(LoadAssetBundlesAsync(bundlesToSend)); assetBundlesToPreLoad.Clear(); } } void Update() { if (assetBundlesToPreLoad.Count > 0) { List<string> bundlesToSend = new List<string>(assetBundlesToPreLoad.Count); bundlesToSend.AddRange(assetBundlesToPreLoad); StartCoroutine(LoadAssetBundlesAsync(bundlesToSend)); assetBundlesToPreLoad.Clear(); } #if UNITY_EDITOR if (AssetBundleManager.SimulateAssetBundleInEditor) { if (gameObjectsToActivate.Count > 0) { foreach (GameObject go in gameObjectsToActivate) { if (!go.activeSelf) { go.SetActive(true); } } gameObjectsToActivate.Clear(); } } else { #endif if (downloadingAssets.downloadingItems.Count > 0) downloadingAssets.Update(); if (downloadingAssets.areDownloadedItemsReady == false) assetBundlesDownloading = true; if ((assetBundlesDownloading || downloadingAssets.areDownloadedItemsReady == false) && canCheckDownloadingBundles == true) { if (!AssetBundleManager.AreBundlesDownloading() && downloadingAssets.areDownloadedItemsReady == true) { assetBundlesDownloading = false; if (gameObjectsToActivate.Count > 0) { foreach (GameObject go in gameObjectsToActivate) { if (!go.activeSelf) { go.SetActive(true); } } gameObjectsToActivate.Clear(); } } } #if UNITY_EDITOR } #endif } /// <summary> /// Finds the DynamicAssetLoader in the scene and treats it like a singleton. /// </summary> /// <returns>The DynamicAssetLoader.</returns> public static DynamicAssetLoader FindInstance() { if (_instance == null) { DynamicAssetLoader[] dynamicAssetLoaders = FindObjectsOfType(typeof(DynamicAssetLoader)) as DynamicAssetLoader[]; if (dynamicAssetLoaders.Length > 0) { _instance = dynamicAssetLoaders[0]; } } return _instance; } #endregion #region CHECK DOWNLOADS METHODS public bool downloadingAssetsContains(string assetToCheck) { return downloadingAssets.DownloadingItemsContains(assetToCheck); } public bool downloadingAssetsContains(List<string> assetsToCheck) { return downloadingAssets.DownloadingItemsContains(assetsToCheck); } #endregion #region DOWNLOAD METHODS /// <summary> /// Initialize the downloading URL. eg. local server / iOS ODR / or the download URL as defined in the component settings if Simulation Mode and Local Asset Server is off /// </summary> void InitializeSourceURL() { string URLToUse = ""; if (SimpleWebServer.ServerURL != "") { #if UNITY_EDITOR if (SimpleWebServer.serverStarted)//this is not true in builds no matter what- but we in the editor we need to know #endif URLToUse = remoteServerURL = SimpleWebServer.ServerURL; Debug.Log("[DynamicAssetLoader] SimpleWebServer.ServerURL = " + URLToUse); } else { URLToUse = remoteServerURL; } if (URLToUse != "") AssetBundleManager.SetSourceAssetBundleURL(URLToUse); else { string errorString = "LocalAssetBundleServer was off and no remoteServerURL was specified. One of these must be set in order to use any AssetBundles!"; var warningType = "warning"; #if UNITY_EDITOR errorString = "Switched to Simulation Mode because LocalAssetBundleServer was off and no remoteServerURL was specified in the Scenes' DynamicAssetLoader. One of these must be set in order to actually use your AssetBundles."; warningType = "info"; #endif AssetBundleManager.SimulateOverride = true; var context = UMAContext.FindInstance(); if (context != null) { if ((context.dynamicCharacterSystem != null && (context.dynamicCharacterSystem as DynamicCharacterSystem).dynamicallyAddFromAssetBundles) || (context.raceLibrary != null && (context.raceLibrary as DynamicRaceLibrary).dynamicallyAddFromAssetBundles) || (context.slotLibrary != null && (context.slotLibrary as DynamicSlotLibrary).dynamicallyAddFromAssetBundles) || (context.overlayLibrary != null && (context.overlayLibrary as DynamicOverlayLibrary).dynamicallyAddFromAssetBundles)) { if (warningType == "warning") Debug.LogWarning(errorString); else Debug.Log(errorString); } } else //if you are just using dynamicassetLoader independently of UMA then you may still want this message { if (warningType == "warning") Debug.LogWarning(errorString); else Debug.Log(errorString); } } return; } /// <summary> /// Initializes AssetBundleManager which loads the AssetBundleManifest object and the AssetBundleIndex object. /// </summary> /// <returns></returns> protected IEnumerator Initialize() { #if UNITY_EDITOR if (AssetBundleManager.SimulateAssetBundleInEditor) { isInitialized = true; yield break; } #endif if (isInitializing == false) { isInitializing = true; //If we are using encryption set the encryption key in AssetBundleManager if (useEncryptedBundles) { if (bundleEncryptionPassword != "") { #if UNITY_EDITOR //if the set password and the UMAAssetBundleManagerSettings Passwords dont match and we are in the editor warn the user if (bundleEncryptionPassword != UMAABMSettings.GetEncryptionPassword()) Debug.LogWarning("The bundle encryption password set in this scenes DynamicAssetLoader did not match the one set in UMAAssetBundleManagerSettings. You can fix this by inspecting the DynamicAssetLoader component. It will update automatically."); #endif AssetBundleManager.BundleEncryptionKey = bundleEncryptionPassword; } #if UNITY_EDITOR else { //if an encryption key has been generated but it has not been assigned to this DAL show a warning that it needs to be assigned but assign it anyway if (UMAABMSettings.GetEncryptionPassword() != "") { AssetBundleManager.BundleEncryptionKey = UMAABMSettings.GetEncryptionPassword(); Debug.LogWarning("You are using encrypted asset bundles but you have not assigned the encryption key to this scenes DynamicAssetLoader, you need to do this before you build your game or your bundles will not be decrypted!"); } //if an encryption key has NOT been generated show a warnining that the user need to generate one in the UMAAssetBundleManager window else { Debug.LogWarning("The DynamicAssetLoader in this scene is set to use encrypted bundles but you have not generated an encryption key yet. Please go to UMAAssetBundleManager to generate one, then assign it to your DynamicAssetLoader components in your scene."); } } #endif } else { #if UNITY_EDITOR if (UMAABMSettings.GetEncryptionEnabled()) Debug.LogWarning("You have AssetBunlde Encryption turned ON in UMAAssetBundleManager but have not enabled it in this scenes Dynamic AssetLoader. Please do this in the inspector for the DynamicAssetLoader component."); #endif } InitializeSourceURL();//in the editor this might set AssetBundleManager.SimulateAssetBundleInEditor to be true aswell so check that #if UNITY_EDITOR if (AssetBundleManager.SimulateAssetBundleInEditor) { isInitialized = true; isInitializing = false; if (gameObjectsToActivateOnInit.Count > 0) { for (int i = 0; i < gameObjectsToActivateOnInit.Count; i++) { gameObjectsToActivateOnInit[i].SetActive(true); } gameObjectsToActivateOnInit.Clear(); } yield break; } else #endif //DnamicAssetLoader should still say its initialized even no remoteServer URL was set (either manually or by the LocalWebServer) //because we still want to run normally to load assets from Resources if (remoteServerURL == "") { isInitialized = true; isInitializing = false; if (gameObjectsToActivateOnInit.Count > 0) { for (int i = 0; i < gameObjectsToActivateOnInit.Count; i++) { gameObjectsToActivateOnInit[i].SetActive(true); } gameObjectsToActivateOnInit.Clear(); } yield break; } var request = AssetBundleManager.Initialize(useJsonIndex, remoteServerIndexURL); if (request != null) { while (AssetBundleManager.IsOperationInProgress(request)) { yield return null; } isInitializing = false; if (AssetBundleManager.AssetBundleIndexObject != null) { isInitialized = true; if (gameObjectsToActivateOnInit.Count > 0) { for (int i = 0; i < gameObjectsToActivateOnInit.Count; i++) { gameObjectsToActivateOnInit[i].SetActive(true); } gameObjectsToActivateOnInit.Clear(); } } else { //if we are in the editor this can only have happenned because the asset bundles were not built and by this point //an error will have already been shown about that and AssetBundleManager.SimulationOverride will be true so we can just continue. #if UNITY_EDITOR if (AssetBundleManager.AssetBundleIndexObject == null) { isInitialized = true; yield break; } #endif } } else { Debug.LogWarning("AssetBundleManager failed to initialize correctly"); } } } /// <summary> /// Load a single assetbundle (and its dependencies) asynchroniously and sets the Loading Messages. /// </summary> /// <param name="assetBundleToLoad"></param> /// <param name="loadingMsg"></param> /// <param name="loadedMsg"></param> public void LoadAssetBundle(string assetBundleToLoad, string loadingMsg = "", string loadedMsg = "") { var assetBundlesToLoadList = new List<string>(); assetBundlesToLoadList.Add(assetBundleToLoad); LoadAssetBundles(assetBundlesToLoadList, loadingMsg, loadedMsg); } /// <summary> /// Load multiple assetbundles (and their dependencies) asynchroniously and sets the Loading Messages. /// </summary> /// <param name="assetBundlesToLoad"></param> /// <param name="loadingMsg"></param> /// <param name="loadedMsg"></param> public void LoadAssetBundles(string[] assetBundlesToLoad, string loadingMsg = "", string loadedMsg = "") { var assetBundlesToLoadList = new List<string>(assetBundlesToLoad); LoadAssetBundles(assetBundlesToLoadList, loadingMsg, loadedMsg); } /// <summary> /// Load multiple assetbundles (and their dependencies) asynchroniously and sets the Loading Messages. /// </summary> /// <param name="assetBundlesToLoad"></param> /// <param name="loadingMsg"></param> /// <param name="loadedMsg"></param> public void LoadAssetBundles(List<string> assetBundlesToLoad, string loadingMsg = "", string loadedMsg = "") { #if UNITY_EDITOR if (AssetBundleManager.SimulateAssetBundleInEditor) { foreach (string requiredBundle in assetBundlesToLoad) { SimulateLoadAssetBundle(requiredBundle); } return; } #endif List<string> assetBundlesToReallyLoad = new List<string>(); foreach (string requiredBundle in assetBundlesToLoad) { if (!AssetBundleManager.IsAssetBundleDownloaded(requiredBundle)) { assetBundlesToReallyLoad.Add(requiredBundle); } } if (assetBundlesToReallyLoad.Count > 0) { assetBundlesDownloading = true; canCheckDownloadingBundles = false; StartCoroutine(LoadAssetBundlesAsync(assetBundlesToReallyLoad)); } } /// <summary> /// Loads a list of asset bundles and their dependencies asynchroniously /// </summary> /// <param name="assetBundlesToLoad"></param> /// <returns></returns> protected IEnumerator LoadAssetBundlesAsync(List<string> assetBundlesToLoad, string loadingMsg = "", string loadedMsg = "") { #if UNITY_EDITOR if (AssetBundleManager.SimulateAssetBundleInEditor) yield break; #endif if (!isInitialized) { if (!isInitializing) { yield return StartCoroutine(Initialize()); } else { while (isInitialized == false) { yield return null; } } } string[] bundlesInManifest = AssetBundleManager.AssetBundleIndexObject.GetAllAssetBundles(); foreach (string assetBundleName in assetBundlesToLoad) { foreach (string bundle in bundlesInManifest) { if ((bundle == assetBundleName || bundle.IndexOf(assetBundleName + "/") > -1)) { Debug.Log("Started loading of " + bundle); if (AssetBundleLoadingIndicator.Instance) AssetBundleLoadingIndicator.Instance.Show(bundle, loadingMsg, "", loadedMsg); StartCoroutine(LoadAssetBundleAsync(bundle)); } } } canCheckDownloadingBundles = true; assetBundlesDownloading = true; //yield return null; } /// <summary> /// Loads an asset bundle and its dependencies asynchroniously /// </summary> /// <param name="bundle"></param> /// <returns></returns> //DOS NOTES: if the local server is turned off after it was on when AssetBundleManager was initialized //(like could happen in the editor or if you run a build that uses the local server but you have not started Unity and turned local server on) //then this wrongly says that the bundle has downloaded #pragma warning disable 0219 //remove the warning that we are not using loadedBundle- since we want the error protected IEnumerator LoadAssetBundleAsync(string bundle) { float startTime = Time.realtimeSinceStartup; AssetBundleManager.LoadAssetBundle(bundle, false); string error = null; while (AssetBundleManager.GetLoadedAssetBundle(bundle, out error) == null) { yield return null; } LoadedAssetBundle loadedBundle = AssetBundleManager.GetLoadedAssetBundle(bundle, out error); float elapsedTime = Time.realtimeSinceStartup - startTime; Debug.Log(bundle + (!String.IsNullOrEmpty(error) ? " was not" : " was") + " loaded successfully in " + elapsedTime + " seconds"); if (!String.IsNullOrEmpty(error)) { Debug.LogError("[DynamicAssetLoader] Bundle Load Error: " + error); yield break; } //If this assetBundle contains UMATextRecipes we may need to trigger some post processing... //it may have downloaded some dependent bundles too so these may need processing aswell var dependencies = AssetBundleManager.AssetBundleIndexObject.GetAllDependencies(bundle); //DOS 04112016 so maybe what we need to do here is check the dependencies are loaded too if (dependencies.Length > 0) { for (int i = 0; i < dependencies.Length; i++) { while (AssetBundleManager.IsAssetBundleDownloaded(dependencies[i]) == false) { yield return null; } } } DynamicCharacterSystem thisDCS = null; if (UMAContext.Instance != null) { thisDCS = UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem; } if (thisDCS != null) { if (thisDCS.addAllRecipesFromDownloadedBundles) { if (AssetBundleManager.AssetBundleIndexObject.GetAllAssetsOfTypeInBundle(bundle, "UMATextRecipe").Length > 0) { //DCSRefresh only needs to be called if the downloaded asset bundle contained UMATextRecipes (or character recipes) //Also it actually ONLY needs to search this bundle thisDCS.Refresh(false, bundle); } for (int i = 0; i < dependencies.Length; i++) { if (AssetBundleManager.AssetBundleIndexObject.GetAllAssetsOfTypeInBundle(dependencies[i], "UMATextRecipe").Length > 0) { //DCSRefresh only needs to be called if the downloaded asset bundle contained UMATextRecipes (or character recipes) //Also it actually ONLY needs to search this bundle thisDCS.Refresh(false, dependencies[i]); } } } } } #pragma warning restore 0219 #endregion #region LOAD ASSETS METHODS [HideInInspector] public bool debugOnFail = true; public bool AddAssets<T>(ref Dictionary<string, List<string>> assetBundlesUsedDict, bool searchResources, bool searchBundles, bool downloadAssetsEnabled, string bundlesToSearch = "", string resourcesFolderPath = "", int? assetNameHash = null, string assetName = "", Action<T[]> callback = null, bool forceDownloadAll = false) where T : UnityEngine.Object { if (isInitialized == false && Application.isPlaying && (searchBundles && downloadAssetsEnabled)) { Debug.LogWarning("[DynamicAssetLoader] had not finished initializing when " + typeof(T).ToString() + " assets were requested. Please be sure wait for 'DynamicAssetLoader.Instance.isInitialized' to be true before requesting dynamically addedd assets from the libraries."); } bool found = false; List<T> assetsToReturn = new List<T>(); string[] resourcesFolderPathArray = SearchStringToArray(resourcesFolderPath); string[] bundlesToSearchArray = SearchStringToArray(bundlesToSearch); //search UMA AssetIndex if (searchResources) { //using UMAAssetIndexer!! if (UMAAssetIndexer.Instance != null) { found = AddAssetsFromResourcesIndex<T>(ref assetsToReturn, resourcesFolderPathArray, assetNameHash, assetName); } else { Debug.LogWarning("[DynamicAssetLoader] UMAResourcesIndex.Instance WAS NULL"); } } //if we can and want to search asset bundles if ((AssetBundleManager.AssetBundleIndexObject != null || AssetBundleManager.SimulateAssetBundleInEditor == true) || Application.isPlaying == false) if (searchBundles && (found == false || (assetName == "" && assetNameHash == null))) { bool foundHere = AddAssetsFromAssetBundles<T>(ref assetBundlesUsedDict, ref assetsToReturn, downloadAssetsEnabled, bundlesToSearchArray, assetNameHash, assetName, callback, forceDownloadAll); found = foundHere == true ? true : found; } if (callback != null && assetsToReturn.Count > 0) { callback(assetsToReturn.ToArray()); } return found; } public bool AddAssets<T>(bool searchResources, bool searchBundles, bool downloadAssetsEnabled, string bundlesToSearch = "", string resourcesFolderPath = "", int? assetNameHash = null, string assetName = "", Action<T[]> callback = null, bool forceDownloadAll = false) where T : UnityEngine.Object { var dummyDict = new Dictionary<string, List<string>>(); return AddAssets<T>(ref dummyDict, searchResources, searchBundles, downloadAssetsEnabled, bundlesToSearch, resourcesFolderPath, assetNameHash, assetName, callback, forceDownloadAll); } public bool AddAssetsFromResourcesIndex<T>(ref List<T> assetsToReturn, string[] resourcesFolderPathArray, int? assetNameHash = null, string assetName = "") where T : UnityEngine.Object { bool found = false; //Use new UMAAssetIndexer!! if (UMAAssetIndexer.Instance == null) return found; if (assetNameHash != null || assetName != "") { T foundAsset = null; if (assetNameHash != null) { //using UMAAssetIndexer foundAsset = (UMAAssetIndexer.Instance.GetAsset<T>((int)assetNameHash, resourcesFolderPathArray) as T); } else if (assetName != "") { //check if its a Placeholder asset that has been requested directly- this happens when the UMATextRecipePlaceholder tries to load var typePlaceholderName = typeof(T).ToString().Replace(typeof(T).Namespace + ".", "") + "Placeholder"; if (typePlaceholderName == assetName || typePlaceholderName + "_Slot" == assetName) { foundAsset = GetPlaceholderAsset<T>(assetName); } //using UMAAssetIndexer if (foundAsset == null) foundAsset = (UMAAssetIndexer.Instance.GetAsset<T>(assetName, resourcesFolderPathArray) as T); } if (foundAsset != null) { assetsToReturn.Add(foundAsset); found = true; } } else if (assetNameHash == null && assetName == "") { //Using UMAAssetIndexer List<T> assetIndexerAssets = UMAAssetIndexer.Instance.GetAllAssets<T>(resourcesFolderPathArray) as List<T>; List<T> assetIndexerAssetsToAdd = new List<T>(); //UMAAssetIndexer returns null assets so check for that if (assetIndexerAssets.Count > 0) { for (int i = 0; i < assetIndexerAssets.Count; i++) { if (assetIndexerAssets[i] != null) { assetIndexerAssetsToAdd.Add(assetIndexerAssets[i]); } } } assetsToReturn.AddRange(assetIndexerAssetsToAdd); found = assetsToReturn.Count > 0; } return found; } public T GetPlaceholderAsset<T>(string placeholderName) where T : UnityEngine.Object { if (placeholderName.IndexOf("Placeholder") == -1) return null; return (T)Resources.Load<T>("PlaceholderAssets/" + placeholderName) as T; } /// <summary> /// Generic Library function to search AssetBundles for a type of asset, optionally filtered by bundle name, and asset assetNameHash or assetName. /// Optionally sends the found assets to the supplied callback for processing. /// Automatically performs the operation in SimulationMode if AssetBundleManager.SimulationMode is enabled or if the Application is not playing. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bundlesToSearch"></param> /// <param name="assetNameHash"></param> /// <param name="assetName"></param> /// <param name="callback"></param> public bool AddAssetsFromAssetBundles<T>(ref Dictionary<string, List<string>> assetBundlesUsedDict, ref List<T> assetsToReturn, bool downloadAssetsEnabled, string[] bundlesToSearchArray, int? assetNameHash = null, string assetName = "", Action<T[]> callback = null, bool forceDownloadAll = false) where T : UnityEngine.Object { #if UNITY_EDITOR if (AssetBundleManager.SimulateAssetBundleInEditor) { return SimulateAddAssetsFromAssetBundlesNew<T>(ref assetBundlesUsedDict, ref assetsToReturn, bundlesToSearchArray, assetNameHash, assetName, callback, forceDownloadAll); } else { #endif if (AssetBundleManager.AssetBundleIndexObject == null) { #if UNITY_EDITOR Debug.LogWarning("[DynamicAssetLoader] No AssetBundleManager.AssetBundleIndexObject found. Do you need to rebuild your AssetBundles and/or upload the platform index bundle?"); AssetBundleManager.SimulateOverride = true; return SimulateAddAssetsFromAssetBundlesNew<T>(ref assetBundlesUsedDict, ref assetsToReturn, bundlesToSearchArray, assetNameHash, assetName, callback); #else Debug.LogError("[DynamicAssetLoader] No AssetBundleManager.AssetBundleIndexObject found. Do you need to rebuild your AssetBundles and/or upload the platform index bundle?"); return false; #endif } string[] allAssetBundleNames = AssetBundleManager.AssetBundleIndexObject.GetAllAssetBundleNames(); string[] assetBundleNamesArray = allAssetBundleNames; Type typeParameterType = typeof(T); var typeString = typeParameterType.FullName; if (bundlesToSearchArray.Length > 0 && bundlesToSearchArray[0] != "") { List<string> processedBundleNamesArray = new List<string>(); for (int i = 0; i < bundlesToSearchArray.Length; i++) { for (int ii = 0; ii < allAssetBundleNames.Length; ii++) { if (allAssetBundleNames[ii].IndexOf(bundlesToSearchArray[i]) > -1 && !processedBundleNamesArray.Contains(allAssetBundleNames[ii])) { processedBundleNamesArray.Add(allAssetBundleNames[ii]); } } } assetBundleNamesArray = processedBundleNamesArray.ToArray(); } bool assetFound = false; for (int i = 0; i < assetBundleNamesArray.Length; i++) { string error = ""; if (assetNameHash != null && assetName == "") { assetName = AssetBundleManager.AssetBundleIndexObject.GetAssetNameFromHash(assetBundleNamesArray[i], assetNameHash, typeString); } if (assetName != "" || assetNameHash != null) { if (assetName == "" && assetNameHash != null) { continue; } bool assetBundleContains = AssetBundleManager.AssetBundleIndexObject.AssetBundleContains(assetBundleNamesArray[i], assetName, typeString); if (assetBundleContains) { if (AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out error) != null) { var assetFilename = AssetBundleManager.AssetBundleIndexObject.GetFilenameFromAssetName(assetBundleNamesArray[i], assetName, typeString); T target = (T)AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out error).m_AssetBundle.LoadAsset<T>(assetFilename); if (target != null) { assetFound = true; if (!assetBundlesUsedDict.ContainsKey(assetBundleNamesArray[i])) { assetBundlesUsedDict[assetBundleNamesArray[i]] = new List<string>(); } if (!assetBundlesUsedDict[assetBundleNamesArray[i]].Contains(assetName)) { assetBundlesUsedDict[assetBundleNamesArray[i]].Add(assetName); } assetsToReturn.Add(target); if (assetName != "") break; } else { if (!String.IsNullOrEmpty(error)) { Debug.LogWarning(error); } } } else if (downloadAssetsEnabled) { //Here we return a temp asset and wait for the bundle to download //We dont want to create multiple downloads of the same bundle so check its not already downloading if (AssetBundleManager.AreBundlesDownloading(assetBundleNamesArray[i]) == false) { LoadAssetBundle(assetBundleNamesArray[i]); } else { //do nothing its already downloading } if (assetNameHash == null) { assetNameHash = AssetBundleManager.AssetBundleIndexObject.GetAssetHashFromName(assetBundleNamesArray[i], assetName, typeString); } T target = downloadingAssets.AddDownloadItem<T>(assetName, assetNameHash, assetBundleNamesArray[i], callback); if (target != null) { assetFound = true; if (!assetBundlesUsedDict.ContainsKey(assetBundleNamesArray[i])) { assetBundlesUsedDict[assetBundleNamesArray[i]] = new List<string>(); } if (!assetBundlesUsedDict[assetBundleNamesArray[i]].Contains(assetName)) { assetBundlesUsedDict[assetBundleNamesArray[i]].Add(assetName); } assetsToReturn.Add(target); if (assetName != "") break; } } } } else //we are just loading in all assets of type from the downloaded bundles- if you are happy to trigger the download of all possible assetbundles that contain anything of type T set forceDownloadAll to be true { if (AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out error) != null) { string[] assetsInBundle = AssetBundleManager.AssetBundleIndexObject.GetAllAssetsOfTypeInBundle(assetBundleNamesArray[i], typeString); if (assetsInBundle.Length > 0) { foreach (string asset in assetsInBundle) { //sometimes this errors out if the bundle is downloaded but not LOADED var assetFilename = AssetBundleManager.AssetBundleIndexObject.GetFilenameFromAssetName(assetBundleNamesArray[i], asset, typeString); T target = null; try { target = (T)AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out error).m_AssetBundle.LoadAsset<T>(assetFilename); } catch { Debug.LogWarning("[DynamicAssetLoader]AddAssetsFromAssetBundles " + assetBundleNamesArray[i] + " had not loaded at the time of the request"); var thiserror = ""; AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out thiserror); if (thiserror != "" && thiserror != null) Debug.LogWarning("GetLoadedAssetBundle error was " + thiserror); else if (AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out thiserror).m_AssetBundle == null) { //The problem is here the bundle is downloaded but not LOADED Debug.LogWarning("Bundle was ok but m_AssetBundle was null"); } else if (AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out error).m_AssetBundle.LoadAsset<T>(asset) == null) { Debug.LogWarning("Load Asset could not get a " + typeof(T).ToString() + " asset called " + asset + " from " + assetBundleNamesArray[i]); } } /*if (target == null && typeof(T) == typeof(SlotDataAsset)) { //08122016 DOS NOTES now the assetBundleIndex records the 'slotname' for slots rather than just the asset name we should not need to try this any more. TODO Confirm target = (T)AssetBundleManager.GetLoadedAssetBundle(assetBundleNamesArray[i], out error).m_AssetBundle.LoadAsset<T>(asset + "_Slot"); }*/ if (target != null) { assetFound = true; if (!assetBundlesUsedDict.ContainsKey(assetBundleNamesArray[i])) { assetBundlesUsedDict[assetBundleNamesArray[i]] = new List<string>(); } if (!assetBundlesUsedDict[assetBundleNamesArray[i]].Contains(asset)) { assetBundlesUsedDict[assetBundleNamesArray[i]].Add(asset); } assetsToReturn.Add(target); } else { if (!String.IsNullOrEmpty(error)) { Debug.LogWarning(error); } } } } } else if (forceDownloadAll && downloadAssetsEnabled)//if its not downloaded but we are forcefully downloading any bundles that contain a type of asset make it download and add the temp asset to the downloading assets list { string[] assetsInBundle = AssetBundleManager.AssetBundleIndexObject.GetAllAssetsOfTypeInBundle(assetBundleNamesArray[i], typeString); if (assetsInBundle.Length > 0) { //Debug.Log("[DynamicAssetLoader] forceDownloadAll was true for " + typeString + " and found in " + assetBundleNamesArray[i]); for (int aib = 0; aib < assetsInBundle.Length; aib++) { //Here we return a temp asset and wait for the bundle to download //We dont want to create multiple downloads of the same bundle so check its not already downloading if (AssetBundleManager.AreBundlesDownloading(assetBundleNamesArray[i]) == false) { LoadAssetBundle(assetBundleNamesArray[i]); } else { //do nothing its already downloading } var thisAssetName = assetsInBundle[aib]; var thisAssetNameHash = AssetBundleManager.AssetBundleIndexObject.GetAssetHashFromName(assetBundleNamesArray[i], thisAssetName, typeString); T target = downloadingAssets.AddDownloadItem<T>(/*CurrentBatchID,*/ thisAssetName, thisAssetNameHash, assetBundleNamesArray[i], callback/*, requestingUMA*/); if (target != null) { if (!assetBundlesUsedDict.ContainsKey(assetBundleNamesArray[i])) { assetBundlesUsedDict[assetBundleNamesArray[i]] = new List<string>(); } if (!assetBundlesUsedDict[assetBundleNamesArray[i]].Contains(thisAssetName)) { assetBundlesUsedDict[assetBundleNamesArray[i]].Add(thisAssetName); } assetsToReturn.Add(target); } } } } } } if (!assetFound && assetName != "" && debugOnFail) { string[] assetIsInArray = AssetBundleManager.AssetBundleIndexObject.FindContainingAssetBundle(assetName, typeString); string assetIsIn = assetIsInArray.Length > 0 ? " but it was in " + assetIsInArray[0] : ". Do you need to reupload you platform manifest and index?"; Debug.LogWarning("Dynamic" + typeof(T).Name + "Library (" + typeString + ") could not load " + assetName + " from any of the AssetBundles searched" + assetIsIn); } return assetFound; #if UNITY_EDITOR } #endif } #if UNITY_EDITOR /// <summary> /// Simulates the loading of assets when AssetBundleManager is set to 'SimulationMode' /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bundlesToSearch"></param> /// <param name="assetNameHash"></param> /// <param name="assetName"></param> /// <param name="callback"></param> bool SimulateAddAssetsFromAssetBundlesNew<T>(ref Dictionary<string, List<string>> assetBundlesUsedDict, ref List<T> assetsToReturn, string[] bundlesToSearchArray, int? assetNameHash = null, string assetName = "", Action<T[]> callback = null, bool forceDownloadAll = false) where T : UnityEngine.Object { var st = UMAAssetIndexer.StartTimer(); Type typeParameterType = typeof(T); var typeString = typeParameterType.FullName; int currentSimulatedDownloadedBundlesCount = simulatedDownloadedBundles.Count; if (assetNameHash != null) { // We could load all assets of type, iterate over them and get the hash and see if it matches...But then that would be as slow as loading from resources was Debug.Log("It is not currently possible to search for assetBundle assets in SimulationMode using the assetNameHash. " + typeString + " is trying to do this with assetNameHash " + assetNameHash); } string[] allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames(); string[] assetBundleNamesArray; if (bundlesToSearchArray.Length > 0 && bundlesToSearchArray[0] != "") { List<string> processedBundleNamesArray = new List<string>(); for (int i = 0; i < bundlesToSearchArray.Length; i++) { for (int ii = 0; ii < allAssetBundleNames.Length; ii++) { if (allAssetBundleNames[ii].IndexOf(bundlesToSearchArray[i]) > -1 && !processedBundleNamesArray.Contains(allAssetBundleNames[ii])) { processedBundleNamesArray.Add(allAssetBundleNames[ii]); } } } assetBundleNamesArray = processedBundleNamesArray.ToArray(); } else { assetBundleNamesArray = allAssetBundleNames; } bool assetFound = false; ///a list of all the assets any assets we load depend on List<string> dependencies = new List<string>(); for (int i = 0; i < assetBundleNamesArray.Length; i++) { if (assetFound && assetName != "")//Do we want to break actually? What if the user has named two overlays the same? Or would this not work anyway? break; string[] possiblePaths = new string[0]; if (assetName != "") { //This is a compromise for the sake of speed that assumes slot/overlay/race assets have the same slotname/overlayname/racename as their actual asset //if we dont do this we have to load all the assets of that type and check their name which is really slow //I think its worth having this compromise because this does not happen when the local server is on or the assets are *actually* downloaded from an external source because the AssetBundleIndex is used then //if this is looking for SlotsDataAssets then the asset name has _Slot after it usually even if the slot name doesn't have that-but the user might have renamed it so cover both cases if (typeof(T) == typeof(SlotDataAsset)) { string[] possiblePathsTemp = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleNamesArray[i], assetName); string[] possiblePaths_SlotTemp = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleNamesArray[i], assetName + "_Slot"); List<string> possiblePathsList = new List<string>(possiblePathsTemp); foreach (string path in possiblePaths_SlotTemp) { if (!possiblePathsList.Contains(path)) { possiblePathsList.Add(path); } } possiblePaths = possiblePathsList.ToArray(); } else { possiblePaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleNamesArray[i], assetName); } } else { //if the application is not playing we want to load ALL the assets from the bundle this asset will be in if (!Application.isPlaying) { possiblePaths = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleNamesArray[i]); } else if (simulatedDownloadedBundles.Contains(assetBundleNamesArray[i]) || forceDownloadAll) { //DCS.Refresh calls for assets without sending a name and in reality this just checks bundles that are already downloaded //this mimics that behaviour possiblePaths = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleNamesArray[i]); } } foreach (string path in possiblePaths) { // the line T target = (T)AssetDatabase.LoadAssetAtPath(path, typeof(T)); below appears to load the asset *and then* check if its a type of T // this leads to a big slowdown the first time this happens. Its much quicker (although messier) to do the following as getting the paths // does not load the actual asset. This is also slightly quicker than getting all paths of type T outside this loop // the 't:' filter needs the type to not have a namespace var typeForSearch = typeof(T).ToString().Replace(typeof(T).Namespace + ".", ""); var searchString = assetName == "" ? "t:" + typeForSearch : "t:" + typeForSearch + " " + assetName; var containingPath = System.IO.Path.GetDirectoryName(path); var typeGUIDs = AssetDatabase.FindAssets(searchString, new string[1] { containingPath }); var typePaths = new List<string>(typeGUIDs.Length); for (int ti = 0; ti < typeGUIDs.Length; ti++) typePaths.Add(AssetDatabase.GUIDToAssetPath(typeGUIDs[ti])); if (!typePaths.Contains(path)) continue; T target = (T)AssetDatabase.LoadAssetAtPath(path, typeof(T)); if (target != null) { assetFound = true; if (!assetBundlesUsedDict.ContainsKey(assetBundleNamesArray[i])) { assetBundlesUsedDict[assetBundleNamesArray[i]] = new List<string>(); } if (!assetBundlesUsedDict[assetBundleNamesArray[i]].Contains(assetName)) { assetBundlesUsedDict[assetBundleNamesArray[i]].Add(assetName); } assetsToReturn.Add(target); //Add the bundle this asset was in to the simulatedDownloadedBundles list if its not already there if (!simulatedDownloadedBundles.Contains(assetBundleNamesArray[i])) simulatedDownloadedBundles.Add(assetBundleNamesArray[i]); //Find the dependencies for all the assets in this bundle because AssetBundleManager would automatically download those bundles too //Dont bother finding dependencies when something is just trying to load all asset of type if (Application.isPlaying && assetName != "" && forceDownloadAll == false) { var thisDependencies = AssetDatabase.GetDependencies(path, false); for (int depi = 0; depi < thisDependencies.Length; depi++) { if (!dependencies.Contains(thisDependencies[depi])) { dependencies.Add(thisDependencies[depi]); } } } if (assetName != "") break; } } } if (dependencies.Count > 0 && assetName != "" && forceDownloadAll == false) { //we need to load ALL the assets from every Assetbundle that has a dependency in it. List<string> AssetBundlesToFullyLoad = new List<string>(); for (int i = 0; i < assetBundleNamesArray.Length; i++) { var allAssetBundlePaths = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleNamesArray[i]); bool processed = false; for (int ii = 0; ii < allAssetBundlePaths.Length; ii++) { for (int di = 0; di < dependencies.Count; di++) { if (allAssetBundlePaths[ii] == dependencies[di]) { if (!AssetBundlesToFullyLoad.Contains(assetBundleNamesArray[i])) AssetBundlesToFullyLoad.Add(assetBundleNamesArray[i]); //Add this bundle to the simulatedDownloadedBundles list if its not already there because that would have been downloaded too if (!simulatedDownloadedBundles.Contains(assetBundleNamesArray[i])) simulatedDownloadedBundles.Add(assetBundleNamesArray[i]); processed = true; break; } } if (processed) break; } } } if (!assetFound && assetName != "" && debugOnFail) { Debug.LogWarning("Dynamic" + typeString + "Library could not simulate the loading of " + assetName + " from any AssetBundles"); return assetFound; } if (assetsToReturn.Count > 0 && callback != null) { callback(assetsToReturn.ToArray()); } //Racedata will trigger an update of DCS itself if it added a race DCS needs to know about //Other assets may have caused psuedo downloads of bundles DCS should check for UMATextRecipes in //Effectively this mimics DynamicAssetLoader loadAssetBundleAsyncs call of DCS.Refresh //- but without loading all the assets to check if any of them are UMATextRecipes because that is too slow //10012017 Only do this if thisDCS.addAllRecipesFromDownloadedBundles is true if (currentSimulatedDownloadedBundlesCount != simulatedDownloadedBundles.Count /*&& typeof(T) != typeof(RaceData)*/ && assetName != "") { var thisDCS = UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem; if (thisDCS != null) { if (thisDCS.addAllRecipesFromDownloadedBundles) { //but it only needs to add stuff from the bundles that were added for (int i = currentSimulatedDownloadedBundlesCount; i < simulatedDownloadedBundles.Count; i++) { thisDCS.Refresh(false, simulatedDownloadedBundles[i]); } } } } UMAAssetIndexer.StopTimer(st, "SimulateAddAssetsFromAssetBundlesNew Type=" + typeof(T).Name); return assetFound; } #endif #if UNITY_EDITOR /// <summary> /// Mimics the check dynamicAssetLoader does when an actual LoadBundleAsync happens /// where it checks if the asset has any UMATextRecipes in it and if it does makes DCS.Refresh to get them /// </summary> /// <param name="assetBundleToLoad"></param> //10012017 Only do this if thisDCS.addAllRecipesFromDownloadedBundles is true public void SimulateLoadAssetBundle(string assetBundleToLoad) { bool bundleAlreadySimulated = true; if (!simulatedDownloadedBundles.Contains(assetBundleToLoad)) { simulatedDownloadedBundles.Add(assetBundleToLoad); bundleAlreadySimulated = false; } var allAssetBundlePaths = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleToLoad); //We need to add the recipes from the bundle to DCS, other assets add them selves as they are requested by the recipes var thisDCS = UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem; bool dcsNeedsRefresh = false; if (thisDCS) { if (thisDCS.addAllRecipesFromDownloadedBundles) { for (int i = 0; i < allAssetBundlePaths.Length; i++) { UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(allAssetBundlePaths[i]); if (obj.GetType() == typeof(UMATextRecipe)) { if (bundleAlreadySimulated == false) dcsNeedsRefresh = true; break; } } if (dcsNeedsRefresh) { thisDCS.Refresh(false, assetBundleToLoad); } } } } #endif /// <summary> /// Splits the 'ResourcesFolderPath(s)' and 'AssetBundleNamesToSearch' fields up by comma if the field is using that functionality... /// </summary> /// <param name="searchString"></param> /// <returns></returns> string[] SearchStringToArray(string searchString = "") { string[] searchArray; if (String.IsNullOrEmpty(searchString)) { searchArray = new string[] { "" }; } else { searchString.Replace(" ,", ",").Replace(", ", ","); if (searchString.IndexOf(",") == -1) { searchArray = new string[1] { searchString }; } else { searchArray = searchString.Split(new string[1] { "," }, StringSplitOptions.RemoveEmptyEntries); } } return searchArray; } #endregion #region SPECIAL TYPES //DownloadingAssetsList and DownloadingAssetItem moved into their own scripts to make this one a bit more manageable! #endregion } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public class DockContent : Form, IDockContent { public DockContent() { m_dockHandler = new DockContentHandler(this, new GetPersistStringCallback(GetPersistString)); m_dockHandler.DockStateChanged += new EventHandler(DockHandler_DockStateChanged); if (PatchController.EnableFontInheritanceFix != true) { //Suggested as a fix by bensty regarding form resize this.ParentChanged += new EventHandler(DockContent_ParentChanged); } } //Suggested as a fix by bensty regarding form resize private void DockContent_ParentChanged(object Sender, EventArgs e) { if (this.Parent != null) this.Font = this.Parent.Font; } private DockContentHandler m_dockHandler = null; [Browsable(false)] public DockContentHandler DockHandler { get { return m_dockHandler; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_AllowEndUserDocking_Description")] [DefaultValue(true)] public bool AllowEndUserDocking { get { return DockHandler.AllowEndUserDocking; } set { DockHandler.AllowEndUserDocking = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_DockAreas_Description")] [DefaultValue(DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | DockAreas.DockBottom | DockAreas.Document | DockAreas.Float)] public DockAreas DockAreas { get { return DockHandler.DockAreas; } set { DockHandler.DockAreas = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_AutoHidePortion_Description")] [DefaultValue(0.25)] public double AutoHidePortion { get { return DockHandler.AutoHidePortion; } set { DockHandler.AutoHidePortion = value; } } private string m_tabText = null; [Localizable(true)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabText_Description")] [DefaultValue(null)] public string TabText { get { return m_tabText; } set { DockHandler.TabText = m_tabText = value; } } private bool ShouldSerializeTabText() { return (m_tabText != null); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_CloseButton_Description")] [DefaultValue(true)] public bool CloseButton { get { return DockHandler.CloseButton; } set { DockHandler.CloseButton = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_CloseButtonVisible_Description")] [DefaultValue(true)] public bool CloseButtonVisible { get { return DockHandler.CloseButtonVisible; } set { DockHandler.CloseButtonVisible = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPanel DockPanel { get { return DockHandler.DockPanel; } set { DockHandler.DockPanel = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockState DockState { get { return DockHandler.DockState; } set { DockHandler.DockState = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPane Pane { get { return DockHandler.Pane; } set { DockHandler.Pane = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsHidden { get { return DockHandler.IsHidden; } set { DockHandler.IsHidden = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockState VisibleState { get { return DockHandler.VisibleState; } set { DockHandler.VisibleState = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsFloat { get { return DockHandler.IsFloat; } set { DockHandler.IsFloat = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPane PanelPane { get { return DockHandler.PanelPane; } set { DockHandler.PanelPane = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPane FloatPane { get { return DockHandler.FloatPane; } set { DockHandler.FloatPane = value; } } [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected virtual string GetPersistString() { return GetType().ToString(); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_HideOnClose_Description")] [DefaultValue(false)] public bool HideOnClose { get { return DockHandler.HideOnClose; } set { DockHandler.HideOnClose = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_ShowHint_Description")] [DefaultValue(DockState.Unknown)] public DockState ShowHint { get { return DockHandler.ShowHint; } set { DockHandler.ShowHint = value; } } [Browsable(false)] public bool IsActivated { get { return DockHandler.IsActivated; } } public bool PreCreated { get; set; } public bool IsDockStateValid(DockState dockState) { return DockHandler.IsDockStateValid(dockState); } /// <summary> /// Context menu. /// </summary> /// <remarks> /// This property should be obsolete as it does not support theming. Please use <see cref="TabPageContextMenuStrip"/> instead. /// </remarks> [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabPageContextMenu_Description")] [DefaultValue(null)] public ContextMenu TabPageContextMenu { get { return DockHandler.TabPageContextMenu; } set { DockHandler.TabPageContextMenu = value; } } /// <summary> /// Context menu strip. /// </summary> [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")] [DefaultValue(null)] public ContextMenuStrip TabPageContextMenuStrip { get { return DockHandler.TabPageContextMenuStrip; } set { DockHandler.TabPageContextMenuStrip = value; } } public void ApplyTheme() { DockHandler.ApplyTheme(); if (DockPanel != null) { if (MainMenuStrip != null) DockPanel.Theme.ApplyTo(MainMenuStrip); if (ContextMenuStrip != null) DockPanel.Theme.ApplyTo(ContextMenuStrip); } } [Localizable(true)] [Category("Appearance")] [LocalizedDescription("DockContent_ToolTipText_Description")] [DefaultValue(null)] public string ToolTipText { get { return DockHandler.ToolTipText; } set { DockHandler.ToolTipText = value; } } public new void Activate() { DockHandler.Activate(); } public new void Hide() { DockHandler.Hide(); } public new void Show() { DockHandler.Show(); } public void Show(DockPanel dockPanel) { DockHandler.Show(dockPanel); } public void Show(DockPanel dockPanel, DockState dockState) { DockHandler.Show(dockPanel, dockState); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { DockHandler.Show(dockPanel, floatWindowBounds); } public void Show(DockPane pane, IDockContent beforeContent) { DockHandler.Show(pane, beforeContent); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { DockHandler.Show(previousPane, alignment, proportion); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void FloatAt(Rectangle floatWindowBounds) { DockHandler.FloatAt(floatWindowBounds); } public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex) { DockHandler.DockTo(paneTo, dockStyle, contentIndex); } public void DockTo(DockPanel panel, DockStyle dockStyle) { DockHandler.DockTo(panel, dockStyle); } #region IDockContent Members void IDockContent.OnActivated(EventArgs e) { this.OnActivated(e); } void IDockContent.OnDeactivate(EventArgs e) { this.OnDeactivate(e); } #endregion #region Events private void DockHandler_DockStateChanged(object sender, EventArgs e) { OnDockStateChanged(e); } private static readonly object DockStateChangedEvent = new object(); [LocalizedCategory("Category_PropertyChanged")] [LocalizedDescription("Pane_DockStateChanged_Description")] public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion /// <summary> /// Overridden to avoid resize issues with nested controls /// </summary> /// <remarks> /// http://blogs.msdn.com/b/alejacma/archive/2008/11/20/controls-won-t-get-resized-once-the-nesting-hierarchy-of-windows-exceeds-a-certain-depth-x64.aspx /// http://support.microsoft.com/kb/953934 /// </remarks> protected override void OnSizeChanged(EventArgs e) { if (DockPanel != null && DockPanel.SupportDeeplyNestedContent && IsHandleCreated) { BeginInvoke((MethodInvoker)delegate { base.OnSizeChanged(e); }); } else { base.OnSizeChanged(e); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Reflection.Emit; using System.Threading; using Xunit; namespace System.Reflection.Emit.Lightweight.Tests { public class DynamicMethodctor6 { [Fact] public void PosTest1() { Type owner = typeof(MethodTestClass6); bool skipVisb = true; DynamicMethod dynamicMeth = new DynamicMethod("Pos1method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), null, owner, skipVisb); MethodAttributes attributes = dynamicMeth.Attributes; Assert.False(dynamicMeth == null || dynamicMeth.Name != "Pos1method" || attributes != (MethodAttributes.Public | MethodAttributes.Static) || dynamicMeth.CallingConvention != CallingConventions.Standard); } [Fact] public void PosTest2() { Type owner = typeof(MethodTestClass6); bool skipVisb = false; DynamicMethod dynamicMeth = new DynamicMethod("Pos2method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new Type[] { typeof(int), typeof(string) }, owner, skipVisb); MethodAttributes attributes = dynamicMeth.Attributes; Assert.False(dynamicMeth == null || dynamicMeth.Name != "Pos2method" || attributes != (MethodAttributes.Public | MethodAttributes.Static) || dynamicMeth.CallingConvention != CallingConventions.Standard); } [Fact] public void PosTest3() { Type owner = typeof(MethodTestClass6); bool skipVisib = true; DynamicMethod dynamicMeth = new DynamicMethod("Pos3method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(string), new Type[] { typeof(int), typeof(string) }, owner, skipVisib); MethodAttributes attributes = dynamicMeth.Attributes; Assert.False(dynamicMeth == null || dynamicMeth.Name != "Pos3method" || attributes != (MethodAttributes.Static | MethodAttributes.Public) || dynamicMeth.CallingConvention != CallingConventions.Standard); } [Fact] public void NegTest1() { Type owner = typeof(MethodTestClass6); bool[] skipVisbs = new bool[] { false, true }; for (int i = 0; i < skipVisbs.Length; i++) { Assert.Throws<ArgumentException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg1method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new Type[] { null, typeof(string) }, owner, skipVisbs[i]); }); } } [Fact] public void NegTest2() { Type owner = typeof(Array); bool[] skipVisbs = new bool[] { false, true }; for (int i = 0; i < skipVisbs.Length; i++) { Assert.Throws<ArgumentException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg2method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new Type[] { null, typeof(string) }, owner, skipVisbs[i]); }); } } [Fact] public void NegTest3() { Type owner = typeof(MethodTestInterface6); bool[] skipVisbs = new bool[] { false, true }; for (int i = 0; i < skipVisbs.Length; i++) { Assert.Throws<ArgumentException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg3method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new Type[] { null, typeof(string) }, owner, skipVisbs[i]); }); } } [Fact] public void NegTest4() { Type[] genericTypes = typeof(MethodMyClass6<>).GetGenericArguments(); Type owner = genericTypes[0]; bool[] skipVisbs = new bool[] { false, true }; for (int i = 0; i < skipVisbs.Length; i++) { Assert.Throws<ArgumentException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg4method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new Type[] { null, typeof(string) }, owner, skipVisbs[i]); }); } } [Fact] public void NegTest5() { Type owner = typeof(MethodTestClass6); bool[] skipVisbs = new bool[] { false, true }; for (int i = 0; i < skipVisbs.Length; i++) { Assert.Throws<ArgumentNullException>(() => { DynamicMethod dynamicMeth = new DynamicMethod(null, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new Type[] { typeof(string) }, owner, skipVisbs[i]); }); } } [Fact] public void NegTest6() { Type owner = null; bool[] skipVisbs = new bool[] { false, true }; for (int i = 0; i < skipVisbs.Length; i++) { Assert.Throws<ArgumentNullException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg6method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new Type[] { typeof(string) }, owner, skipVisbs[i]); }); } } [Fact] public void NegTest7() { Type returnType = CreateType(); Type owner = typeof(MethodTestClass6); bool[] skipVisbs = new bool[] { false, true }; for (int i = 0; i < skipVisbs.Length; i++) { Assert.Throws<NotSupportedException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg7method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, new Type[] { typeof(string) }, owner, skipVisbs[i]); }); } } [Fact] public void NegTest8() { Type owner = typeof(MethodTestClass6); bool[] skipVisibs = new bool[] { false, true }; for (int i = 0; i < skipVisibs.Length; i++) { Assert.Throws<NotSupportedException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg6method", MethodAttributes.Private | MethodAttributes.Virtual, CallingConventions.Standard, typeof(void), new Type[] { typeof(string) }, owner, skipVisibs[i]); }); } } [Fact] public void NegTest9() { Type owner = typeof(MethodTestClass6); bool[] skipVisibs = new bool[] { false, true }; for (int i = 0; i < skipVisibs.Length; i++) { Assert.Throws<NotSupportedException>(() => { DynamicMethod dynamicMeth = new DynamicMethod("Neg7method", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.VarArgs, typeof(void), new Type[] { typeof(string) }, owner, skipVisibs[i]); }); } } private static Type CreateType() { AssemblyName assemName = new AssemblyName("assemName"); AssemblyBuilder myAssemBuilder = AssemblyBuilder.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run); ModuleBuilder myModB = Utilities.GetModuleBuilder(myAssemBuilder, "Module1"); TypeBuilder myTypeB = myModB.DefineType("testType"); return myTypeB.MakeByRefType(); } } public class MethodTestClass6 { private int _id = 0; public MethodTestClass6(int id) { _id = id; } public int ID { get { return _id; } } } public interface MethodTestInterface6 { } public class MethodMyClass6<T> { } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Remoting; using IronPython.Runtime.Types; using Microsoft.PythonTools.Interpreter; namespace Microsoft.IronPythonTools.Interpreter { class IronPythonType : PythonObject, IAdvancedPythonType { private IPythonFunction _ctors; private string _name; private BuiltinTypeId? _typeId; private IList<IPythonType> _propagateOnCall; private IList<IPythonType> _mro; private PythonMemberType _memberType; private bool? _genericTypeDefinition; internal static IPythonType[] EmptyTypes = new IPythonType[0]; public IronPythonType(IronPythonInterpreter interpreter, ObjectIdentityHandle type) : base(interpreter, type) { } #region IPythonType Members public IPythonFunction GetConstructors() { if (_ctors == null) { var ri = RemoteInterpreter; if (ri != null && !ri.PythonTypeHasNewOrInitMethods(Value)) { _ctors = GetClrOverloads(); } if (_ctors == null) { _ctors = GetMember(null, "__new__") as IPythonFunction; } } return _ctors; } /// <summary> /// Returns the overloads for a normal .NET type /// </summary> private IPythonFunction GetClrOverloads() { var ri = RemoteInterpreter; var ctors = ri != null ? ri.GetPythonTypeConstructors(Value) : null; if (ctors != null) { return new IronPythonConstructorFunction(Interpreter, ctors, this); } return null; } public override PythonMemberType MemberType { get { if (_memberType == PythonMemberType.Unknown) { var ri = RemoteInterpreter; _memberType = ri != null ? ri.GetPythonTypeMemberType(Value) : PythonMemberType.Unknown; } return _memberType; } } public string Name { get { if (_name == null) { var ri = RemoteInterpreter; _name = ri != null ? ri.GetPythonTypeName(Value) : string.Empty; } return _name; } } public string Documentation { get { var ri = RemoteInterpreter; return ri != null ? ri.GetPythonTypeDocumentation(Value) : string.Empty; } } public BuiltinTypeId TypeId { get { if (_typeId == null) { var ri = RemoteInterpreter; _typeId = ri != null ? ri.PythonTypeGetBuiltinTypeId(Value) : BuiltinTypeId.Unknown; } return _typeId.Value; } } public IPythonModule DeclaringModule { get { var ri = RemoteInterpreter; return ri != null ? Interpreter.ImportModule(ri.GetTypeDeclaringModule(Value)) : null; } } public IList<IPythonType> Mro { get { if (_mro == null) { var ri = RemoteInterpreter; var types = ri != null ? ri.GetPythonTypeMro(Value) : new ObjectIdentityHandle[0]; var mro = new IPythonType[types.Length]; for (int i = 0; i < types.Length; ++i) { mro[i] = Interpreter.GetTypeFromType(types[i]); } _mro = mro; } return _mro; } } public bool IsBuiltin { get { return true; } } public IEnumerable<IPythonType> IndexTypes { get { return null; } } public bool IsArray { get { var ri = RemoteInterpreter; return ri != null ? ri.IsPythonTypeArray(Value) : false; } } public IPythonType GetElementType() { var ri = RemoteInterpreter; return ri != null ? Interpreter.GetTypeFromType(ri.GetPythonTypeElementType(Value)) : null; } public IList<IPythonType> GetTypesPropagatedOnCall() { if (_propagateOnCall == null) { var ri = RemoteInterpreter; if (ri != null && ri.IsDelegateType(Value)) { _propagateOnCall = GetEventInvokeArgs(); } else { _propagateOnCall = EmptyTypes; } } return _propagateOnCall == EmptyTypes ? null : _propagateOnCall; } #endregion private IPythonType[] GetEventInvokeArgs() { var ri = RemoteInterpreter; var types = ri != null ? ri.GetEventInvokeArgs(Value) : new ObjectIdentityHandle[0]; var args = new IPythonType[types.Length]; for (int i = 0; i < types.Length; i++) { args[i] = Interpreter.GetTypeFromType(types[i]); } return args; } #region IPythonType Members public bool IsGenericTypeDefinition { get { if (_genericTypeDefinition == null) { var ri = RemoteInterpreter; _genericTypeDefinition = ri != null ? ri.IsPythonTypeGenericTypeDefinition(Value) : false; } return _genericTypeDefinition.Value; } } public IPythonType MakeGenericType(IPythonType[] indexTypes) { // Should we hash on the types here? ObjectIdentityHandle[] types = new ObjectIdentityHandle[indexTypes.Length]; for (int i = 0; i < types.Length; i++) { types[i] = ((IronPythonType)indexTypes[i]).Value; } var ri = RemoteInterpreter; return ri != null ? Interpreter.GetTypeFromType(ri.PythonTypeMakeGenericType(Value, types)) : null; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace System.IO { internal sealed partial class Win32FileSystem : FileSystem { public override int MaxPath { get { return Interop.mincore.MAX_PATH; } } public override int MaxDirectoryPath { get { return Interop.mincore.MAX_DIRECTORY_PATH; } } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES); int errorCode = Interop.mincore.CopyFile(sourceFullPath, destFullPath, !overwrite); if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS) { String fileName = destFullPath; if (errorCode != Interop.mincore.Errors.ERROR_FILE_EXISTS) { // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using (SafeFileHandle handle = Interop.mincore.UnsafeCreateFile(sourceFullPath, Win32FileStream.GENERIC_READ, FileShare.Read, ref secAttrs, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFullPath; } if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED) { if (DirectoryExists(destFullPath)) throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.mincore.Errors.ERROR_ACCESS_DENIED); } } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } [System.Security.SecuritySafeCritical] public override void CreateDirectory(string fullPath) { int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) length--; int lengthRoot = PathInternal.GetRootLength(fullPath); // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessable and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (DirectoryExists(fullPath)) return; List<string> stackDir = new List<string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { String dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing stackDir.Add(dir); else somepathexists = true; while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) i--; i--; } } int count = stackDir.Count; // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES); bool r = true; int firstError = 0; String errorString = fullPath; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { String name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); if (name.Length >= Interop.mincore.MAX_DIRECTORY_PATH) throw new PathTooLongException(SR.IO_PathTooLong); r = Interop.mincore.CreateDirectory(name, ref secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Interop.mincore.Errors.ERROR_ALREADY_EXISTS) firstError = currentError; else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.mincore.Errors.ERROR_ACCESS_DENIED)) { firstError = currentError; errorString = name; } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { String root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, root); return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString); } public override void DeleteFile(System.String fullPath) { bool r = Interop.mincore.DeleteFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) return; else throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override bool DirectoryExists(string fullPath) { int lastError = Interop.mincore.Errors.ERROR_SUCCESS; return DirectoryExists(fullPath, out lastError); } private bool DirectoryExists(String path, out int lastError) { Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); lastError = FillAttributeInfo(path, ref data, false, true); return (lastError == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0); } public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern, (searchTarget & SearchTarget.Files) == SearchTarget.Files, (searchTarget & SearchTarget.Directories) == SearchTarget.Directories, searchOption); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Directories: return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Files: return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Both: return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, "searchTarget"); } } // Returns 0 on success, otherwise a Win32 error code. Note that // classes should use -1 as the uninitialized state for dataInitialized. [System.Security.SecurityCritical] // auto-generated internal static int FillAttributeInfo(String path, ref Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound) { int errorCode = 0; if (tryagain) // someone has a handle to the file open, or other error { Interop.mincore.WIN32_FIND_DATA findData; findData = new Interop.mincore.WIN32_FIND_DATA(); // Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error String tempPath = path.TrimEnd(PathHelpers.DirectorySeparatorChars); // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS); try { bool error = false; SafeFindHandle handle = Interop.mincore.FindFirstFile(tempPath, ref findData); try { if (handle.IsInvalid) { error = true; errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND || errorCode == Interop.mincore.Errors.ERROR_NOT_READY) // floppy device not ready { if (!returnErrorOnNotFound) { // Return default value for backward compatibility errorCode = 0; data.fileAttributes = -1; } } return errorCode; } } finally { // Close the Win32 handle try { handle.Dispose(); } catch { // if we're already returning an error, don't throw another one. if (!error) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } } } finally { Interop.mincore.SetErrorMode(oldMode); } // Copy the information to data data.PopulateFrom(findData); } else { // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. bool success = false; uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS); try { success = Interop.mincore.GetFileAttributesEx(path, Interop.mincore.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data); } finally { Interop.mincore.SetErrorMode(oldMode); } if (!success) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.mincore.Errors.ERROR_NOT_READY) // floppy device not ready { // In case someone latched onto the file. Take the perf hit only for failure return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound); } else { if (!returnErrorOnNotFound) { // Return default value for backward compatibility errorCode = 0; data.fileAttributes = -1; } } } } return errorCode; } public override bool FileExists(System.String fullPath) { Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, true); return (errorCode == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0); } public override FileAttributes GetAttributes(string fullPath) { Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, true); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); return (FileAttributes)data.fileAttributes; } public override string GetCurrentDirectory() { StringBuilder sb = StringBuilderCache.Acquire(Interop.mincore.MAX_PATH + 1); if (Interop.mincore.GetCurrentDirectory(sb.Capacity, sb) == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); String currentDirectory = sb.ToString(); // Note that if we have somehow put our command prompt into short // file name mode (ie, by running edlin or a DOS grep, etc), then // this will return a short file name. if (currentDirectory.IndexOf('~') >= 0) { int r = Interop.mincore.GetLongPathName(currentDirectory, sb, sb.Capacity); if (r == 0 || r >= Interop.mincore.MAX_PATH) { int errorCode = Marshal.GetLastWin32Error(); if (r >= Interop.mincore.MAX_PATH) errorCode = Interop.mincore.Errors.ERROR_FILENAME_EXCED_RANGE; if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.mincore.Errors.ERROR_INVALID_FUNCTION && // by design - enough said. errorCode != Interop.mincore.Errors.ERROR_ACCESS_DENIED) throw Win32Marshal.GetExceptionForWin32Error(errorCode); } currentDirectory = sb.ToString(); } StringBuilderCache.Release(sb); return currentDirectory; } public override DateTimeOffset GetCreationTime(string fullPath) { Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTimeOffset.FromFileTime(dt); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return new Win32FileSystemObject(fullPath, asDirectory); } public override DateTimeOffset GetLastAccessTime(string fullPath) { Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow); return DateTimeOffset.FromFileTime(dt); } public override DateTimeOffset GetLastWriteTime(string fullPath) { Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTimeOffset.FromFileTime(dt); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { if (!Interop.mincore.MoveFile(sourceFullPath, destFullPath)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath); // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public override void MoveFile(string sourceFullPath, string destFullPath) { if (!Interop.mincore.MoveFile(sourceFullPath, destFullPath)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { return new Win32FileStream(fullPath, mode, access, share, bufferSize, options, parent); } [System.Security.SecurityCritical] private static SafeFileHandle OpenHandle(string fullPath, bool asDirectory) { String root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); if (root == fullPath && root[1] == Path.VolumeSeparatorChar) { // intentionally not fullpath, most upstack public APIs expose this as path. throw new ArgumentException(SR.Arg_PathIsVolume, "path"); } Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES); SafeFileHandle handle = Interop.mincore.SafeCreateFile( fullPath, (int)Interop.mincore.GenericOperations.GENERIC_WRITE, FileShare.ReadWrite | FileShare.Delete, ref secAttrs, FileMode.Open, asDirectory ? (int)Interop.mincore.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : (int)FileOptions.None, IntPtr.Zero ); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // NT5 oddity - when trying to open "C:\" as a File, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. if (!asDirectory && errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath))) errorCode = Interop.mincore.Errors.ERROR_ACCESS_DENIED; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return handle; } public override void RemoveDirectory(string fullPath, bool recursive) { // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, true); if (errorCode != 0) { // Ensure we throw a DirectoryNotFoundException. if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.mincore.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0) recursive = false; // We want extended syntax so we can delete "extended" subdirectories and files // (most notably ones with trailing whitespace or periods) RemoveDirectoryHelper(PathInternal.AddExtendedPathPrefix(fullPath), recursive, true); } [System.Security.SecurityCritical] // auto-generated private static void RemoveDirectoryHelper(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound) { bool r; int errorCode; Exception ex = null; // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. // Note the logic to check whether fullPath is a reparse point is // in Delete(String, String, bool), and will set "recursive" to false. // Note that Win32's DeleteFile and RemoveDirectory will just delete // the reparse point itself. if (recursive) { Interop.mincore.WIN32_FIND_DATA data = new Interop.mincore.WIN32_FIND_DATA(); // Open a Find handle using (SafeFindHandle hnd = Interop.mincore.FindFirstFile(fullPath + PathHelpers.DirectorySeparatorCharAsString + "*", ref data)) { if (hnd.IsInvalid) throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); do { bool isDir = (0 != (data.dwFileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY)); if (isDir) { // Skip ".", "..". if (data.cFileName.Equals(".") || data.cFileName.Equals("..")) continue; // Recurse for all directories, unless they are // reparse points. Do not follow mount points nor // symbolic links, but do delete the reparse point // itself. bool shouldRecurse = (0 == (data.dwFileAttributes & (int)FileAttributes.ReparsePoint)); if (shouldRecurse) { string newFullPath = Path.Combine(fullPath, data.cFileName); try { RemoveDirectoryHelper(newFullPath, recursive, false); } catch (Exception e) { if (ex == null) ex = e; } } else { // Check to see if this is a mount point, and // unmount it. if (data.dwReserved0 == Interop.mincore.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT) { // Use full path plus a trailing '\' String mountPoint = Path.Combine(fullPath, data.cFileName + PathHelpers.DirectorySeparatorCharAsString); if (!Interop.mincore.DeleteVolumeMountPoint(mountPoint)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS && errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } // RemoveDirectory on a symbolic link will // remove the link itself. String reparsePoint = Path.Combine(fullPath, data.cFileName); r = Interop.mincore.RemoveDirectory(reparsePoint); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } else { String fileName = Path.Combine(fullPath, data.cFileName); r = Interop.mincore.DeleteFile(fileName); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } while (Interop.mincore.FindNextFile(hnd, ref data)); // Make sure we quit with a sensible error. errorCode = Marshal.GetLastWin32Error(); } if (ex != null) throw ex; if (errorCode != 0 && errorCode != Interop.mincore.Errors.ERROR_NO_MORE_FILES) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } r = Interop.mincore.RemoveDirectory(fullPath); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) // A dubious error code. errorCode = Interop.mincore.Errors.ERROR_PATH_NOT_FOUND; // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED) throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // don't throw the DirectoryNotFoundException since this is a subdir and // there could be a race condition between two Directory.Delete callers if (errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound) return; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetAttributes(string fullPath, FileAttributes attributes) { SetAttributesInternal(fullPath, attributes); } private static void SetAttributesInternal(string fullPath, FileAttributes attributes) { bool r = Interop.mincore.SetFileAttributes(fullPath, (int)attributes); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.mincore.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_InvalidFileAttrs, "attributes"); throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetCreationTimeInternal(fullPath, time, asDirectory); } private static void SetCreationTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.mincore.SetFileTime(handle, creationTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetCurrentDirectory(string fullPath) { if (!Interop.mincore.SetCurrentDirectory(fullPath)) { // If path doesn't exist, this sets last error to 2 (File // not Found). LEGACY: This may potentially have worked correctly // on Win9x, maybe. int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.mincore.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastAccessTimeInternal(fullPath, time, asDirectory); } private static void SetLastAccessTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.mincore.SetFileTime(handle, lastAccessTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastWriteTimeInternal(fullPath, time, asDirectory); } private static void SetLastWriteTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.mincore.SetFileTime(handle, lastWriteTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } } }
// // eval.cs: Evaluation and Hosting API for the C# compiler // // Authors: // Miguel de Icaza (miguel@gnome.org) // Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com) // Copyright 2004-2011 Novell, Inc // using System; using System.Threading; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.IO; using System.Text; using System.Linq; namespace Mono.CSharp { /// <summary> /// Evaluator: provides an API to evaluate C# statements and /// expressions dynamically. /// </summary> /// <remarks> /// This class exposes static methods to evaluate expressions in the /// current program. /// /// To initialize the evaluator with a number of compiler /// options call the Init(string[]args) method with a set of /// command line options that the compiler recognizes. /// /// To interrupt execution of a statement, you can invoke the /// Evaluator.Interrupt method. /// </remarks> public class Evaluator { enum ParseMode { // Parse silently, do not output any error messages Silent, // Report errors during parse ReportErrors, // Auto-complete, means that the tokenizer will start producing // GETCOMPLETIONS tokens when it reaches a certain point. GetCompletions } static object evaluator_lock = new object (); static volatile bool invoking; static int count; static Thread invoke_thread; readonly Dictionary<string, Tuple<FieldSpec, FieldInfo>> fields; Type base_class; bool inited; readonly CompilerContext ctx; readonly ModuleContainer module; readonly ReflectionImporter importer; // TODO: somehow merge with module NamespaceEntry ns; public Evaluator (CompilerSettings settings, Report report) { ctx = new CompilerContext (settings, report); module = new ModuleContainer (ctx); module.Evaluator = this; // FIXME: Importer needs this assembly for internalsvisibleto module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator")); importer = new ReflectionImporter (module, ctx.BuildinTypes); InteractiveBaseClass = typeof (InteractiveBase); fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> (); } void Init () { var loader = new DynamicLoader (importer, ctx); CompilerCallableEntryPoint.Reset (); RootContext.ToplevelTypes = module; //var startup_files = new List<string> (); //foreach (CompilationUnit file in Location.SourceFiles) // startup_files.Add (file.Path); loader.LoadReferences (module); ctx.BuildinTypes.CheckDefinitions (module); module.InitializePredefinedTypes (); inited = true; } static void Reset () { CompilerCallableEntryPoint.PartialReset (); Location.AddFile (null, "{interactive}"); Location.Initialize (); } /// <summary> /// If true, turns type expressions into valid expressions /// and calls the describe method on it /// </summary> public bool DescribeTypeExpressions; /// <summary> /// The base class for the classes that host the user generated code /// </summary> /// <remarks> /// /// This is the base class that will host the code /// executed by the Evaluator. By default /// this is the Mono.CSharp.InteractiveBase class /// which is useful for interactive use. /// /// By changing this property you can control the /// base class and the static members that are /// available to your evaluated code. /// </remarks> public Type InteractiveBaseClass { get { return base_class; } set { base_class = value; if (value != null && typeof (InteractiveBase).IsAssignableFrom (value)) InteractiveBase.Evaluator = this; } } /// <summary> /// Interrupts the evaluation of an expression executing in Evaluate. /// </summary> /// <remarks> /// Use this method to interrupt long-running invocations. /// </remarks> public void Interrupt () { if (!inited || !invoking) return; if (invoke_thread != null) invoke_thread.Abort (); } /// <summary> /// Compiles the input string and returns a delegate that represents the compiled code. /// </summary> /// <remarks> /// /// Compiles the input string as a C# expression or /// statement, unlike the Evaluate method, the /// resulting delegate can be invoked multiple times /// without incurring in the compilation overhead. /// /// If the return value of this function is null, /// this indicates that the parsing was complete. /// If the return value is a string it indicates /// that the input string was partial and that the /// invoking code should provide more code before /// the code can be successfully compiled. /// /// If you know that you will always get full expressions or /// statements and do not care about partial input, you can use /// the other Compile overload. /// /// On success, in addition to returning null, the /// compiled parameter will be set to the delegate /// that can be invoked to execute the code. /// /// </remarks> public string Compile (string input, out CompiledMethod compiled) { if (input == null || input.Length == 0){ compiled = null; return null; } lock (evaluator_lock){ if (!inited) Init (); else ctx.Report.Printer.Reset (); bool partial_input; CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input); if (parser == null){ compiled = null; if (partial_input) return input; ParseString (ParseMode.ReportErrors, input, out partial_input); return null; } Class parser_result = parser.InteractiveResult; compiled = CompileBlock (parser_result, parser.undo, ctx.Report); return null; } } /// <summary> /// Compiles the input string and returns a delegate that represents the compiled code. /// </summary> /// <remarks> /// /// Compiles the input string as a C# expression or /// statement, unlike the Evaluate method, the /// resulting delegate can be invoked multiple times /// without incurring in the compilation overhead. /// /// This method can only deal with fully formed input /// strings and does not provide a completion mechanism. /// If you must deal with partial input (for example for /// interactive use) use the other overload. /// /// On success, a delegate is returned that can be used /// to invoke the method. /// /// </remarks> public CompiledMethod Compile (string input) { CompiledMethod compiled; // Ignore partial inputs if (Compile (input, out compiled) != null){ // Error, the input was partial. return null; } // Either null (on error) or the compiled method. return compiled; } /// <summary> /// Evaluates and expression or statement and returns any result values. /// </summary> /// <remarks> /// Evaluates the input string as a C# expression or /// statement. If the input string is an expression /// the result will be stored in the result variable /// and the result_set variable will be set to true. /// /// It is necessary to use the result/result_set /// pair to identify when a result was set (for /// example, execution of user-provided input can be /// an expression, a statement or others, and /// result_set would only be set if the input was an /// expression. /// /// If the return value of this function is null, /// this indicates that the parsing was complete. /// If the return value is a string, it indicates /// that the input is partial and that the user /// should provide an updated string. /// </remarks> public string Evaluate (string input, out object result, out bool result_set) { CompiledMethod compiled; result_set = false; result = null; input = Compile (input, out compiled); if (input != null) return input; if (compiled == null) return null; // // The code execution does not need to keep the compiler lock // object retval = typeof (QuitValue); try { invoke_thread = System.Threading.Thread.CurrentThread; invoking = true; compiled (ref retval); } catch (ThreadAbortException e){ //Thread.ResetAbort (); Console.WriteLine ("Interrupted!\n{0}", e); } finally { invoking = false; } // // We use a reference to a compiler type, in this case // Driver as a flag to indicate that this was a statement // if (!ReferenceEquals (retval, typeof (QuitValue))) { result_set = true; result = retval; } return null; } public string [] GetCompletions (string input, out string prefix) { prefix = ""; if (input == null || input.Length == 0) return null; lock (evaluator_lock){ if (!inited) Init (); bool partial_input; CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input); if (parser == null){ if (CSharpParser.yacc_verbose_flag != 0) Console.WriteLine ("DEBUG: No completions available"); return null; } Class parser_result = parser.InteractiveResult; #if NET_4_0 var access = AssemblyBuilderAccess.Run; #else var access = AssemblyBuilderAccess.Run; #endif var a = new AssemblyDefinitionDynamic (module, "completions"); a.Create (AppDomain.CurrentDomain, access); module.SetDeclaringAssembly (a); // Need to setup MemberCache parser_result.CreateType (); var method = parser_result.Methods[0] as Method; BlockContext bc = new BlockContext (method, method.Block, TypeManager.void_type); try { method.Block.Resolve (null, bc, method); } catch (CompletionResult cr) { prefix = cr.BaseText; return cr.Result; } } return null; } /// <summary> /// Executes the given expression or statement. /// </summary> /// <remarks> /// Executes the provided statement, returns true /// on success, false on parsing errors. Exceptions /// might be thrown by the called code. /// </remarks> public bool Run (string statement) { object result; bool result_set; return Evaluate (statement, out result, out result_set) == null; } /// <summary> /// Evaluates and expression or statement and returns the result. /// </summary> /// <remarks> /// Evaluates the input string as a C# expression or /// statement and returns the value. /// /// This method will throw an exception if there is a syntax error, /// of if the provided input is not an expression but a statement. /// </remarks> public object Evaluate (string input) { object result; bool result_set; string r = Evaluate (input, out result, out result_set); if (r != null) throw new ArgumentException ("Syntax error on input: partial input"); if (result_set == false) throw new ArgumentException ("The expression did not set a result"); return result; } enum InputKind { EOF, StatementOrExpression, CompilationUnit, Error } // // Deambiguates the input string to determine if we // want to process a statement or if we want to // process a compilation unit. // // This is done using a top-down predictive parser, // since the yacc/jay parser can not deambiguage this // without more than one lookahead token. There are very // few ambiguities. // InputKind ToplevelOrStatement (SeekableStreamReader seekable) { Tokenizer tokenizer = new Tokenizer (seekable, (CompilationUnit) Location.SourceFiles [0], ctx); int t = tokenizer.token (); switch (t){ case Token.EOF: return InputKind.EOF; // These are toplevels case Token.EXTERN: case Token.OPEN_BRACKET: case Token.ABSTRACT: case Token.CLASS: case Token.ENUM: case Token.INTERFACE: case Token.INTERNAL: case Token.NAMESPACE: case Token.PRIVATE: case Token.PROTECTED: case Token.PUBLIC: case Token.SEALED: case Token.STATIC: case Token.STRUCT: return InputKind.CompilationUnit; // Definitely expression case Token.FIXED: case Token.BOOL: case Token.BYTE: case Token.CHAR: case Token.DECIMAL: case Token.DOUBLE: case Token.FLOAT: case Token.INT: case Token.LONG: case Token.NEW: case Token.OBJECT: case Token.SBYTE: case Token.SHORT: case Token.STRING: case Token.UINT: case Token.ULONG: return InputKind.StatementOrExpression; // These need deambiguation help case Token.USING: t = tokenizer.token (); if (t == Token.EOF) return InputKind.EOF; if (t == Token.IDENTIFIER) return InputKind.CompilationUnit; return InputKind.StatementOrExpression; // Distinguish between: // delegate opt_anonymous_method_signature block // delegate type case Token.DELEGATE: t = tokenizer.token (); if (t == Token.EOF) return InputKind.EOF; if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE) return InputKind.StatementOrExpression; return InputKind.CompilationUnit; // Distinguih between: // unsafe block // unsafe as modifier of a type declaration case Token.UNSAFE: t = tokenizer.token (); if (t == Token.EOF) return InputKind.EOF; if (t == Token.OPEN_PARENS) return InputKind.StatementOrExpression; return InputKind.CompilationUnit; // These are errors: we list explicitly what we had // from the grammar, ERROR and then everything else case Token.READONLY: case Token.OVERRIDE: case Token.ERROR: return InputKind.Error; // This catches everything else allowed by // expressions. We could add one-by-one use cases // if needed. default: return InputKind.StatementOrExpression; } } // // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // CSharpParser ParseString (ParseMode mode, string input, out bool partial_input) { partial_input = false; Reset (); Tokenizer.LocatedToken.Initialize (); Stream s = new MemoryStream (Encoding.UTF8.GetBytes (input)); SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.UTF8); InputKind kind = ToplevelOrStatement (seekable); if (kind == InputKind.Error){ if (mode == ParseMode.ReportErrors) ctx.Report.Error (-25, "Detection Parsing Error"); partial_input = false; return null; } if (kind == InputKind.EOF){ if (mode == ParseMode.ReportErrors) Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true"); partial_input = true; return null; } seekable.Position = 0; if (ns == null) ns = new NamespaceEntry (module, null, Location.SourceFiles[0], null); ns.DeclarationFound = false; CSharpParser parser = new CSharpParser (seekable, Location.SourceFiles [0], module, ns); if (kind == InputKind.StatementOrExpression){ parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; ctx.Settings.StatementMode = true; } else { parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; ctx.Settings.StatementMode = false; } if (mode == ParseMode.GetCompletions) parser.Lexer.CompleteOnEOF = true; ReportPrinter old_printer = null; if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0) old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null)); try { parser.parse (); } finally { if (ctx.Report.Errors != 0){ if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF) partial_input = true; if (parser.undo != null) parser.undo.ExecuteUndo (); parser = null; } if (old_printer != null) ctx.Report.SetPrinter (old_printer); } return parser; } CompiledMethod CompileBlock (Class host, Undo undo, Report Report) { string current_debug_name = "eval-" + count + ".dll"; ++count; #if STATIC throw new NotSupportedException (); #else AssemblyDefinitionDynamic assembly; AssemblyBuilderAccess access; /* if (Environment.GetEnvironmentVariable ("SAVE") != null) { access = AssemblyBuilderAccess.RunAndSave; assembly = new AssemblyDefinitionDynamic (module, current_debug_name, current_debug_name); assembly.Importer = importer; } else*/ { #if NET_4_0 access = AssemblyBuilderAccess.Run; #else access = AssemblyBuilderAccess.Run; #endif assembly = new AssemblyDefinitionDynamic (module, current_debug_name); } assembly.Create (AppDomain.CurrentDomain, access); Method expression_method; if (host != null) { var base_class_imported = importer.ImportType (base_class); var baseclass_list = new List<FullNamedExpression> (1) { new TypeExpression (base_class_imported, host.Location) }; host.AddBasesForPart (host, baseclass_list); host.CreateType (); host.DefineType (); host.Define (); expression_method = (Method) host.Methods[0]; } else { expression_method = null; } module.CreateType (); module.Define (); if (Report.Errors != 0){ if (undo != null) undo.ExecuteUndo (); return null; } if (host != null){ host.EmitType (); } module.Emit (); if (Report.Errors != 0){ if (undo != null) undo.ExecuteUndo (); return null; } module.CloseType (); if (host != null) host.CloseType (); //if (access == AssemblyBuilderAccess.RunAndSave) // assembly.Save (); if (host == null) return null; // // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant // work from MethodBuilders. Retarded, I know. // var tt = assembly.Builder.GetType (host.TypeBuilder.Name); var mi = tt.GetMethod (expression_method.Name); if (host.Fields != null) { // // We need to then go from FieldBuilder to FieldInfo // or reflection gets confused (it basically gets confused, and variables override each // other). // foreach (Field field in host.Fields) { var fi = tt.GetField (field.Name); Tuple<FieldSpec, FieldInfo> old; // If a previous value was set, nullify it, so that we do // not leak memory if (fields.TryGetValue (field.Name, out old)) { if (old.Item1.MemberType.IsStruct) { // // TODO: Clear fields for structs // } else { try { old.Item2.SetValue (null, null); } catch { } } } fields[field.Name] = Tuple.Create (field.Spec, fi); } } return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi); #endif } /// <summary> /// A sentinel value used to indicate that no value was /// was set by the compiled function. This is used to /// differentiate between a function not returning a /// value and null. /// </summary> internal static class QuitValue { } internal Tuple<FieldSpec, FieldInfo> LookupField (string name) { Tuple<FieldSpec, FieldInfo> fi; fields.TryGetValue (name, out fi); return fi; } static string Quote (string s) { if (s.IndexOf ('"') != -1) s = s.Replace ("\"", "\\\""); return "\"" + s + "\""; } public string GetUsing () { if (ns == null) return null; StringBuilder sb = new StringBuilder (); // TODO: //foreach (object x in ns.using_alias_list) // sb.AppendFormat ("using {0};\n", x); foreach (var ue in ns.Usings) { sb.AppendFormat ("using {0};", ue.ToString ()); sb.Append (Environment.NewLine); } return sb.ToString (); } internal ICollection<string> GetUsingList () { var res = new List<string> (); foreach (var ue in ns.Usings) res.Add (ue.ToString ()); return res; } internal string [] GetVarNames () { lock (evaluator_lock){ return new List<string> (fields.Keys).ToArray (); } } public string GetVars () { lock (evaluator_lock){ StringBuilder sb = new StringBuilder (); foreach (var de in fields){ var fi = LookupField (de.Key); object value; try { value = fi.Item2.GetValue (null); if (value is string) value = Quote ((string)value); } catch { value = "<error reading value>"; } sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value); sb.AppendLine (); } return sb.ToString (); } } /// <summary> /// Loads the given assembly and exposes the API to the user. /// </summary> public void LoadAssembly (string file) { var loader = new DynamicLoader (importer, ctx); var assembly = loader.LoadAssemblyFile (file); if (assembly == null) return; lock (evaluator_lock){ importer.ImportAssembly (assembly, module.GlobalRootNamespace); } } /// <summary> /// Exposes the API of the given assembly to the Evaluator /// </summary> public void ReferenceAssembly (Assembly a) { lock (evaluator_lock){ importer.ImportAssembly (a, module.GlobalRootNamespace); } } } /// <summary> /// A delegate that can be used to invoke the /// compiled expression or statement. /// </summary> /// <remarks> /// Since the Compile methods will compile /// statements and expressions into the same /// delegate, you can tell if a value was returned /// by checking whether the returned value is of type /// NoValueSet. /// </remarks> public delegate void CompiledMethod (ref object retvalue); /// <summary> /// The default base class for every interaction line /// </summary> /// <remarks> /// The expressions and statements behave as if they were /// a static method of this class. The InteractiveBase class /// contains a number of useful methods, but can be overwritten /// by setting the InteractiveBaseType property in the Evaluator /// </remarks> public class InteractiveBase { /// <summary> /// Determines where the standard output of methods in this class will go. /// </summary> public static TextWriter Output = Console.Out; /// <summary> /// Determines where the standard error of methods in this class will go. /// </summary> public static TextWriter Error = Console.Error; /// <summary> /// The primary prompt used for interactive use. /// </summary> public static string Prompt = "csharp> "; /// <summary> /// The secondary prompt used for interactive use (used when /// an expression is incomplete). /// </summary> public static string ContinuationPrompt = " > "; /// <summary> /// Used to signal that the user has invoked the `quit' statement. /// </summary> public static bool QuitRequested; public static Evaluator Evaluator; /// <summary> /// Shows all the variables defined so far. /// </summary> static public void ShowVars () { Output.Write (Evaluator.GetVars ()); Output.Flush (); } /// <summary> /// Displays the using statements in effect at this point. /// </summary> static public void ShowUsing () { Output.Write (Evaluator.GetUsing ()); Output.Flush (); } /// <summary> /// Times the execution of the given delegate /// </summary> static public TimeSpan Time (Action a) { DateTime start = DateTime.Now; a (); return DateTime.Now - start; } /// <summary> /// Loads the assemblies from a package /// </summary> /// <remarks> /// Loads the assemblies from a package. This is equivalent /// to passing the -pkg: command line flag to the C# compiler /// on the command line. /// </remarks> static public void LoadPackage (string pkg) { if (pkg == null){ Error.WriteLine ("Invalid package specified"); return; } string pkgout = "";// Driver.GetPackageFlags(pkg, null); string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}). Split (new Char [] { ' ', '\t'}); foreach (string s in xargs){ if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){ string lib = s.Substring (s.IndexOf (':')+1); Evaluator.LoadAssembly (lib); continue; } } } /// <summary> /// Loads the assembly /// </summary> /// <remarks> /// Loads the specified assembly and makes its types /// available to the evaluator. This is equivalent /// to passing the -pkg: command line flag to the C# /// compiler on the command line. /// </remarks> static public void LoadAssembly (string assembly) { Evaluator.LoadAssembly (assembly); } static public void print (string obj) { Output.WriteLine (obj); } static public void print (string fmt, params object [] args) { Output.WriteLine (fmt, args); } /// <summary> /// Returns a list of available static methods. /// </summary> static public string help { get { return "Static methods:\n" + " Describe (object) - Describes the object's type\n" + " LoadPackage (package); - Loads the given Package (like -pkg:FILE)\n" + " LoadAssembly (assembly) - Loads the given assembly (like -r:ASSEMBLY)\n" + " ShowVars (); - Shows defined local variables.\n" + " ShowUsing (); - Show active using declarations.\n" + " Prompt - The prompt used by the C# shell\n" + " ContinuationPrompt - The prompt for partial input\n" + " Time(() -> { }) - Times the specified code\n" + " print (obj) - Shorthand for Console.WriteLine\n" + " quit; - You'll never believe it - this quits the repl!\n" + " help; - This help text\n"; } } /// <summary> /// Indicates to the read-eval-print-loop that the interaction should be finished. /// </summary> static public object quit { get { QuitRequested = true; // To avoid print null at the exit return typeof (Evaluator.QuitValue); } } #if !NET_2_1 /// <summary> /// Describes an object or a type. /// </summary> /// <remarks> /// This method will show a textual representation /// of the object's type. If the object is a /// System.Type it renders the type directly, /// otherwise it renders the type returned by /// invoking GetType on the object. /// </remarks> static public string Describe (object x) { if (x == null) return "<null>"; var type = x as Type ?? x.GetType (); StringWriter sw = new StringWriter (); new Outline (type, sw, true, false, false).OutlineType (); return sw.ToString (); } #endif } class HoistedEvaluatorVariable : HoistedVariable { public HoistedEvaluatorVariable (Field field) : base (null, field) { } public override void EmitSymbolInfo () { } protected override FieldExpr GetFieldExpression (EmitContext ec) { return new FieldExpr (field, field.Location); } } /// <summary> /// A class used to assign values if the source expression is not void /// /// Used by the interactive shell to allow it to call this code to set /// the return value for an invocation. /// </summary> class OptionalAssign : SimpleAssign { public OptionalAssign (Expression t, Expression s, Location loc) : base (t, s, loc) { } protected override Expression DoResolve (ResolveContext ec) { CloneContext cc = new CloneContext (); Expression clone = source.Clone (cc); clone = clone.Resolve (ec); if (clone == null) return null; // // A useful feature for the REPL: if we can resolve the expression // as a type, Describe the type; // if (ec.Module.Evaluator.DescribeTypeExpressions){ var old_printer = ec.Report.SetPrinter (new SessionReportPrinter ()); Expression tclone; try { tclone = source.Clone (cc); tclone = tclone.Resolve (ec, ResolveFlags.Type); if (ec.Report.Errors > 0) tclone = null; } finally { ec.Report.SetPrinter (old_printer); } if (tclone != null) { Arguments args = new Arguments (1); args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location))); return new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec); } } // This means its really a statement. if (clone.Type == TypeManager.void_type || clone is DynamicInvocation || clone is Assign) { return clone; } source = clone; return base.DoResolve (ec); } } public class Undo { List<Action> undo_actions; public Undo () { } public void AddTypeContainer (TypeContainer current_container, TypeContainer tc) { if (current_container == tc){ Console.Error.WriteLine ("Internal error: inserting container into itself"); return; } if (undo_actions == null) undo_actions = new List<Action> (); var existing = current_container.Types.FirstOrDefault (l => l.MemberName.Basename == tc.MemberName.Basename); if (existing != null) { current_container.RemoveTypeContainer (existing); existing.NamespaceEntry.SlaveDeclSpace.RemoveTypeContainer (existing); undo_actions.Add (() => current_container.AddTypeContainer (existing)); } undo_actions.Add (() => current_container.RemoveTypeContainer (tc)); } public void ExecuteUndo () { if (undo_actions == null) return; foreach (var p in undo_actions){ p (); } undo_actions = null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class ExceptTests { private const int DuplicateFactor = 4; public static IEnumerable<object[]> ExceptUnorderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => 0 - r / 2, rightCounts.Cast<int>())) { yield return parms.Take(4).Concat(new object[] { (int)parms[3] + (int)parms[4], Math.Max(0, (int)parms[1] - ((int)parms[3] + 1) / 2) }).ToArray(); } } public static IEnumerable<object[]> ExceptData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in ExceptUnorderedData(leftCounts, rightCounts)) { parms[0] = ((Labeled<ParallelQuery<int>>)parms[0]).Order(); yield return parms; } } public static IEnumerable<object[]> ExceptSourceMultipleData(int[] counts) { foreach (int leftCount in counts.Cast<int>()) { ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered(); foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor * 2, leftCount), 2 * Math.Max(DuplicateFactor, leftCount) }) { int rightStart = 0 - rightCount / 2; yield return new object[] { left, leftCount, ParallelEnumerable.Range(rightStart, rightCount), rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) }; } } } // // Except // [Theory] [MemberData("ExceptUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(start, count); foreach (int i in leftQuery.Except(rightQuery)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("ExceptUnorderedData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = start; foreach (int i in leftQuery.Except(rightQuery)) { Assert.Equal(seen++, i); } Assert.Equal(count + start, seen); } [Theory] [OuterLoop] [MemberData("ExceptData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(leftQuery.Except(rightQuery).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("ExceptUnorderedData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = start; Assert.All(leftQuery.Except(rightQuery).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(count + start, seen); } [Theory] [OuterLoop] [MemberData("ExceptData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount); foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2))) { seen.Add(i % (DuplicateFactor * 2)); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("ExceptUnorderedData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered_Distinct(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); int seen = expectedCount == 0 ? 0 : leftCount - expectedCount; foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2))) { Assert.Equal(seen++, i); } Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen); } [Theory] [OuterLoop] [MemberData("ExceptData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Distinct(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount); Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("ExceptData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Except_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); int seen = expectedCount == 0 ? 0 : leftCount - expectedCount; Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen); } [Theory] [OuterLoop] [MemberData("ExceptData", new int[] { 1024, 1024 * 16 }, new int[] { 0, 1024, 1024 * 32 })] public static void Except_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Distinct_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData("ExceptSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Except_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { // The difference between this test and the previous, is that it's not possible to // get non-unique results from ParallelEnumerable.Range()... // Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar, // or via a comparator that considers some elements equal. IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(leftQuery.AsUnordered().Except(rightQuery), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("ExceptSourceMultipleData", (object)(new int[] { 1024, 1024 * 16 }))] public static void Except_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count); } [Theory] [MemberData("ExceptSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Except_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { int seen = start; Assert.All(leftQuery.Except(rightQuery), x => Assert.Equal(seen++, x)); Assert.Equal(start + count, seen); } [Theory] [OuterLoop] [MemberData("ExceptSourceMultipleData", (object)(new int[] { 1024, 1024 * 16 }))] public static void Except_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count); } [Fact] public static void Except_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void Except_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Except(ParallelEnumerable.Range(0, 1).WithCancellation(t))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Except(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Except(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Except(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default))); } [Fact] public static void Except_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Except(null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Except(null, EqualityComparer<int>.Default)); } } }